language
stringclasses 1
value | repo
stringclasses 60
values | path
stringlengths 22
294
| class_span
dict | source
stringlengths 13
1.16M
| target
stringlengths 1
113
|
|---|---|---|---|---|---|
java
|
bumptech__glide
|
library/test/src/test/java/com/bumptech/glide/manager/RequestManagerRetrieverTest.java
|
{
"start": 13444,
"end": 14011
}
|
class ____
extends FragmentHostCallback<RequestManagerRetrieverTest> {
private final Context context;
NonActivityHostCallback(Context context) {
super(context, new Handler(Looper.getMainLooper()), /* windowAnimations= */ 0);
this.context = context;
}
@Override
public LayoutInflater onGetLayoutInflater() {
return LayoutInflater.from(context).cloneInContext(context);
}
@Override
public RequestManagerRetrieverTest onGetHost() {
return RequestManagerRetrieverTest.this;
}
}
}
|
NonActivityHostCallback
|
java
|
greenrobot__greendao
|
tests/DaoTest/src/androidTest/java/org/greenrobot/greendao/daotest/encrypted/EncryptionSimpleEntityTest.java
|
{
"start": 1175,
"end": 2004
}
|
class ____ extends SimpleEntityTest {
@Override
protected Database createDatabase() {
return EncryptedDbUtils.createDatabase(getContext(), null, "password");
}
@Override
public void testInsertTwice() {
try {
super.testInsertTwice();
fail("Expected SQLCipher exception");
} catch (SQLiteConstraintException ex) {
// OK, expected
}
}
public void testEncryptedDbUsed() {
EncryptedDbUtils.assertEncryptedDbUsed(db);
}
public void testOrderAscString() {
// SQLCipher 3.5.0 does not understand "COLLATE LOCALIZED ASC" and crashed here initially
List<SimpleEntity> result = dao.queryBuilder().orderAsc(Properties.SimpleString).list();
assertEquals(0, result.size());
}
}
|
EncryptionSimpleEntityTest
|
java
|
resilience4j__resilience4j
|
resilience4j-spring/src/main/java/io/github/resilience4j/fallback/FallbackDecorator.java
|
{
"start": 712,
"end": 754
}
|
interface ____ FallbackDecorator
*/
public
|
of
|
java
|
apache__kafka
|
trogdor/src/main/java/org/apache/kafka/trogdor/task/NoOpTaskWorker.java
|
{
"start": 1067,
"end": 1820
}
|
class ____ implements TaskWorker {
private static final Logger log = LoggerFactory.getLogger(NoOpTaskWorker.class);
private final String id;
private WorkerStatusTracker status;
public NoOpTaskWorker(String id) {
this.id = id;
}
@Override
public void start(Platform platform, WorkerStatusTracker status,
KafkaFutureImpl<String> errorFuture) throws Exception {
log.info("{}: Activating NoOpTask.", id);
this.status = status;
this.status.update(new TextNode("active"));
}
@Override
public void stop(Platform platform) throws Exception {
log.info("{}: Deactivating NoOpTask.", id);
this.status.update(new TextNode("done"));
}
}
|
NoOpTaskWorker
|
java
|
apache__flink
|
flink-test-utils-parent/flink-test-utils-connector/src/main/java/org/apache/flink/test/util/source/TestSplitEnumerator.java
|
{
"start": 1742,
"end": 3135
}
|
class ____<EnumChkptState>
implements SplitEnumerator<TestSplit, EnumChkptState> {
protected final SplitEnumeratorContext<TestSplit> context;
protected final EnumChkptState checkpointState;
public TestSplitEnumerator(
SplitEnumeratorContext<TestSplit> context, EnumChkptState checkpointState) {
this.context = context;
this.checkpointState = checkpointState;
}
@Override
public void start() {
// No-op implementation
}
@Override
public void handleSplitRequest(int subtaskId, String requesterHostname) {
// Most common case: split request means reader is ready for work
addReader(subtaskId);
}
@Override
public void addSplitsBack(List<TestSplit> splits, int subtaskId) {
// No-op implementation
}
@Override
public void addReader(int subtaskId) {
// Signal no more splits to ensure immediate completion
context.signalNoMoreSplits(subtaskId);
}
@Override
public void close() {
// No-op implementation
}
/**
* Subclasses should override this method to provide their checkpoint state. The default
* implementation returns the checkpoint state passed in the constructor.
*/
@Override
public EnumChkptState snapshotState(long checkpointId) {
return checkpointState;
}
}
|
TestSplitEnumerator
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/strategy/TestingSchedulingTopology.java
|
{
"start": 1884,
"end": 14408
}
|
class ____ implements SchedulingTopology {
// Use linked map here to so we can get the values in inserted order
private final Map<ExecutionVertexID, TestingSchedulingExecutionVertex>
schedulingExecutionVertices = new LinkedHashMap<>();
private final Map<IntermediateResultPartitionID, TestingSchedulingResultPartition>
schedulingResultPartitions = new HashMap<>();
private Map<ExecutionVertexID, TestingSchedulingPipelinedRegion> vertexRegions;
@Override
public Iterable<TestingSchedulingExecutionVertex> getVertices() {
return Collections.unmodifiableCollection(schedulingExecutionVertices.values());
}
@Override
public TestingSchedulingExecutionVertex getVertex(final ExecutionVertexID executionVertexId) {
final TestingSchedulingExecutionVertex executionVertex =
schedulingExecutionVertices.get(executionVertexId);
if (executionVertex == null) {
throw new IllegalArgumentException("can not find vertex: " + executionVertexId);
}
return executionVertex;
}
@Override
public TestingSchedulingResultPartition getResultPartition(
final IntermediateResultPartitionID intermediateResultPartitionId) {
final TestingSchedulingResultPartition resultPartition =
schedulingResultPartitions.get(intermediateResultPartitionId);
if (resultPartition == null) {
throw new IllegalArgumentException(
"can not find partition: " + intermediateResultPartitionId);
}
return resultPartition;
}
@Override
public void registerSchedulingTopologyListener(SchedulingTopologyListener listener) {}
@Override
public Iterable<SchedulingPipelinedRegion> getAllPipelinedRegions() {
return new HashSet<>(getVertexRegions().values());
}
@Override
public SchedulingPipelinedRegion getPipelinedRegionOfVertex(ExecutionVertexID vertexId) {
return getVertexRegions().get(vertexId);
}
private Map<ExecutionVertexID, TestingSchedulingPipelinedRegion> getVertexRegions() {
if (vertexRegions == null) {
generatePipelinedRegions();
}
return vertexRegions;
}
private void generatePipelinedRegions() {
vertexRegions = new HashMap<>();
final Set<Set<SchedulingExecutionVertex>> rawRegions =
SchedulingPipelinedRegionComputeUtil.computePipelinedRegions(
getVertices(), this::getVertex, this::getResultPartition);
for (Set<SchedulingExecutionVertex> rawRegion : rawRegions) {
final Set<TestingSchedulingExecutionVertex> vertices =
rawRegion.stream()
.map(vertex -> schedulingExecutionVertices.get(vertex.getId()))
.collect(Collectors.toSet());
final TestingSchedulingPipelinedRegion region =
new TestingSchedulingPipelinedRegion(vertices);
for (TestingSchedulingExecutionVertex vertex : vertices) {
vertexRegions.put(vertex.getId(), region);
}
}
}
private void resetPipelinedRegions() {
vertexRegions = null;
}
void addSchedulingExecutionVertex(TestingSchedulingExecutionVertex schedulingExecutionVertex) {
checkState(!schedulingExecutionVertices.containsKey(schedulingExecutionVertex.getId()));
schedulingExecutionVertices.put(
schedulingExecutionVertex.getId(), schedulingExecutionVertex);
updateVertexResultPartitions(schedulingExecutionVertex);
resetPipelinedRegions();
}
private void updateVertexResultPartitions(
final TestingSchedulingExecutionVertex schedulingExecutionVertex) {
addSchedulingResultPartitions(schedulingExecutionVertex.getConsumedResults());
addSchedulingResultPartitions(schedulingExecutionVertex.getProducedResults());
}
private void addSchedulingResultPartitions(
final Iterable<TestingSchedulingResultPartition> resultPartitions) {
for (TestingSchedulingResultPartition schedulingResultPartition : resultPartitions) {
schedulingResultPartitions.put(
schedulingResultPartition.getId(), schedulingResultPartition);
}
}
void addSchedulingExecutionVertices(List<TestingSchedulingExecutionVertex> vertices) {
for (TestingSchedulingExecutionVertex vertex : vertices) {
addSchedulingExecutionVertex(vertex);
}
}
public SchedulingExecutionVerticesBuilder addExecutionVertices() {
return new SchedulingExecutionVerticesBuilder();
}
public TestingSchedulingExecutionVertex newExecutionVertex() {
return newExecutionVertex(new JobVertexID(), 0);
}
public TestingSchedulingExecutionVertex newExecutionVertex(ExecutionState executionState) {
final TestingSchedulingExecutionVertex newVertex =
TestingSchedulingExecutionVertex.newBuilder()
.withExecutionState(executionState)
.build();
addSchedulingExecutionVertex(newVertex);
return newVertex;
}
public TestingSchedulingExecutionVertex newExecutionVertex(
final JobVertexID jobVertexId, final int subtaskIndex) {
final TestingSchedulingExecutionVertex newVertex =
TestingSchedulingExecutionVertex.withExecutionVertexID(jobVertexId, subtaskIndex);
addSchedulingExecutionVertex(newVertex);
return newVertex;
}
public TestingSchedulingTopology connect(
final TestingSchedulingExecutionVertex producer,
final TestingSchedulingExecutionVertex consumer) {
return connect(producer, consumer, ResultPartitionType.PIPELINED);
}
public TestingSchedulingTopology connect(
TestingSchedulingExecutionVertex producer,
TestingSchedulingExecutionVertex consumer,
ResultPartitionType resultPartitionType) {
connectConsumersToProducers(
Collections.singletonList(consumer),
Collections.singletonList(producer),
new IntermediateDataSetID(),
resultPartitionType,
ResultPartitionState.ALL_DATA_PRODUCED);
updateVertexResultPartitions(producer);
updateVertexResultPartitions(consumer);
resetPipelinedRegions();
return this;
}
public ProducerConsumerConnectionBuilder connectPointwise(
final List<TestingSchedulingExecutionVertex> producers,
final List<TestingSchedulingExecutionVertex> consumers) {
return new ProducerConsumerPointwiseConnectionBuilder(producers, consumers);
}
public ProducerConsumerConnectionBuilder connectAllToAll(
final List<TestingSchedulingExecutionVertex> producers,
final List<TestingSchedulingExecutionVertex> consumers) {
return new ProducerConsumerAllToAllConnectionBuilder(producers, consumers);
}
private static List<TestingSchedulingResultPartition> connectConsumersToProducers(
final List<TestingSchedulingExecutionVertex> consumers,
final List<TestingSchedulingExecutionVertex> producers,
final IntermediateDataSetID intermediateDataSetId,
final ResultPartitionType resultPartitionType,
final ResultPartitionState resultPartitionState) {
final List<TestingSchedulingResultPartition> resultPartitions = new ArrayList<>();
final ConnectionResult connectionResult =
connectConsumersToProducersById(
consumers.stream()
.map(SchedulingExecutionVertex::getId)
.collect(Collectors.toList()),
producers.stream()
.map(SchedulingExecutionVertex::getId)
.collect(Collectors.toList()),
intermediateDataSetId,
resultPartitionType);
final ConsumedPartitionGroup consumedPartitionGroup =
connectionResult.getConsumedPartitionGroup();
final ConsumerVertexGroup consumerVertexGroup = connectionResult.getConsumerVertexGroup();
final TestingSchedulingResultPartition.Builder resultPartitionBuilder =
new TestingSchedulingResultPartition.Builder()
.withIntermediateDataSetID(intermediateDataSetId)
.withResultPartitionType(resultPartitionType)
.withResultPartitionState(resultPartitionState);
for (int i = 0; i < producers.size(); i++) {
final TestingSchedulingExecutionVertex producer = producers.get(i);
final IntermediateResultPartitionID partitionId =
connectionResult.getResultPartitions().get(i);
final TestingSchedulingResultPartition resultPartition =
resultPartitionBuilder
.withPartitionNum(partitionId.getPartitionNumber())
.build();
producer.addProducedPartition(resultPartition);
resultPartition.setProducer(producer);
resultPartitions.add(resultPartition);
resultPartition.registerConsumedPartitionGroup(consumedPartitionGroup);
resultPartition.addConsumerGroup(consumerVertexGroup);
if (resultPartition.getState() == ResultPartitionState.ALL_DATA_PRODUCED) {
consumedPartitionGroup.partitionFinished();
}
}
final Map<IntermediateResultPartitionID, TestingSchedulingResultPartition>
consumedPartitionById =
resultPartitions.stream()
.collect(
Collectors.toMap(
TestingSchedulingResultPartition::getId,
Function.identity()));
for (TestingSchedulingExecutionVertex consumer : consumers) {
consumer.addConsumedPartitionGroup(consumedPartitionGroup, consumedPartitionById);
}
return resultPartitions;
}
public static ConnectionResult connectConsumersToProducersById(
final List<ExecutionVertexID> consumers,
final List<ExecutionVertexID> producers,
final IntermediateDataSetID intermediateDataSetId,
final ResultPartitionType resultPartitionType) {
final List<IntermediateResultPartitionID> resultPartitions = new ArrayList<>();
for (ExecutionVertexID producer : producers) {
final IntermediateResultPartitionID resultPartition =
new IntermediateResultPartitionID(
intermediateDataSetId, producer.getSubtaskIndex());
resultPartitions.add(resultPartition);
}
final ConsumedPartitionGroup consumedPartitionGroup =
createConsumedPartitionGroup(
consumers.size(), resultPartitions, resultPartitionType);
final ConsumerVertexGroup consumerVertexGroup =
createConsumerVertexGroup(consumers, resultPartitionType);
consumedPartitionGroup.setConsumerVertexGroup(consumerVertexGroup);
consumerVertexGroup.setConsumedPartitionGroup(consumedPartitionGroup);
return new ConnectionResult(resultPartitions, consumedPartitionGroup, consumerVertexGroup);
}
private static ConsumedPartitionGroup createConsumedPartitionGroup(
final int numConsumers,
final List<IntermediateResultPartitionID> consumedPartitions,
final ResultPartitionType resultPartitionType) {
return ConsumedPartitionGroup.fromMultiplePartitions(
numConsumers, consumedPartitions, resultPartitionType);
}
private static ConsumerVertexGroup createConsumerVertexGroup(
final List<ExecutionVertexID> consumers,
final ResultPartitionType resultPartitionType) {
return ConsumerVertexGroup.fromMultipleVertices(consumers, resultPartitionType);
}
/**
* The result of connecting a set of consumers to their producers, including the created result
* partitions and the consumption groups.
*/
public static
|
TestingSchedulingTopology
|
java
|
quarkusio__quarkus
|
extensions/spring-scheduled/deployment/src/test/java/io/quarkus/spring/scheduled/deployment/UnsupportedFixedDelayParamTest.java
|
{
"start": 816,
"end": 938
}
|
class ____ {
@Scheduled(fixedDelay = 1000)
void unsupportedParamFixedDelay() {
}
}
}
|
InvalidBean
|
java
|
apache__flink
|
flink-python/src/main/java/org/apache/flink/table/runtime/arrow/vectors/ArrowNullColumnVector.java
|
{
"start": 1029,
"end": 1291
}
|
class ____ implements ColumnVector {
public static final ArrowNullColumnVector INSTANCE = new ArrowNullColumnVector();
private ArrowNullColumnVector() {}
@Override
public boolean isNullAt(int i) {
return true;
}
}
|
ArrowNullColumnVector
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ClassInitializationDeadlockTest.java
|
{
"start": 7578,
"end": 7701
}
|
interface ____ {
default Object foo() {
return null;
}
|
TestInterface
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/common/processor/src/main/java/org/jboss/resteasy/reactive/common/processor/EndpointIndexer.java
|
{
"start": 91395,
"end": 99551
}
|
class ____<T extends EndpointIndexer<T, ?, METHOD>, B extends Builder<T, B, METHOD>, METHOD extends ResourceMethod> {
private Function<String, BeanFactory<Object>> factoryCreator;
private BlockingDefault defaultBlocking = BlockingDefault.AUTOMATIC;
private IndexView index;
private IndexView applicationIndex;
private Map<String, String> existingConverters = new HashMap<>();
private Map<DotName, String> scannedResourcePaths;
private ResteasyReactiveConfig config;
private AdditionalReaders additionalReaders;
private Map<DotName, String> httpAnnotationToMethod;
private Map<String, InjectableBean> injectableBeans;
private AdditionalWriters additionalWriters;
private boolean hasRuntimeConverters;
private Map<DotName, Map<String, String>> classLevelExceptionMappers;
private Consumer<ResourceMethodCallbackEntry> resourceMethodCallback;
private Collection<AnnotationTransformation> annotationsTransformers;
private ApplicationScanningResult applicationScanningResult;
private Set<DotName> alreadyHandledRequestScopedResources = new HashSet<>();
private final Set<DotName> contextTypes = new HashSet<>(DEFAULT_CONTEXT_TYPES);
private final Set<DotName> parameterContainerTypes = new HashSet<>();
private MultipartReturnTypeIndexerExtension multipartReturnTypeIndexerExtension = new MultipartReturnTypeIndexerExtension() {
@Override
public boolean handleMultipartForReturnType(AdditionalWriters additionalWriters, ClassInfo multipartClassInfo,
IndexView indexView) {
return false;
}
};
private TargetJavaVersion targetJavaVersion = new TargetJavaVersion.Unknown();
private Function<ClassInfo, Supplier<Boolean>> isDisabledCreator = null;
private Predicate<Map<DotName, AnnotationInstance>> skipMethodParameter = null;
private List<Predicate<ClassInfo>> defaultPredicate = Arrays.asList(new Predicate<>() {
@Override
public boolean test(ClassInfo classInfo) {
return Modifier.isInterface(classInfo.flags())
|| Modifier.isAbstract(classInfo.flags());
}
});
private boolean skipNotRestParameters = false;
public B setMultipartReturnTypeIndexerExtension(MultipartReturnTypeIndexerExtension multipartReturnTypeHandler) {
this.multipartReturnTypeIndexerExtension = multipartReturnTypeHandler;
return (B) this;
}
public B setDefaultBlocking(BlockingDefault defaultBlocking) {
this.defaultBlocking = defaultBlocking;
return (B) this;
}
public B setHasRuntimeConverters(boolean hasRuntimeConverters) {
this.hasRuntimeConverters = hasRuntimeConverters;
return (B) this;
}
public B setIndex(IndexView index) {
this.index = index;
return (B) this;
}
public B setApplicationIndex(IndexView index) {
this.applicationIndex = index;
return (B) this;
}
public B addContextType(DotName contextType) {
this.contextTypes.add(contextType);
return (B) this;
}
public B addContextTypes(Collection<DotName> contextTypes) {
this.contextTypes.addAll(contextTypes);
return (B) this;
}
public B addParameterContainerType(DotName parameterContainerType) {
this.parameterContainerTypes.add(parameterContainerType);
return (B) this;
}
public B addParameterContainerTypes(Collection<DotName> parameterContainerTypes) {
this.parameterContainerTypes.addAll(parameterContainerTypes);
return (B) this;
}
public B setExistingConverters(Map<String, String> existingConverters) {
this.existingConverters = existingConverters;
return (B) this;
}
public B setScannedResourcePaths(Map<DotName, String> scannedResourcePaths) {
this.scannedResourcePaths = scannedResourcePaths;
return (B) this;
}
public B setFactoryCreator(Function<String, BeanFactory<Object>> factoryCreator) {
this.factoryCreator = factoryCreator;
return (B) this;
}
public B setConfig(ResteasyReactiveConfig config) {
this.config = config;
return (B) this;
}
public B setAdditionalReaders(AdditionalReaders additionalReaders) {
this.additionalReaders = additionalReaders;
return (B) this;
}
public B setHttpAnnotationToMethod(Map<DotName, String> httpAnnotationToMethod) {
this.httpAnnotationToMethod = httpAnnotationToMethod;
return (B) this;
}
public B setInjectableBeans(Map<String, InjectableBean> injectableBeans) {
this.injectableBeans = injectableBeans;
return (B) this;
}
public B setAdditionalWriters(AdditionalWriters additionalWriters) {
this.additionalWriters = additionalWriters;
return (B) this;
}
public B setClassLevelExceptionMappers(Map<DotName, Map<String, String>> classLevelExceptionMappers) {
this.classLevelExceptionMappers = classLevelExceptionMappers;
return (B) this;
}
public B setResourceMethodCallback(Consumer<ResourceMethodCallbackEntry> resourceMethodCallback) {
this.resourceMethodCallback = resourceMethodCallback;
return (B) this;
}
/**
* @deprecated use {@link #setAnnotationTransformations(Collection)}
*/
@Deprecated(forRemoval = true)
public B setAnnotationsTransformers(Collection<AnnotationsTransformer> annotationsTransformers) {
List<AnnotationTransformation> transformations = new ArrayList<>(annotationsTransformers.size());
transformations.addAll(annotationsTransformers);
this.annotationsTransformers = transformations;
return (B) this;
}
public B setAnnotationTransformations(Collection<AnnotationTransformation> annotationTransformations) {
this.annotationsTransformers = annotationTransformations;
return (B) this;
}
public B setApplicationScanningResult(ApplicationScanningResult applicationScanningResult) {
this.applicationScanningResult = applicationScanningResult;
return (B) this;
}
public B setTargetJavaVersion(TargetJavaVersion targetJavaVersion) {
this.targetJavaVersion = targetJavaVersion;
return (B) this;
}
public B setIsDisabledCreator(
Function<ClassInfo, Supplier<Boolean>> isDisabledCreator) {
this.isDisabledCreator = isDisabledCreator;
return (B) this;
}
public B setSkipMethodParameter(
Predicate<Map<DotName, AnnotationInstance>> skipMethodParameter) {
this.skipMethodParameter = skipMethodParameter;
return (B) this;
}
public B setValidateEndpoint(List<Predicate<ClassInfo>> validateEndpoint) {
List<Predicate<ClassInfo>> predicates = new ArrayList<>(validateEndpoint.size() + 1);
predicates.addAll(validateEndpoint);
predicates.addAll(this.defaultPredicate);
this.defaultPredicate = predicates;
return (B) this;
}
public B skipNotRestParameters(boolean skipNotRestParameters) {
this.skipNotRestParameters = skipNotRestParameters;
return (B) this;
}
public B alreadyHandledRequestScopedResources(Set<DotName> alreadyHandledRequestScopedResources) {
this.alreadyHandledRequestScopedResources = alreadyHandledRequestScopedResources;
return (B) this;
}
public abstract T build();
}
public static
|
Builder
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/job/results/GeoResults.java
|
{
"start": 731,
"end": 3370
}
|
class ____ implements ToXContentObject, Writeable {
public static final ParseField GEO_RESULTS = new ParseField("geo_results");
public static final ParseField TYPICAL_POINT = new ParseField("typical_point");
public static final ParseField ACTUAL_POINT = new ParseField("actual_point");
public static final ObjectParser<GeoResults, Void> STRICT_PARSER = createParser(false);
public static final ObjectParser<GeoResults, Void> LENIENT_PARSER = createParser(true);
private static ObjectParser<GeoResults, Void> createParser(boolean ignoreUnknownFields) {
ObjectParser<GeoResults, Void> parser = new ObjectParser<>(GEO_RESULTS.getPreferredName(), ignoreUnknownFields, GeoResults::new);
parser.declareString(GeoResults::setActualPoint, ACTUAL_POINT);
parser.declareString(GeoResults::setTypicalPoint, TYPICAL_POINT);
return parser;
}
private String actualPoint;
private String typicalPoint;
public GeoResults() {}
public GeoResults(StreamInput in) throws IOException {
this.actualPoint = in.readOptionalString();
this.typicalPoint = in.readOptionalString();
}
public String getActualPoint() {
return actualPoint;
}
public void setActualPoint(String actualPoint) {
this.actualPoint = actualPoint;
}
public String getTypicalPoint() {
return typicalPoint;
}
public void setTypicalPoint(String typicalPoint) {
this.typicalPoint = typicalPoint;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
out.writeOptionalString(actualPoint);
out.writeOptionalString(typicalPoint);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
if (typicalPoint != null) {
builder.field(TYPICAL_POINT.getPreferredName(), typicalPoint);
}
if (actualPoint != null) {
builder.field(ACTUAL_POINT.getPreferredName(), actualPoint);
}
builder.endObject();
return builder;
}
@Override
public int hashCode() {
return Objects.hash(typicalPoint, actualPoint);
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || getClass() != other.getClass()) {
return false;
}
GeoResults that = (GeoResults) other;
return Objects.equals(this.typicalPoint, that.typicalPoint) && Objects.equals(this.actualPoint, that.actualPoint);
}
}
|
GeoResults
|
java
|
elastic__elasticsearch
|
test/framework/src/main/java/org/elasticsearch/plugins/internal/rewriter/MockQueryRewriteInterceptor.java
|
{
"start": 640,
"end": 969
}
|
class ____ implements QueryRewriteInterceptor {
@Override
public QueryBuilder interceptAndRewrite(QueryRewriteContext context, QueryBuilder queryBuilder) {
return queryBuilder;
}
@Override
public String getQueryName() {
return this.getClass().getSimpleName();
}
}
|
MockQueryRewriteInterceptor
|
java
|
google__guice
|
core/test/com/google/inject/internal/MoreTypesTest.java
|
{
"start": 3693,
"end": 3720
}
|
class ____<S, T> {}
static
|
D
|
java
|
netty__netty
|
codec-mqtt/src/main/java/io/netty/handler/codec/mqtt/MqttMessageBuilders.java
|
{
"start": 10235,
"end": 11866
}
|
class ____ {
private MqttConnectReturnCode returnCode;
private boolean sessionPresent;
private MqttProperties properties = MqttProperties.NO_PROPERTIES;
private ConnAckPropertiesBuilder propsBuilder;
private ConnAckBuilder() {
}
public ConnAckBuilder returnCode(MqttConnectReturnCode returnCode) {
this.returnCode = returnCode;
return this;
}
public ConnAckBuilder sessionPresent(boolean sessionPresent) {
this.sessionPresent = sessionPresent;
return this;
}
public ConnAckBuilder properties(MqttProperties properties) {
this.properties = properties;
return this;
}
public ConnAckBuilder properties(PropertiesInitializer<ConnAckPropertiesBuilder> consumer) {
if (propsBuilder == null) {
propsBuilder = new ConnAckPropertiesBuilder();
}
consumer.apply(propsBuilder);
return this;
}
public MqttConnAckMessage build() {
if (propsBuilder != null) {
properties = propsBuilder.build();
}
MqttFixedHeader mqttFixedHeader =
new MqttFixedHeader(MqttMessageType.CONNACK, false, MqttQoS.AT_MOST_ONCE, false, 0);
MqttConnAckVariableHeader mqttConnAckVariableHeader =
new MqttConnAckVariableHeader(returnCode, sessionPresent, properties);
return new MqttConnAckMessage(mqttFixedHeader, mqttConnAckVariableHeader);
}
}
public static final
|
ConnAckBuilder
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java
|
{
"start": 125129,
"end": 125791
}
|
class ____ {
public int foo(Suit suit) {
int x = 0;
switch (suit) {
case HEART:
case DIAMOND:
x = x + 1;
break;
case SPADE:
throw new RuntimeException();
case CLUB:
throw new NullPointerException();
case null, default:
throw new IllegalArgumentException();
}
return x;
}
}
""")
.addOutputLines(
"Test.java",
"""
|
Test
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/ReferenceEqualityTest.java
|
{
"start": 2209,
"end": 2665
}
|
class ____ {
public static final Foo CONST = new Foo();
boolean f(Foo a) {
return a == CONST;
}
boolean f(Object o, Foo a) {
return o == a;
}
}
""")
.doTest();
}
@Test
public void negative_extends_equalsObject() {
compilationHelper
.addSourceLines(
"Sup.java",
"""
|
Test
|
java
|
apache__camel
|
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/StartupShutdownOrderBaseTest.java
|
{
"start": 5954,
"end": 7025
}
|
interface ____ {
void assertValid();
}
@Test
public void camelContextShouldBeStartedLastAndStoppedFirst() {
final ConfigurableApplicationContext context = createContext();
final CamelContext camelContext = context.getBean(CamelContext.class);
final Map<String, TestState> testStates = context.getBeansOfType(TestState.class);
assertThat("Camel context should be started", camelContext.isStarted());
context.close();
assertThat("Camel context should be stopped", camelContext.isStopped());
testStates.values().stream().forEach(TestState::assertValid);
}
abstract ConfigurableApplicationContext createContext();
static CamelContext camel(final ApplicationContext context) {
return context.getBean(CamelContext.class);
}
static boolean camelIsStarted(final ApplicationContext context) {
return camel(context).isStarted();
}
static boolean camelIsStopped(final ApplicationContext context) {
return !camelIsStarted(context);
}
}
|
TestState
|
java
|
apache__kafka
|
server/src/test/java/org/apache/kafka/server/MonitorablePluginsIntegrationTest.java
|
{
"start": 2254,
"end": 5730
}
|
class ____ {
private static int controllerId(Type type) {
return type == Type.KRAFT ? 3000 : 0;
}
@ClusterTest(
types = {Type.KRAFT, Type.CO_KRAFT},
serverProperties = {
@ClusterConfigProperty(key = StandardAuthorizer.SUPER_USERS_CONFIG, value = "User:ANONYMOUS"),
@ClusterConfigProperty(key = AUTHORIZER_CLASS_NAME_CONFIG, value = "org.apache.kafka.metadata.authorizer.StandardAuthorizer"),
@ClusterConfigProperty(key = REPLICA_SELECTOR_CLASS_CONFIG, value = "org.apache.kafka.server.MonitorablePluginsIntegrationTest$MonitorableReplicaSelector"),
@ClusterConfigProperty(key = REMOTE_LOG_STORAGE_SYSTEM_ENABLE_PROP, value = "true"),
@ClusterConfigProperty(key = REMOTE_LOG_METADATA_MANAGER_CLASS_NAME_PROP,
value = "org.apache.kafka.server.MonitorablePluginsIntegrationTest$MonitorableNoOpRemoteLogMetadataManager"),
@ClusterConfigProperty(key = REMOTE_STORAGE_MANAGER_CLASS_NAME_PROP,
value = "org.apache.kafka.server.MonitorablePluginsIntegrationTest$MonitorableNoOpRemoteStorageManager")
}
)
public void testMonitorableServerPlugins(ClusterInstance clusterInstance) {
assertAuthorizerMetrics(clusterInstance);
assertReplicaSelectorMetrics(clusterInstance);
assertRemoteLogManagerMetrics(clusterInstance);
}
private void assertAuthorizerMetrics(ClusterInstance clusterInstance) {
assertMetrics(
clusterInstance.brokers().get(0).metrics(),
4,
expectedTags(AUTHORIZER_CLASS_NAME_CONFIG, "StandardAuthorizer", Map.of("role", "broker")));
assertMetrics(
clusterInstance.controllers().get(controllerId(clusterInstance.type())).metrics(),
4,
expectedTags(AUTHORIZER_CLASS_NAME_CONFIG, "StandardAuthorizer", Map.of("role", "controller")));
}
private void assertRemoteLogManagerMetrics(ClusterInstance clusterInstance) {
assertMetrics(
clusterInstance.brokers().get(0).metrics(),
MonitorableNoOpRemoteLogMetadataManager.METRICS_COUNT,
expectedTags(REMOTE_LOG_METADATA_MANAGER_CLASS_NAME_PROP, MonitorableNoOpRemoteLogMetadataManager.class.getSimpleName()));
assertMetrics(
clusterInstance.brokers().get(0).metrics(),
MonitorableNoOpRemoteStorageManager.METRICS_COUNT,
expectedTags(REMOTE_STORAGE_MANAGER_CLASS_NAME_PROP, MonitorableNoOpRemoteStorageManager.class.getSimpleName()));
}
private void assertReplicaSelectorMetrics(ClusterInstance clusterInstance) {
assertMetrics(
clusterInstance.brokers().get(0).metrics(),
MonitorableReplicaSelector.METRICS_COUNT,
expectedTags(REPLICA_SELECTOR_CLASS_CONFIG, MonitorableReplicaSelector.class.getSimpleName()));
}
private void assertMetrics(Metrics metrics, int expected, Map<String, String> expectedTags) {
int found = 0;
for (MetricName metricName : metrics.metrics().keySet()) {
if (metricName.group().equals("plugins")) {
Map<String, String> tags = metricName.tags();
if (expectedTags.equals(tags)) {
found++;
}
}
}
assertEquals(expected, found);
}
public static
|
MonitorablePluginsIntegrationTest
|
java
|
apache__camel
|
components/camel-hl7/src/test/java/org/apache/camel/component/hl7/ConvertLineFeedTest.java
|
{
"start": 1113,
"end": 1635
}
|
class ____ extends CamelTestSupport {
@Test
public void testConvertLineFeed() {
String s = "line1\nline2\rline3";
String result = template.requestBody("direct:test1", s, String.class);
assertEquals("line1\rline2\rline3", result);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("direct:test1").transform(convertLFToCR());
}
};
}
}
|
ConvertLineFeedTest
|
java
|
apache__camel
|
components/camel-ibm/camel-ibm-watson-speech-to-text/src/test/java/org/apache/camel/component/ibm/watson/stt/integration/WatsonSpeechToTextTestSupport.java
|
{
"start": 934,
"end": 1005
}
|
class ____ Watson Speech to Text integration tests.
*/
public abstract
|
for
|
java
|
apache__kafka
|
clients/src/test/java/org/apache/kafka/clients/consumer/internals/TopicIdPartitionSetTest.java
|
{
"start": 1389,
"end": 6654
}
|
class ____ {
private TopicIdPartitionSet topicIdPartitionSet;
@BeforeEach
public void setUp() {
topicIdPartitionSet = new TopicIdPartitionSet();
}
@Test
public void testIsEmpty() {
assertTrue(topicIdPartitionSet.isEmpty());
TopicIdPartition topicIdPartition = new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("foo", 0));
topicIdPartitionSet.add(topicIdPartition);
assertFalse(topicIdPartitionSet.isEmpty());
}
@Test
public void testRetrieveTopicPartitions() {
TopicPartition tp1 = new TopicPartition("foo", 0);
TopicPartition tp2 = new TopicPartition("foo", 1);
TopicPartition tp3 = new TopicPartition("bar", 0);
Uuid topicId1 = Uuid.randomUuid();
Uuid topicId2 = Uuid.randomUuid();
topicIdPartitionSet.add(new TopicIdPartition(topicId1, tp1));
topicIdPartitionSet.add(new TopicIdPartition(topicId1, tp2));
topicIdPartitionSet.add(new TopicIdPartition(topicId2, tp3));
Set<TopicPartition> topicPartitionSet = topicIdPartitionSet.topicPartitions();
assertEquals(3, topicPartitionSet.size());
assertTrue(topicPartitionSet.contains(tp1));
assertTrue(topicPartitionSet.contains(tp2));
assertTrue(topicPartitionSet.contains(tp3));
}
@Test
public void testRetrieveTopicIds() {
Uuid topicId1 = Uuid.randomUuid();
Uuid topicId2 = Uuid.randomUuid();
topicIdPartitionSet.add(new TopicIdPartition(topicId1, new TopicPartition("foo", 0)));
topicIdPartitionSet.add(new TopicIdPartition(topicId1, new TopicPartition("foo", 1)));
topicIdPartitionSet.add(new TopicIdPartition(topicId2, new TopicPartition("bar", 0)));
Set<Uuid> topicIds = topicIdPartitionSet.topicIds();
assertEquals(2, topicIds.size());
assertTrue(topicIds.contains(topicId1));
assertTrue(topicIds.contains(topicId2));
}
@Test
public void testRetrieveTopicNames() {
String topic1 = "foo";
String topic2 = "bar";
Uuid topicId1 = Uuid.randomUuid();
Uuid topicId2 = Uuid.randomUuid();
topicIdPartitionSet.add(new TopicIdPartition(topicId1, new TopicPartition(topic1, 0)));
topicIdPartitionSet.add(new TopicIdPartition(topicId1, new TopicPartition(topic1, 1)));
topicIdPartitionSet.add(new TopicIdPartition(topicId2, new TopicPartition(topic2, 0)));
Set<String> topicNames = topicIdPartitionSet.topicNames();
assertEquals(2, topicNames.size());
assertTrue(topicNames.contains(topic1));
assertTrue(topicNames.contains(topic2));
}
@Test
public void testRetrievedTopicNamesAreSorted() {
LinkedHashSet<TopicIdPartition> expectedOrderedTopicPartitions = new LinkedHashSet<>();
expectedOrderedTopicPartitions.add(new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("topic-z", 1)));
expectedOrderedTopicPartitions.add(new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("topic-z", 0)));
expectedOrderedTopicPartitions.add(new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("topic-a", 0)));
expectedOrderedTopicPartitions.add(new TopicIdPartition(Uuid.randomUuid(), new TopicPartition("topic-a", 1)));
List<TopicIdPartition> reversed = new ArrayList<>(expectedOrderedTopicPartitions);
Collections.reverse(reversed);
reversed.forEach(tp -> topicIdPartitionSet.add(tp));
List<TopicPartition> topicPartitions = new ArrayList<>(topicIdPartitionSet.toTopicNamePartitionSet());
assertEquals(4, topicPartitions.size());
assertEquals(new TopicPartition("topic-a", 0), topicPartitions.get(0));
assertEquals(new TopicPartition("topic-a", 1), topicPartitions.get(1));
assertEquals(new TopicPartition("topic-z", 0), topicPartitions.get(2));
assertEquals(new TopicPartition("topic-z", 1), topicPartitions.get(3));
}
@Test
public void testToString() {
Uuid topicId1 = Uuid.randomUuid();
TopicIdPartition tp1 = new TopicIdPartition(topicId1, new TopicPartition("topic-a", 0));
TopicIdPartition tp2 = new TopicIdPartition(topicId1, new TopicPartition("topic-a", 1));
TopicIdPartition tp3 = new TopicIdPartition(topicId1, new TopicPartition("topic-b", 0));
topicIdPartitionSet.add(tp1);
topicIdPartitionSet.add(tp2);
topicIdPartitionSet.add(tp3);
String toString = topicIdPartitionSet.toString();
assertEquals(List.of(tp1, tp2, tp3).toString(), toString);
}
@Test
public void testToStringSorted() {
Uuid topicId1 = Uuid.randomUuid();
TopicIdPartition tp1 = new TopicIdPartition(topicId1, new TopicPartition("topic-a", 0));
TopicIdPartition tpz1 = new TopicIdPartition(topicId1, new TopicPartition("topic-z", 0));
TopicIdPartition tpz2 = new TopicIdPartition(topicId1, new TopicPartition("topic-z", 1));
topicIdPartitionSet.add(tpz2);
topicIdPartitionSet.add(tpz1);
topicIdPartitionSet.add(tp1);
String toString = topicIdPartitionSet.toString();
assertEquals(List.of(tp1, tpz1, tpz2).toString(), toString);
}
}
|
TopicIdPartitionSetTest
|
java
|
apache__camel
|
components/camel-rss/src/test/java/org/apache/camel/component/rss/RssPollingConsumerTest.java
|
{
"start": 1336,
"end": 2382
}
|
class ____ extends CamelTestSupport {
@Test
public void testGrabbingListOfEntries() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMinimumMessageCount(1);
mock.assertIsSatisfied();
Exchange exchange = mock.getExchanges().get(0);
Message in = exchange.getIn();
assertNotNull(in);
assertTrue(in.getBody() instanceof SyndFeed);
assertTrue(in.getHeader(RssConstants.RSS_FEED) instanceof SyndFeed);
SyndFeed feed = in.getHeader(RssConstants.RSS_FEED, SyndFeed.class);
assertTrue(feed.getAuthor().contains("Jonathan Anstey"));
SyndFeed body = in.getBody(SyndFeed.class);
assertEquals(10, body.getEntries().size());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("rss:file:src/test/data/rss20.xml?splitEntries=false").to("mock:result");
}
};
}
}
|
RssPollingConsumerTest
|
java
|
spring-projects__spring-boot
|
module/spring-boot-data-neo4j/src/main/java/org/springframework/boot/data/neo4j/autoconfigure/DataNeo4jReactiveRepositoriesRegistrar.java
|
{
"start": 1326,
"end": 1881
}
|
class ____ extends AbstractRepositoryConfigurationSourceSupport {
@Override
protected Class<? extends Annotation> getAnnotation() {
return EnableReactiveNeo4jRepositories.class;
}
@Override
protected Class<?> getConfiguration() {
return EnableReactiveNeo4jRepositoriesConfiguration.class;
}
@Override
protected RepositoryConfigurationExtension getRepositoryConfigurationExtension() {
return new ReactiveNeo4jRepositoryConfigurationExtension();
}
@EnableReactiveNeo4jRepositories
private static final
|
DataNeo4jReactiveRepositoriesRegistrar
|
java
|
elastic__elasticsearch
|
x-pack/plugin/spatial/src/main/java/org/elasticsearch/xpack/spatial/script/field/CartesianPointDocValuesField.java
|
{
"start": 623,
"end": 2447
}
|
class ____ extends PointDocValuesField<CartesianPoint> {
// maintain bwc by making centroid and bounding box available to ScriptDocValues.GeoPoints
private CartesianPointScriptValues points = null;
public CartesianPointDocValuesField(MultiPointValues<CartesianPoint> input, String name) {
super(
input,
name,
CartesianPoint::new,
new CartesianBoundingBox(new CartesianPoint(), new CartesianPoint()),
new CartesianPoint[0]
);
}
@Override
protected void resetPointAt(int i, CartesianPoint point) {
values[i].reset(point.getX(), point.getY());
}
@Override
protected void resetCentroidAndBounds(CartesianPoint point, CartesianPoint topLeft, CartesianPoint bottomRight) {
centroid.reset(point.getX() / count, point.getY() / count);
boundingBox.topLeft().reset(topLeft.getX(), topLeft.getY());
boundingBox.bottomRight().reset(bottomRight.getX(), bottomRight.getY());
}
@Override
protected double getXFrom(CartesianPoint point) {
return point.getX();
}
@Override
protected double getYFrom(CartesianPoint point) {
return point.getY();
}
@Override
protected CartesianPoint pointOf(double x, double y) {
return new CartesianPoint(x, y);
}
@Override
protected double planeDistance(double x1, double y1, CartesianPoint point) {
double x = point.getX() - x1;
double y = point.getY() - y1;
return Math.sqrt(x * x + y * y);
}
@Override
public ScriptDocValues<CartesianPoint> toScriptDocValues() {
if (points == null) {
points = new CartesianPointScriptValues(this);
}
return points;
}
public abstract static
|
CartesianPointDocValuesField
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/transform/KnownTransformConfigVersions.java
|
{
"start": 400,
"end": 637
}
|
class ____ {
/**
* A sorted list of all known transform config versions
*/
public static final List<TransformConfigVersion> ALL_VERSIONS = List.copyOf(TransformConfigVersion.getAllVersions());
}
|
KnownTransformConfigVersions
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/asyncprocessing/operators/windowing/AsyncEvictingWindowOperator.java
|
{
"start": 3553,
"end": 16398
}
|
class ____<K, IN, OUT, W extends Window>
extends AsyncWindowOperator<K, IN, StateIterator<IN>, OUT, W> {
private static final long serialVersionUID = 1L;
// ------------------------------------------------------------------------
// these fields are set by the API stream graph builder to configure the operator
private final Evictor<? super IN, ? super W> evictor;
private final StateDescriptor<StreamRecord<IN>> evictingWindowStateDescriptor;
// ------------------------------------------------------------------------
// the fields below are instantiated once the operator runs in the runtime
private transient EvictorContext evictorContext;
private transient InternalListState<K, W, StreamRecord<IN>> evictingWindowState;
// ------------------------------------------------------------------------
public AsyncEvictingWindowOperator(
WindowAssigner<? super IN, W> windowAssigner,
TypeSerializer<W> windowSerializer,
KeySelector<IN, K> keySelector,
TypeSerializer<K> keySerializer,
StateDescriptor<StreamRecord<IN>> windowStateDescriptor,
InternalAsyncWindowFunction<StateIterator<IN>, OUT, K, W> windowFunction,
AsyncTrigger<? super IN, ? super W> trigger,
Evictor<? super IN, ? super W> evictor,
long allowedLateness,
OutputTag<IN> lateDataOutputTag) {
super(
windowAssigner,
windowSerializer,
keySelector,
keySerializer,
null,
windowFunction,
trigger,
allowedLateness,
lateDataOutputTag);
this.evictor = checkNotNull(evictor);
this.evictingWindowStateDescriptor = checkNotNull(windowStateDescriptor);
}
@Override
public void processElement(StreamRecord<IN> element) throws Exception {
final Collection<W> elementWindows =
windowAssigner.assignWindows(
element.getValue(), element.getTimestamp(), windowAssignerContext);
final K key = (K) getCurrentKey();
// Note: windowFutures is empty => implicitly isSkippedElement == true.
Collection<StateFuture<Void>> windowFutures = new ArrayList<>();
if (windowAssigner instanceof MergingWindowAssigner) {
throw new UnsupportedOperationException(
"Async WindowOperator not support merging window (e.g. session window) yet.");
} else {
for (W window : elementWindows) {
// drop if the window is already late
if (isWindowLate(window)) {
continue;
}
AtomicReference<TriggerResult> triggerResult = new AtomicReference<>();
windowDeclaredVariable.set(window);
// Implicitly isSkippedElement = false
windowFutures.add(
evictingWindowState
.asyncAdd(element)
.thenCompose(
ignore ->
triggerContext
.onElement(element)
.thenAccept(triggerResult::set))
.thenConditionallyCompose(
ignore -> triggerResult.get().isFire(),
ignore ->
evictingWindowState
.asyncGet()
.thenConditionallyCompose(
Objects::nonNull,
contents ->
emitWindowContents(
key,
window,
contents,
evictingWindowState)))
.thenConditionallyCompose(
ignore -> triggerResult.get().isPurge(),
ignore -> evictingWindowState.asyncClear())
.thenAccept(ignore -> registerCleanupTimer(window)));
}
// side output input event if
// element not handled by any window
// late arriving tag has been set
// windowAssigner is event time and current timestamp + allowed lateness no less than
// element timestamp
if (windowFutures.isEmpty() && isElementLate(element)) {
if (lateDataOutputTag != null) {
sideOutput(element);
} else {
this.numLateRecordsDropped.inc();
}
}
}
}
@Override
public void onEventTime(InternalTimer<K, W> timer) throws Exception {
windowDeclaredVariable.set(timer.getNamespace());
AtomicReference<TriggerResult> triggerResult = new AtomicReference<>();
if (windowAssigner instanceof MergingWindowAssigner) {
throw new UnsupportedOperationException(
"Async WindowOperator not support merging window (e.g. session window) yet.");
} else {
triggerContext
.onEventTime(timer.getTimestamp())
.thenAccept(triggerResult::set)
.thenConditionallyCompose(
ignore -> triggerResult.get().isFire(),
ignore ->
evictingWindowState
.asyncGet()
.thenConditionallyCompose(
Objects::nonNull,
contents ->
emitWindowContents(
timer.getKey(),
timer.getNamespace(),
contents,
evictingWindowState)))
.thenConditionallyCompose(
ignore -> triggerResult.get().isPurge(),
ignore -> evictingWindowState.asyncClear())
.thenConditionallyCompose(
ignore ->
windowAssigner.isEventTime()
&& isCleanupTime(
timer.getNamespace(), timer.getTimestamp()),
ignore -> clearAllState(timer.getNamespace(), evictingWindowState));
}
}
@Override
public void onProcessingTime(InternalTimer<K, W> timer) throws Exception {
windowDeclaredVariable.set(timer.getNamespace());
AtomicReference<TriggerResult> triggerResult = new AtomicReference<>();
if (windowAssigner instanceof MergingWindowAssigner) {
throw new UnsupportedOperationException(
"Async WindowOperator not support merging window (e.g. session window) yet.");
} else {
triggerContext
.onProcessingTime(timer.getTimestamp())
.thenAccept(triggerResult::set)
.thenConditionallyCompose(
ignore -> triggerResult.get().isFire(),
ignore ->
evictingWindowState
.asyncGet()
.thenConditionallyCompose(
Objects::nonNull,
contents ->
emitWindowContents(
timer.getKey(),
timer.getNamespace(),
contents,
evictingWindowState)))
.thenConditionallyCompose(
ignore -> triggerResult.get().isPurge(),
ignore -> evictingWindowState.asyncClear())
.thenConditionallyCompose(
ignore ->
!windowAssigner.isEventTime()
&& isCleanupTime(
timer.getNamespace(), timer.getTimestamp()),
ignore -> clearAllState(timer.getNamespace(), evictingWindowState));
}
}
private StateFuture<Void> emitWindowContents(
K key,
W window,
StateIterator<StreamRecord<IN>> contents,
ListState<StreamRecord<IN>> windowState)
throws Exception {
timestampedCollector.setAbsoluteTimestamp(window.maxTimestamp());
List<StreamRecord<IN>> elements = new ArrayList<>();
return contents.onNext(
(item) -> {
elements.add(item);
})
.thenApply(
ignore -> {
// Work around type system restrictions...
FluentIterable<TimestampedValue<IN>> recordsWithTimestamp =
FluentIterable.from(elements).transform(TimestampedValue::from);
evictorContext.evictBefore(
recordsWithTimestamp, Iterables.size(recordsWithTimestamp));
FluentIterable<IN> projectedContents =
recordsWithTimestamp.transform(TimestampedValue::getValue);
StateIterator<IN> projectedContentIter =
new CompleteStateIterator<>(projectedContents);
return Tuple2.of(recordsWithTimestamp, projectedContentIter);
})
.thenCompose(
tuple ->
userFunction
.process(
key,
window,
processContext,
tuple.f1,
timestampedCollector)
.thenCompose(
ignore -> {
evictorContext.evictAfter(
tuple.f0, Iterables.size(tuple.f0));
return windowState.asyncUpdate(
tuple.f0.stream()
.map(
TimestampedValue
::getStreamRecord)
.collect(Collectors.toList()));
}));
}
private StateFuture<Void> clearAllState(W window, ListState<StreamRecord<IN>> windowState) {
return windowState
.asyncClear()
.thenCompose(ignore -> triggerContext.clear())
.thenCompose(ignore -> processContext.clear());
}
/**
* {@code EvictorContext} is a utility for handling {@code Evictor} invocations. It can be
* reused by setting the {@code key} and {@code window} fields. No internal state must be kept
* in the {@code EvictorContext}.
*/
|
AsyncEvictingWindowOperator
|
java
|
spring-projects__spring-security
|
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java
|
{
"start": 32618,
"end": 33358
}
|
class ____ extends AbstractOAuth2AuthorizationParametersMapper {
private ObjectMapper objectMapper = Jackson2.createObjectMapper();
@Override
String writeValueAsString(Map<String, Object> data) throws JsonProcessingException {
return this.objectMapper.writeValueAsString(data);
}
protected final ObjectMapper getObjectMapper() {
return this.objectMapper;
}
public final void setObjectMapper(ObjectMapper objectMapper) {
Assert.notNull(objectMapper, "objectMapper cannot be null");
this.objectMapper = objectMapper;
}
}
/**
* The base {@code Function} that maps {@link OAuth2Authorization} to a {@code List}
* of {@link SqlParameterValue}.
*/
private abstract static
|
OAuth2AuthorizationParametersMapper
|
java
|
elastic__elasticsearch
|
x-pack/plugin/rank-rrf/src/internalClusterTest/java/org/elasticsearch/xpack/rank/rrf/RRFRetrieverBuilderIT.java
|
{
"start": 2610,
"end": 46840
}
|
class ____ extends ESIntegTestCase {
protected static String INDEX = "test_index";
protected static final String DOC_FIELD = "doc";
protected static final String TEXT_FIELD = "text";
protected static final String VECTOR_FIELD = "vector";
protected static final String TOPIC_FIELD = "topic";
@Override
protected Collection<Class<? extends Plugin>> nodePlugins() {
return List.of(RRFRankPlugin.class);
}
@Before
public void setup() throws Exception {
setupIndex();
}
protected void setupIndex() {
String mapping = """
{
"properties": {
"vector": {
"type": "dense_vector",
"dims": 1,
"element_type": "float",
"similarity": "l2_norm",
"index": true,
"index_options": {
"type": "hnsw"
}
},
"text": {
"type": "text"
},
"doc": {
"type": "keyword"
},
"topic": {
"type": "keyword"
},
"views": {
"type": "nested",
"properties": {
"last30d": {
"type": "integer"
},
"all": {
"type": "integer"
}
}
}
}
}
""";
createIndex(INDEX, Settings.builder().put(SETTING_NUMBER_OF_SHARDS, randomIntBetween(1, 5)).build());
admin().indices().preparePutMapping(INDEX).setSource(mapping, XContentType.JSON).get();
indexDoc(INDEX, "doc_1", DOC_FIELD, "doc_1", TOPIC_FIELD, "technology", TEXT_FIELD, "term");
indexDoc(
INDEX,
"doc_2",
DOC_FIELD,
"doc_2",
TOPIC_FIELD,
"astronomy",
TEXT_FIELD,
"search term term",
VECTOR_FIELD,
new float[] { 2.0f }
);
indexDoc(INDEX, "doc_3", DOC_FIELD, "doc_3", TOPIC_FIELD, "technology", VECTOR_FIELD, new float[] { 3.0f });
indexDoc(INDEX, "doc_4", DOC_FIELD, "doc_4", TOPIC_FIELD, "technology", TEXT_FIELD, "term term term term");
indexDoc(INDEX, "doc_5", DOC_FIELD, "doc_5", TOPIC_FIELD, "science", TEXT_FIELD, "irrelevant stuff");
indexDoc(
INDEX,
"doc_6",
DOC_FIELD,
"doc_6",
TEXT_FIELD,
"search term term term term term term",
VECTOR_FIELD,
new float[] { 6.0f }
);
indexDoc(
INDEX,
"doc_7",
DOC_FIELD,
"doc_7",
TOPIC_FIELD,
"biology",
TEXT_FIELD,
"term term term term term term term",
VECTOR_FIELD,
new float[] { 7.0f }
);
refresh(INDEX);
}
public void testRRFPagination() {
final int rankWindowSize = 100;
final int rankConstant = 10;
final List<String> expectedDocIds = List.of("doc_2", "doc_6", "doc_7", "doc_1", "doc_3", "doc_4");
final int totalDocs = expectedDocIds.size();
for (int i = 0; i < randomIntBetween(1, 5); i++) {
int from = randomIntBetween(0, totalDocs - 1);
int size = randomIntBetween(1, totalDocs - from);
for (int from_value = from; from_value < totalDocs; from_value += size) {
SearchSourceBuilder source = new SearchSourceBuilder();
source.from(from_value);
source.size(size);
assertRRFPagination(source, from_value, size, rankWindowSize, rankConstant, expectedDocIds);
}
}
// test with `from` as the default (-1)
for (int i = 0; i < randomIntBetween(5, 20); i++) {
int size = randomIntBetween(1, totalDocs);
SearchSourceBuilder source = new SearchSourceBuilder();
source.size(size);
assertRRFPagination(source, source.from(), size, rankWindowSize, rankConstant, expectedDocIds);
}
// and finally test with from = default, and size > {total docs} to be sure
SearchSourceBuilder source = new SearchSourceBuilder();
source.size(totalDocs + 2);
assertRRFPagination(source, source.from(), totalDocs, rankWindowSize, rankConstant, expectedDocIds);
}
private void assertRRFPagination(
SearchSourceBuilder source,
int from,
int maxExpectedSize,
int rankWindowSize,
int rankConstant,
List<String> expectedDocIds
) {
// this one retrieves docs 1, 2, 4, 6, and 7
StandardRetrieverBuilder standard0 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_1")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(9L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_4")).boost(8L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(7L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_7")).boost(6L))
);
// this one retrieves docs 2 and 6 due to prefilter
StandardRetrieverBuilder standard1 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(20L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_3")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(5L))
);
standard1.getPreFilterQueryBuilders().add(QueryBuilders.queryStringQuery("search").defaultField(TEXT_FIELD));
// this one retrieves docs 2, 3, 6, and 7
KnnRetrieverBuilder knnRetrieverBuilder = new KnnRetrieverBuilder(
VECTOR_FIELD,
new float[] { 2.0f },
null,
10,
100,
null,
null,
null
);
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(standard0, null),
new CompoundRetrieverBuilder.RetrieverSource(standard1, null),
new CompoundRetrieverBuilder.RetrieverSource(knnRetrieverBuilder, null)
),
rankWindowSize,
rankConstant
)
);
SearchRequestBuilder req = client().prepareSearch(INDEX).setSource(source);
int innerFrom = Math.max(from, 0);
ElasticsearchAssertions.assertResponse(req, resp -> {
assertNull(resp.pointInTimeId());
assertNotNull(resp.getHits().getTotalHits());
assertThat(resp.getHits().getTotalHits().value(), equalTo(6L));
assertThat(resp.getHits().getTotalHits().relation(), equalTo(TotalHits.Relation.EQUAL_TO));
int expectedSize = innerFrom + maxExpectedSize > 6 ? 6 - innerFrom : maxExpectedSize;
assertThat(resp.getHits().getHits().length, equalTo(expectedSize));
for (int k = 0; k < expectedSize; k++) {
assertThat(resp.getHits().getAt(k).getId(), equalTo(expectedDocIds.get(k + innerFrom)));
}
});
}
public void testRRFWithAggs() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
// this one retrieves docs 1, 2, 4, 6, and 7
StandardRetrieverBuilder standard0 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_1")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(9L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_4")).boost(8L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(7L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_7")).boost(6L))
);
// this one retrieves docs 2 and 6 due to prefilter
StandardRetrieverBuilder standard1 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(20L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_3")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(5L))
);
standard1.getPreFilterQueryBuilders().add(QueryBuilders.queryStringQuery("search").defaultField(TEXT_FIELD));
// this one retrieves docs 2, 3, 6, and 7
KnnRetrieverBuilder knnRetrieverBuilder = new KnnRetrieverBuilder(
VECTOR_FIELD,
new float[] { 2.0f },
null,
10,
100,
null,
null,
null
);
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(standard0, null),
new CompoundRetrieverBuilder.RetrieverSource(standard1, null),
new CompoundRetrieverBuilder.RetrieverSource(knnRetrieverBuilder, null)
),
rankWindowSize,
rankConstant
)
);
source.size(1);
source.aggregation(AggregationBuilders.terms("topic_agg").field(TOPIC_FIELD));
SearchRequestBuilder req = client().prepareSearch(INDEX).setSource(source);
ElasticsearchAssertions.assertResponse(req, resp -> {
assertNull(resp.pointInTimeId());
assertNotNull(resp.getHits().getTotalHits());
assertThat(resp.getHits().getTotalHits().value(), equalTo(6L));
assertThat(resp.getHits().getTotalHits().relation(), equalTo(TotalHits.Relation.EQUAL_TO));
assertThat(resp.getHits().getHits().length, equalTo(1));
assertThat(resp.getHits().getAt(0).getId(), equalTo("doc_2"));
assertNotNull(resp.getAggregations());
assertNotNull(resp.getAggregations().get("topic_agg"));
Terms terms = resp.getAggregations().get("topic_agg");
assertThat(terms.getBucketByKey("technology").getDocCount(), equalTo(3L));
assertThat(terms.getBucketByKey("astronomy").getDocCount(), equalTo(1L));
assertThat(terms.getBucketByKey("biology").getDocCount(), equalTo(1L));
});
}
public void testRRFWithCollapse() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
// this one retrieves docs 1, 2, 4, 6, and 7
StandardRetrieverBuilder standard0 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_1")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(9L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_4")).boost(8L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(7L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_7")).boost(6L))
);
// this one retrieves docs 2 and 6 due to prefilter
StandardRetrieverBuilder standard1 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(20L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_3")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(5L))
);
standard1.getPreFilterQueryBuilders().add(QueryBuilders.queryStringQuery("search").defaultField(TEXT_FIELD));
// this one retrieves docs 2, 3, 6, and 7
KnnRetrieverBuilder knnRetrieverBuilder = new KnnRetrieverBuilder(
VECTOR_FIELD,
new float[] { 2.0f },
null,
10,
100,
null,
null,
null
);
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(standard0, null),
new CompoundRetrieverBuilder.RetrieverSource(standard1, null),
new CompoundRetrieverBuilder.RetrieverSource(knnRetrieverBuilder, null)
),
rankWindowSize,
rankConstant
)
);
source.collapse(
new CollapseBuilder(TOPIC_FIELD).setInnerHits(
new InnerHitBuilder("a").addSort(new FieldSortBuilder(DOC_FIELD).order(SortOrder.DESC)).setSize(10)
)
);
source.fetchField(TOPIC_FIELD);
SearchRequestBuilder req = client().prepareSearch(INDEX).setSource(source);
ElasticsearchAssertions.assertResponse(req, resp -> {
assertNull(resp.pointInTimeId());
assertNotNull(resp.getHits().getTotalHits());
assertThat(resp.getHits().getTotalHits().value(), equalTo(6L));
assertThat(resp.getHits().getTotalHits().relation(), equalTo(TotalHits.Relation.EQUAL_TO));
assertThat(resp.getHits().getHits().length, equalTo(4));
assertThat(resp.getHits().getAt(0).getId(), equalTo("doc_2"));
assertThat(resp.getHits().getAt(1).getId(), equalTo("doc_6"));
assertThat(resp.getHits().getAt(2).getId(), equalTo("doc_7"));
assertThat(resp.getHits().getAt(3).getId(), equalTo("doc_1"));
assertThat(resp.getHits().getAt(3).getInnerHits().get("a").getAt(0).getId(), equalTo("doc_4"));
assertThat(resp.getHits().getAt(3).getInnerHits().get("a").getAt(1).getId(), equalTo("doc_3"));
assertThat(resp.getHits().getAt(3).getInnerHits().get("a").getAt(2).getId(), equalTo("doc_1"));
});
}
public void testRRFRetrieverWithCollapseAndAggs() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
// this one retrieves docs 1, 2, 4, 6, and 7
StandardRetrieverBuilder standard0 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_1")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(9L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_4")).boost(8L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(7L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_7")).boost(6L))
);
// this one retrieves docs 2 and 6 due to prefilter
StandardRetrieverBuilder standard1 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(20L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_3")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(5L))
);
standard1.getPreFilterQueryBuilders().add(QueryBuilders.queryStringQuery("search").defaultField(TEXT_FIELD));
// this one retrieves docs 2, 3, 6, and 7
KnnRetrieverBuilder knnRetrieverBuilder = new KnnRetrieverBuilder(
VECTOR_FIELD,
new float[] { 2.0f },
null,
10,
100,
null,
null,
null
);
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(standard0, null),
new CompoundRetrieverBuilder.RetrieverSource(standard1, null),
new CompoundRetrieverBuilder.RetrieverSource(knnRetrieverBuilder, null)
),
rankWindowSize,
rankConstant
)
);
source.collapse(
new CollapseBuilder(TOPIC_FIELD).setInnerHits(
new InnerHitBuilder("a").addSort(new FieldSortBuilder(DOC_FIELD).order(SortOrder.DESC)).setSize(10)
)
);
source.fetchField(TOPIC_FIELD);
source.aggregation(AggregationBuilders.terms("topic_agg").field(TOPIC_FIELD));
SearchRequestBuilder req = client().prepareSearch(INDEX).setSource(source);
ElasticsearchAssertions.assertResponse(req, resp -> {
assertNull(resp.pointInTimeId());
assertNotNull(resp.getHits().getTotalHits());
assertThat(resp.getHits().getTotalHits().value(), equalTo(6L));
assertThat(resp.getHits().getTotalHits().relation(), equalTo(TotalHits.Relation.EQUAL_TO));
assertThat(resp.getHits().getHits().length, equalTo(4));
assertThat(resp.getHits().getAt(0).getId(), equalTo("doc_2"));
assertThat(resp.getHits().getAt(1).getId(), equalTo("doc_6"));
assertThat(resp.getHits().getAt(2).getId(), equalTo("doc_7"));
assertThat(resp.getHits().getAt(3).getId(), equalTo("doc_1"));
assertThat(resp.getHits().getAt(3).getInnerHits().get("a").getAt(0).getId(), equalTo("doc_4"));
assertThat(resp.getHits().getAt(3).getInnerHits().get("a").getAt(1).getId(), equalTo("doc_3"));
assertThat(resp.getHits().getAt(3).getInnerHits().get("a").getAt(2).getId(), equalTo("doc_1"));
assertNotNull(resp.getAggregations());
assertNotNull(resp.getAggregations().get("topic_agg"));
Terms terms = resp.getAggregations().get("topic_agg");
assertThat(terms.getBucketByKey("technology").getDocCount(), equalTo(3L));
assertThat(terms.getBucketByKey("astronomy").getDocCount(), equalTo(1L));
assertThat(terms.getBucketByKey("biology").getDocCount(), equalTo(1L));
});
}
public void testMultipleRRFRetrievers() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
// this one retrieves docs 1, 2, 4, 6, and 7
StandardRetrieverBuilder standard0 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_1")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(9L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_4")).boost(8L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(7L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_7")).boost(6L))
);
// this one retrieves docs 2 and 6 due to prefilter
StandardRetrieverBuilder standard1 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(20L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_3")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(5L))
);
standard1.getPreFilterQueryBuilders().add(QueryBuilders.queryStringQuery("search").defaultField(TEXT_FIELD));
// this one retrieves docs 2, 3, 6, and 7
KnnRetrieverBuilder knnRetrieverBuilder = new KnnRetrieverBuilder(
VECTOR_FIELD,
new float[] { 2.0f },
null,
10,
100,
null,
null,
null
);
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(
// this one returns docs 6, 7, 1, 3, and 4
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(standard0, null),
new CompoundRetrieverBuilder.RetrieverSource(standard1, null),
new CompoundRetrieverBuilder.RetrieverSource(knnRetrieverBuilder, null)
),
rankWindowSize,
rankConstant
),
null
),
// this one bring just doc 7 which should be ranked first eventually
new CompoundRetrieverBuilder.RetrieverSource(
new KnnRetrieverBuilder(VECTOR_FIELD, new float[] { 7.0f }, null, 1, 100, null, null, null),
null
)
),
rankWindowSize,
rankConstant
)
);
SearchRequestBuilder req = client().prepareSearch(INDEX).setSource(source);
ElasticsearchAssertions.assertResponse(req, resp -> {
assertNull(resp.pointInTimeId());
assertNotNull(resp.getHits().getTotalHits());
assertThat(resp.getHits().getTotalHits().value(), equalTo(6L));
assertThat(resp.getHits().getTotalHits().relation(), equalTo(TotalHits.Relation.EQUAL_TO));
assertThat(resp.getHits().getAt(0).getId(), equalTo("doc_7"));
assertThat(resp.getHits().getAt(1).getId(), equalTo("doc_2"));
assertThat(resp.getHits().getAt(2).getId(), equalTo("doc_6"));
assertThat(resp.getHits().getAt(3).getId(), equalTo("doc_1"));
assertThat(resp.getHits().getAt(4).getId(), equalTo("doc_3"));
assertThat(resp.getHits().getAt(5).getId(), equalTo("doc_4"));
});
}
public void testRRFExplainWithNamedRetrievers() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
// this one retrieves docs 1, 2, 4, 6, and 7
StandardRetrieverBuilder standard0 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_1")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(9L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_4")).boost(8L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(7L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_7")).boost(6L))
);
standard0.retrieverName("my_custom_retriever");
// this one retrieves docs 2 and 6 due to prefilter
StandardRetrieverBuilder standard1 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(20L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_3")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(5L))
);
standard1.getPreFilterQueryBuilders().add(QueryBuilders.queryStringQuery("search").defaultField(TEXT_FIELD));
// this one retrieves docs 2, 3, 6, and 7
KnnRetrieverBuilder knnRetrieverBuilder = new KnnRetrieverBuilder(
VECTOR_FIELD,
new float[] { 2.0f },
null,
10,
100,
null,
null,
null
);
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(standard0, null),
new CompoundRetrieverBuilder.RetrieverSource(standard1, null),
new CompoundRetrieverBuilder.RetrieverSource(knnRetrieverBuilder, null)
),
rankWindowSize,
rankConstant
)
);
source.explain(true);
source.size(1);
SearchRequestBuilder req = client().prepareSearch(INDEX).setSource(source);
ElasticsearchAssertions.assertResponse(req, resp -> {
assertNull(resp.pointInTimeId());
assertNotNull(resp.getHits().getTotalHits());
assertThat(resp.getHits().getTotalHits().value(), equalTo(6L));
assertThat(resp.getHits().getTotalHits().relation(), equalTo(TotalHits.Relation.EQUAL_TO));
assertThat(resp.getHits().getHits().length, equalTo(1));
assertThat(resp.getHits().getAt(0).getId(), equalTo("doc_2"));
assertThat(resp.getHits().getAt(0).getExplanation().isMatch(), equalTo(true));
assertThat(resp.getHits().getAt(0).getExplanation().getDescription(), containsString("sum of:"));
assertThat(resp.getHits().getAt(0).getExplanation().getDetails().length, equalTo(2));
var rrfDetails = resp.getHits().getAt(0).getExplanation().getDetails()[0];
assertThat(rrfDetails.getDetails().length, equalTo(3));
assertThat(rrfDetails.getDescription(), containsString("computed for initial ranks [2, 1, 1]"));
assertThat(rrfDetails.getDetails()[0].getDescription(), containsString("for rank [2] in query at index [0]"));
assertThat(rrfDetails.getDetails()[0].getDescription(), containsString("[my_custom_retriever]"));
assertThat(rrfDetails.getDetails()[1].getDescription(), containsString("for rank [1] in query at index [1]"));
assertThat(rrfDetails.getDetails()[2].getDescription(), containsString("for rank [1] in query at index [2]"));
});
}
public void testRRFExplainWithAnotherNestedRRF() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
// this one retrieves docs 1, 2, 4, 6, and 7
StandardRetrieverBuilder standard0 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_1")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(9L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_4")).boost(8L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(7L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_7")).boost(6L))
);
standard0.retrieverName("my_custom_retriever");
// this one retrieves docs 2 and 6 due to prefilter
StandardRetrieverBuilder standard1 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(20L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_3")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(5L))
);
standard1.getPreFilterQueryBuilders().add(QueryBuilders.queryStringQuery("search").defaultField(TEXT_FIELD));
// this one retrieves docs 2, 3, 6, and 7
KnnRetrieverBuilder knnRetrieverBuilder = new KnnRetrieverBuilder(
VECTOR_FIELD,
new float[] { 2.0f },
null,
10,
100,
null,
null,
null
);
RRFRetrieverBuilder nestedRRF = new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(standard0, null),
new CompoundRetrieverBuilder.RetrieverSource(standard1, null),
new CompoundRetrieverBuilder.RetrieverSource(knnRetrieverBuilder, null)
),
rankWindowSize,
rankConstant
);
StandardRetrieverBuilder standard2 = new StandardRetrieverBuilder(
QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(20L)
);
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(nestedRRF, null),
new CompoundRetrieverBuilder.RetrieverSource(standard2, null)
),
rankWindowSize,
rankConstant
)
);
source.explain(true);
source.size(1);
SearchRequestBuilder req = client().prepareSearch(INDEX).setSource(source);
ElasticsearchAssertions.assertResponse(req, resp -> {
assertNull(resp.pointInTimeId());
assertNotNull(resp.getHits().getTotalHits());
assertThat(resp.getHits().getTotalHits().value(), equalTo(6L));
assertThat(resp.getHits().getTotalHits().relation(), equalTo(TotalHits.Relation.EQUAL_TO));
assertThat(resp.getHits().getHits().length, equalTo(1));
assertThat(resp.getHits().getAt(0).getId(), equalTo("doc_6"));
assertThat(resp.getHits().getAt(0).getExplanation().isMatch(), equalTo(true));
assertThat(resp.getHits().getAt(0).getExplanation().getDescription(), containsString("sum of:"));
assertThat(resp.getHits().getAt(0).getExplanation().getDetails().length, equalTo(2));
var rrfTopLevel = resp.getHits().getAt(0).getExplanation().getDetails()[0];
assertThat(rrfTopLevel.getDetails().length, equalTo(2));
assertThat(rrfTopLevel.getDescription(), containsString("computed for initial ranks [2, 1]"));
assertThat(rrfTopLevel.getDetails()[0].getDetails()[0].getDescription(), containsString("rrf score"));
assertThat(rrfTopLevel.getDetails()[1].getDetails()[0].getDescription(), containsString("ConstantScore"));
var rrfDetails = rrfTopLevel.getDetails()[0].getDetails()[0];
assertThat(rrfDetails.getDetails().length, equalTo(3));
assertThat(rrfDetails.getDescription(), containsString("computed for initial ranks [4, 2, 3]"));
assertThat(rrfDetails.getDetails()[0].getDescription(), containsString("for rank [4] in query at index [0]"));
assertThat(rrfDetails.getDetails()[0].getDescription(), containsString("for rank [4] in query at index [0]"));
assertThat(rrfDetails.getDetails()[0].getDescription(), containsString("[my_custom_retriever]"));
assertThat(rrfDetails.getDetails()[1].getDescription(), containsString("for rank [2] in query at index [1]"));
assertThat(rrfDetails.getDetails()[2].getDescription(), containsString("for rank [3] in query at index [2]"));
});
}
public void testRRFInnerRetrieverAll4xxSearchErrors() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
// this will throw a 4xx error during evaluation
StandardRetrieverBuilder standard0 = new StandardRetrieverBuilder(
QueryBuilders.constantScoreQuery(QueryBuilders.rangeQuery(VECTOR_FIELD).gte(10))
);
StandardRetrieverBuilder standard1 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(20L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_3")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(5L))
);
standard1.getPreFilterQueryBuilders().add(QueryBuilders.queryStringQuery("search").defaultField(TEXT_FIELD));
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(standard0, null),
new CompoundRetrieverBuilder.RetrieverSource(standard1, null)
),
rankWindowSize,
rankConstant
)
);
SearchRequestBuilder req = client().prepareSearch(INDEX).setSource(source);
Exception ex = expectThrows(ElasticsearchStatusException.class, req::get);
assertThat(ex, instanceOf(ElasticsearchStatusException.class));
assertThat(
ex.getMessage(),
containsString(
"[rrf] search failed - retrievers '[standard]' returned errors. All failures are attached as suppressed exceptions."
)
);
assertThat(ExceptionsHelper.status(ex), equalTo(RestStatus.BAD_REQUEST));
assertThat(ex.getSuppressed().length, equalTo(1));
assertThat(ex.getSuppressed()[0].getCause().getCause(), instanceOf(IllegalArgumentException.class));
}
public void testRRFInnerRetrieverMultipleErrorsOne5xx() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
// this will throw a 4xx error during evaluation
StandardRetrieverBuilder standard0 = new StandardRetrieverBuilder(
QueryBuilders.constantScoreQuery(QueryBuilders.rangeQuery(VECTOR_FIELD).gte(10))
);
// this will throw a 5xx error
TestRetrieverBuilder testRetrieverBuilder = new TestRetrieverBuilder("val") {
@Override
public void extractToSearchSourceBuilder(SearchSourceBuilder searchSourceBuilder, boolean compoundUsed) {
searchSourceBuilder.aggregation(AggregationBuilders.avg("some_invalid_param"));
}
};
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(standard0, null),
new CompoundRetrieverBuilder.RetrieverSource(testRetrieverBuilder, null)
),
rankWindowSize,
rankConstant
)
);
SearchRequestBuilder req = client().prepareSearch(INDEX).setSource(source);
Exception ex = expectThrows(ElasticsearchStatusException.class, req::get);
assertThat(ex, instanceOf(ElasticsearchStatusException.class));
assertThat(
ex.getMessage(),
containsString(
"[rrf] search failed - retrievers '[standard, test]' returned errors. All failures are attached as suppressed exceptions."
)
);
assertThat(ExceptionsHelper.status(ex), equalTo(RestStatus.INTERNAL_SERVER_ERROR));
assertThat(ex.getSuppressed().length, equalTo(2));
assertThat(ex.getSuppressed()[0].getCause().getCause(), instanceOf(IllegalArgumentException.class));
assertThat(ex.getSuppressed()[1].getCause().getCause(), instanceOf(IllegalStateException.class));
}
public void testRRFInnerRetrieverErrorWhenExtractingToSource() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
TestRetrieverBuilder failingRetriever = new TestRetrieverBuilder("some value") {
@Override
public QueryBuilder topDocsQuery() {
return QueryBuilders.matchAllQuery();
}
@Override
public void extractToSearchSourceBuilder(SearchSourceBuilder searchSourceBuilder, boolean compoundUsed) {
throw new UnsupportedOperationException("simulated failure");
}
};
StandardRetrieverBuilder standard1 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(20L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_3")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(5L))
);
standard1.getPreFilterQueryBuilders().add(QueryBuilders.queryStringQuery("search").defaultField(TEXT_FIELD));
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(failingRetriever, null),
new CompoundRetrieverBuilder.RetrieverSource(standard1, null)
),
rankWindowSize,
rankConstant
)
);
source.size(1);
expectThrows(UnsupportedOperationException.class, () -> client().prepareSearch(INDEX).setSource(source).get());
}
public void testRRFInnerRetrieverErrorOnTopDocs() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
TestRetrieverBuilder failingRetriever = new TestRetrieverBuilder("some value") {
@Override
public QueryBuilder topDocsQuery() {
throw new UnsupportedOperationException("simulated failure");
}
@Override
public void extractToSearchSourceBuilder(SearchSourceBuilder searchSourceBuilder, boolean compoundUsed) {
searchSourceBuilder.query(QueryBuilders.matchAllQuery());
}
};
StandardRetrieverBuilder standard1 = new StandardRetrieverBuilder(
QueryBuilders.boolQuery()
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_2")).boost(20L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_3")).boost(10L))
.should(QueryBuilders.constantScoreQuery(QueryBuilders.idsQuery().addIds("doc_6")).boost(5L))
);
standard1.getPreFilterQueryBuilders().add(QueryBuilders.queryStringQuery("search").defaultField(TEXT_FIELD));
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(failingRetriever, null),
new CompoundRetrieverBuilder.RetrieverSource(standard1, null)
),
rankWindowSize,
rankConstant
)
);
source.size(1);
source.aggregation(AggregationBuilders.terms("topic_agg").field(TOPIC_FIELD));
expectThrows(UnsupportedOperationException.class, () -> client().prepareSearch(INDEX).setSource(source).get());
}
public void testRRFFiltersPropagatedToKnnQueryVectorBuilder() {
final int rankWindowSize = 100;
final int rankConstant = 10;
SearchSourceBuilder source = new SearchSourceBuilder();
// this will retriever all but 7 only due to top-level filter
StandardRetrieverBuilder standardRetriever = new StandardRetrieverBuilder(QueryBuilders.matchAllQuery());
// this will too retrieve just doc 7
KnnRetrieverBuilder knnRetriever = new KnnRetrieverBuilder(
"vector",
null,
new TestQueryVectorBuilderPlugin.TestQueryVectorBuilder(new float[] { 3 }),
10,
10,
null,
null,
null
);
source.retriever(
new RRFRetrieverBuilder(
Arrays.asList(
new CompoundRetrieverBuilder.RetrieverSource(standardRetriever, null),
new CompoundRetrieverBuilder.RetrieverSource(knnRetriever, null)
),
rankWindowSize,
rankConstant
)
);
source.retriever().getPreFilterQueryBuilders().add(QueryBuilders.boolQuery().must(QueryBuilders.termQuery(DOC_FIELD, "doc_7")));
source.size(10);
SearchRequestBuilder req = client().prepareSearch(INDEX).setSource(source);
ElasticsearchAssertions.assertResponse(req, resp -> {
assertNull(resp.pointInTimeId());
assertNotNull(resp.getHits().getTotalHits());
assertThat(resp.getHits().getTotalHits().value(), equalTo(1L));
assertThat(resp.getHits().getHits()[0].getId(), equalTo("doc_7"));
});
}
public void testRewriteOnce() {
final float[] vector = new float[] { 1 };
AtomicInteger numAsyncCalls = new AtomicInteger();
QueryVectorBuilder vectorBuilder = new QueryVectorBuilder() {
@Override
public void buildVector(Client client, ActionListener<float[]> listener) {
numAsyncCalls.incrementAndGet();
listener.onResponse(vector);
}
@Override
public String getWriteableName() {
throw new IllegalStateException("Should not be called");
}
@Override
public TransportVersion getMinimalSupportedVersion() {
throw new IllegalStateException("Should not be called");
}
@Override
public void writeTo(StreamOutput out) throws IOException {
throw new IllegalStateException("Should not be called");
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
throw new IllegalStateException("Should not be called");
}
};
var knn = new KnnRetrieverBuilder("vector", null, vectorBuilder, 10, 10, null, null, null);
var standard = new StandardRetrieverBuilder(new KnnVectorQueryBuilder("vector", vectorBuilder, 10, 10, 10f, null));
var rrf = new RRFRetrieverBuilder(
List.of(new CompoundRetrieverBuilder.RetrieverSource(knn, null), new CompoundRetrieverBuilder.RetrieverSource(standard, null)),
10,
10
);
assertResponse(
client().prepareSearch(INDEX).setSource(new SearchSourceBuilder().retriever(rrf)),
searchResponse -> assertThat(searchResponse.getHits().getTotalHits().value(), is(4L))
);
assertThat(numAsyncCalls.get(), equalTo(2));
// check that we use the rewritten vector to build the explain query
assertResponse(
client().prepareSearch(INDEX).setSource(new SearchSourceBuilder().retriever(rrf).explain(true)),
searchResponse -> assertThat(searchResponse.getHits().getTotalHits().value(), is(4L))
);
assertThat(numAsyncCalls.get(), equalTo(4));
}
}
|
RRFRetrieverBuilderIT
|
java
|
netty__netty
|
testsuite-native-image/src/main/java/io/netty/testsuite/svm/HttpNativeServer.java
|
{
"start": 6699,
"end": 6777
}
|
enum ____ {
NIO,
EPOLL,
IO_URING,
}
|
TransportType
|
java
|
apache__flink
|
flink-core/src/test/java/org/apache/flink/api/common/typeutils/base/BasicTypeSerializerUpgradeTestSpecifications.java
|
{
"start": 27079,
"end": 28101
}
|
class ____
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<NullValue> {
@Override
public TypeSerializer<NullValue> createUpgradedSerializer() {
return NullValueSerializer.INSTANCE;
}
@Override
public Condition<NullValue> testDataCondition() {
return new Condition<>(
NullValue.getInstance()::equals, "value is NullValue.getInstance()");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<NullValue>> schemaCompatibilityCondition(
FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAsIs();
}
}
// ----------------------------------------------------------------------------------------------
// Specification for "short-serializer"
// ----------------------------------------------------------------------------------------------
/** ShortSerializerSetup. */
public static final
|
NullValueSerializerVerifier
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CaffeineCacheEndpointBuilderFactory.java
|
{
"start": 24671,
"end": 25023
}
|
class ____ extends AbstractEndpointBuilder implements CaffeineCacheEndpointBuilder, AdvancedCaffeineCacheEndpointBuilder {
public CaffeineCacheEndpointBuilderImpl(String path) {
super(componentName, path);
}
}
return new CaffeineCacheEndpointBuilderImpl(path);
}
}
|
CaffeineCacheEndpointBuilderImpl
|
java
|
quarkusio__quarkus
|
integration-tests/oidc-wiremock/src/main/java/io/quarkus/it/keycloak/Product.java
|
{
"start": 40,
"end": 304
}
|
class ____ {
final String name;
final int quantity;
final String accessToken;
Product(String name, int quantity, String accessToken) {
this.name = name;
this.quantity = quantity;
this.accessToken = accessToken;
}
}
|
Product
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamTaskException.java
|
{
"start": 1014,
"end": 2110
}
|
class ____ extends RuntimeException {
/** Serial version UID for serialization interoperability. */
private static final long serialVersionUID = 8392043527067472439L;
/** Creates a compiler exception with no message and no cause. */
public StreamTaskException() {}
/**
* Creates a compiler exception with the given message and no cause.
*
* @param message The message for the exception.
*/
public StreamTaskException(String message) {
super(message);
}
/**
* Creates a compiler exception with the given cause and no message.
*
* @param cause The <tt>Throwable</tt> that caused this exception.
*/
public StreamTaskException(Throwable cause) {
super(cause);
}
/**
* Creates a compiler exception with the given message and cause.
*
* @param message The message for the exception.
* @param cause The <tt>Throwable</tt> that caused this exception.
*/
public StreamTaskException(String message, Throwable cause) {
super(message, cause);
}
}
|
StreamTaskException
|
java
|
apache__flink
|
flink-table/flink-table-common/src/main/java/org/apache/flink/table/factories/CatalogStoreFactory.java
|
{
"start": 2931,
"end": 3878
}
|
class ____ implements SessionManager {
* public SessionManagerImpl(DefaultContext defaultContext) {
* this.catalogStoreFactory = createCatalogStore();
* }
*
* @Override
* public void start() {
* // initialize the CatalogStoreFactory
* this.catalogStoreFactory(buildCatalogStoreContext());
* }
*
* @Override
* public synchronized Session openSession(SessionEnvironment environment) {
* // Create a new catalog store for this session.
* CatalogStore catalogStore = this.catalogStoreFactory.createCatalogStore(buildCatalogStoreContext());
*
* // Create a new CatalogManager using catalog store.
* }
*
* @Override
* public void stop() {
* // Close the CatalogStoreFactory when stopping the SessionManager.
* this.catalogStoreFactory.close();
* }
* }
* }</pre>
*/
@PublicEvolving
public
|
SessionManagerImpl
|
java
|
google__guice
|
core/test/com/googlecode/guice/GuiceJakartaTck.java
|
{
"start": 1308,
"end": 2247
}
|
class ____ extends TestCase {
public static Test suite() {
return Tck.testsFor(
Guice.createInjector(
new AbstractModule() {
@Override
protected void configure() {
bind(Car.class).to(Convertible.class);
bind(Seat.class).annotatedWith(Drivers.class).to(DriversSeat.class);
bind(Engine.class).to(V8Engine.class);
bind(Cupholder.class);
bind(Tire.class);
bind(FuelTank.class);
requestStaticInjection(Convertible.class, SpareTire.class);
}
@Provides
@Named("spare")
Tire provideSpareTire(SpareTire spare) {
return spare;
}
})
.getInstance(Car.class),
true,
true);
}
}
|
GuiceJakartaTck
|
java
|
elastic__elasticsearch
|
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/profile/RestUpdateProfileDataAction.java
|
{
"start": 1424,
"end": 3455
}
|
class ____ extends SecurityBaseRestHandler {
@SuppressWarnings("unchecked")
static final ConstructingObjectParser<Payload, Void> PARSER = new ConstructingObjectParser<>(
"update_profile_data_request_payload",
a -> new Payload((Map<String, Object>) a[0], (Map<String, Object>) a[1])
);
static {
PARSER.declareObject(optionalConstructorArg(), (p, c) -> p.map(), new ParseField("labels"));
PARSER.declareObject(optionalConstructorArg(), (p, c) -> p.map(), new ParseField("data"));
}
public RestUpdateProfileDataAction(Settings settings, XPackLicenseState licenseState) {
super(settings, licenseState);
}
@Override
public List<Route> routes() {
return List.of(new Route(PUT, "/_security/profile/{uid}/_data"), new Route(POST, "/_security/profile/{uid}/_data"));
}
@Override
public String getName() {
return "xpack_security_update_profile_data";
}
@Override
protected RestChannelConsumer innerPrepareRequest(RestRequest request, NodeClient client) throws IOException {
final String uid = request.param("uid");
final long ifPrimaryTerm = request.paramAsLong("if_primary_term", -1);
final long ifSeqNo = request.paramAsLong("if_seq_no", -1);
final RefreshPolicy refreshPolicy = RefreshPolicy.parse(request.param("refresh", "wait_for"));
final Payload payload;
try (var parser = request.contentParser()) {
payload = PARSER.parse(parser, null);
}
final UpdateProfileDataRequest updateProfileDataRequest = new UpdateProfileDataRequest(
uid,
payload.labels,
payload.data,
ifPrimaryTerm,
ifSeqNo,
refreshPolicy
);
return channel -> client.execute(UpdateProfileDataAction.INSTANCE, updateProfileDataRequest, new RestToXContentListener<>(channel));
}
record Payload(Map<String, Object> labels, Map<String, Object> data) {}
}
|
RestUpdateProfileDataAction
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/predicate/operator/comparison/NotEqualsNanosMillisEvaluator.java
|
{
"start": 1200,
"end": 5036
}
|
class ____ implements EvalOperator.ExpressionEvaluator {
private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(NotEqualsNanosMillisEvaluator.class);
private final Source source;
private final EvalOperator.ExpressionEvaluator lhs;
private final EvalOperator.ExpressionEvaluator rhs;
private final DriverContext driverContext;
private Warnings warnings;
public NotEqualsNanosMillisEvaluator(Source source, EvalOperator.ExpressionEvaluator lhs,
EvalOperator.ExpressionEvaluator rhs, DriverContext driverContext) {
this.source = source;
this.lhs = lhs;
this.rhs = rhs;
this.driverContext = driverContext;
}
@Override
public Block eval(Page page) {
try (LongBlock lhsBlock = (LongBlock) lhs.eval(page)) {
try (LongBlock rhsBlock = (LongBlock) rhs.eval(page)) {
LongVector lhsVector = lhsBlock.asVector();
if (lhsVector == null) {
return eval(page.getPositionCount(), lhsBlock, rhsBlock);
}
LongVector rhsVector = rhsBlock.asVector();
if (rhsVector == null) {
return eval(page.getPositionCount(), lhsBlock, rhsBlock);
}
return eval(page.getPositionCount(), lhsVector, rhsVector).asBlock();
}
}
}
@Override
public long baseRamBytesUsed() {
long baseRamBytesUsed = BASE_RAM_BYTES_USED;
baseRamBytesUsed += lhs.baseRamBytesUsed();
baseRamBytesUsed += rhs.baseRamBytesUsed();
return baseRamBytesUsed;
}
public BooleanBlock eval(int positionCount, LongBlock lhsBlock, LongBlock rhsBlock) {
try(BooleanBlock.Builder result = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
switch (lhsBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
switch (rhsBlock.getValueCount(p)) {
case 0:
result.appendNull();
continue position;
case 1:
break;
default:
warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value"));
result.appendNull();
continue position;
}
long lhs = lhsBlock.getLong(lhsBlock.getFirstValueIndex(p));
long rhs = rhsBlock.getLong(rhsBlock.getFirstValueIndex(p));
result.appendBoolean(NotEquals.processNanosMillis(lhs, rhs));
}
return result.build();
}
}
public BooleanVector eval(int positionCount, LongVector lhsVector, LongVector rhsVector) {
try(BooleanVector.FixedBuilder result = driverContext.blockFactory().newBooleanVectorFixedBuilder(positionCount)) {
position: for (int p = 0; p < positionCount; p++) {
long lhs = lhsVector.getLong(p);
long rhs = rhsVector.getLong(p);
result.appendBoolean(p, NotEquals.processNanosMillis(lhs, rhs));
}
return result.build();
}
}
@Override
public String toString() {
return "NotEqualsNanosMillisEvaluator[" + "lhs=" + lhs + ", rhs=" + rhs + "]";
}
@Override
public void close() {
Releasables.closeExpectNoException(lhs, rhs);
}
private Warnings warnings() {
if (warnings == null) {
this.warnings = Warnings.createWarnings(
driverContext.warningsMode(),
source.source().getLineNumber(),
source.source().getColumnNumber(),
source.text()
);
}
return warnings;
}
static
|
NotEqualsNanosMillisEvaluator
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/CheckReturnValueTest.java
|
{
"start": 6148,
"end": 6236
}
|
class ____ {
@CheckReturnValue
MyObject() {}
}
private abstract static
|
MyObject
|
java
|
resilience4j__resilience4j
|
resilience4j-spring-boot2/src/test/java/io/github/resilience4j/fallback/FallbackConfigurationOnMissingBeanTest.java
|
{
"start": 565,
"end": 823
}
|
class ____ {
@Autowired
private FallbackDecorators fallbackDecorators;
@Test
public void testSizeOfDecorators() {
assertThat(fallbackDecorators.getFallbackDecorators().size()).isEqualTo(4);
}
}
|
FallbackConfigurationOnMissingBeanTest
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/views/ViewSerializationTest.java
|
{
"start": 760,
"end": 1161
}
|
class ____
{
@JsonView(ViewA.class)
public String a = "1";
@JsonView({ViewAA.class, ViewB.class})
public String aa = "2";
@JsonView(ViewB.class)
public String getB() { return "3"; }
}
/**
* Bean with mix of explicitly annotated
* properties, and implicit ones that may or may
* not be included in views.
*/
static
|
Bean
|
java
|
spring-projects__spring-framework
|
spring-aop/src/main/java/org/springframework/aop/TrueMethodMatcher.java
|
{
"start": 896,
"end": 1792
}
|
class ____ implements MethodMatcher, Serializable {
public static final TrueMethodMatcher INSTANCE = new TrueMethodMatcher();
/**
* Enforce Singleton pattern.
*/
private TrueMethodMatcher() {
}
@Override
public boolean isRuntime() {
return false;
}
@Override
public boolean matches(Method method, Class<?> targetClass) {
return true;
}
@Override
public boolean matches(Method method, Class<?> targetClass, @Nullable Object... args) {
// Should never be invoked as isRuntime returns false.
throw new UnsupportedOperationException();
}
@Override
public String toString() {
return "MethodMatcher.TRUE";
}
/**
* Required to support serialization. Replaces with canonical
* instance on deserialization, protecting Singleton pattern.
* Alternative to overriding {@code equals()}.
*/
private Object readResolve() {
return INSTANCE;
}
}
|
TrueMethodMatcher
|
java
|
apache__camel
|
core/camel-core/src/test/java/org/apache/camel/issues/ContextScopedOnExceptionRouteScopedErrorHandlerRefIssueTwoRoutesTest.java
|
{
"start": 1106,
"end": 2769
}
|
class ____ extends ContextTestSupport {
@Test
public void testOnExceptionErrorHandlerRef() throws Exception {
getMockEndpoint("mock:a").expectedMessageCount(1);
getMockEndpoint("mock:handled").expectedMessageCount(1);
getMockEndpoint("mock:dead").expectedMessageCount(0);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Test
public void testOnExceptionErrorHandlerRefFoo() throws Exception {
getMockEndpoint("mock:a").expectedMessageCount(0);
getMockEndpoint("mock:handled").expectedMessageCount(0);
getMockEndpoint("mock:dead").expectedMessageCount(1);
template.sendBody("direct:foo", "Hello Foo");
assertMockEndpointsSatisfied();
}
@Override
protected Registry createCamelRegistry() throws Exception {
Registry jndi = super.createCamelRegistry();
jndi.bind("myDLC", new DeadLetterChannelBuilder("mock:dead"));
return jndi;
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
onException(IllegalArgumentException.class).handled(true).to("mock:handled").end();
from("direct:foo").errorHandler("myDLC").to("mock:foo")
.throwException(new IOException("Damn IO"));
from("direct:start").errorHandler("myDLC").to("mock:a")
.throwException(new IllegalArgumentException("Damn"));
}
};
}
}
|
ContextScopedOnExceptionRouteScopedErrorHandlerRefIssueTwoRoutesTest
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/metamodel/model/domain/IdentifiableDomainType.java
|
{
"start": 497,
"end": 1522
}
|
interface ____<J>
extends ManagedDomainType<J>, IdentifiableType<J> {
@Nullable PathSource<?> getIdentifierDescriptor();
@Override
<Y> SingularPersistentAttribute<? super J, Y> getId(Class<Y> type);
@Override
<Y> SingularPersistentAttribute<J, Y> getDeclaredId(Class<Y> type);
@Override
<Y> SingularPersistentAttribute<? super J, Y> getVersion(Class<Y> type);
@Override
<Y> SingularPersistentAttribute<J, Y> getDeclaredVersion(Class<Y> type);
@Override
Set<SingularAttribute<? super J, ?>> getIdClassAttributes();
@Override
SimpleDomainType<?> getIdType();
@Override
@Nullable IdentifiableDomainType<? super J> getSupertype();
boolean hasIdClass();
@Nullable SingularPersistentAttribute<? super J,?> findIdAttribute();
void visitIdClassAttributes(Consumer<SingularPersistentAttribute<? super J,?>> action);
@Nullable SingularPersistentAttribute<? super J, ?> findVersionAttribute();
@Nullable List<? extends PersistentAttribute<? super J, ?>> findNaturalIdAttributes();
}
|
IdentifiableDomainType
|
java
|
apache__spark
|
launcher/src/main/java/org/apache/spark/launcher/LauncherConnection.java
|
{
"start": 1330,
"end": 3136
}
|
class ____ implements Closeable, Runnable {
private static final Logger LOG = Logger.getLogger(LauncherConnection.class.getName());
private final Socket socket;
private final ObjectOutputStream out;
private volatile boolean closed;
LauncherConnection(Socket socket) throws IOException {
this.socket = socket;
this.out = new ObjectOutputStream(socket.getOutputStream());
this.closed = false;
}
protected abstract void handle(Message msg) throws IOException;
@Override
public void run() {
try {
FilteredObjectInputStream in = new FilteredObjectInputStream(socket.getInputStream());
while (isOpen()) {
Message msg = (Message) in.readObject();
handle(msg);
}
} catch (EOFException eof) {
// Remote side has closed the connection, just cleanup.
try {
close();
} catch (Exception unused) {
// no-op.
}
} catch (Exception e) {
if (!closed) {
LOG.log(Level.WARNING, "Error in inbound message handling.", e);
try {
close();
} catch (Exception unused) {
// no-op.
}
}
}
}
protected synchronized void send(Message msg) throws IOException {
try {
CommandBuilderUtils.checkState(!closed, "Disconnected.");
out.writeObject(msg);
out.flush();
} catch (IOException ioe) {
if (!closed) {
LOG.log(Level.WARNING, "Error when sending message.", ioe);
try {
close();
} catch (Exception unused) {
// no-op.
}
}
throw ioe;
}
}
@Override
public synchronized void close() throws IOException {
if (isOpen()) {
closed = true;
socket.close();
}
}
boolean isOpen() {
return !closed;
}
}
|
LauncherConnection
|
java
|
spring-projects__spring-data-jpa
|
spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/QueryRenderer.java
|
{
"start": 9729,
"end": 12106
}
|
class ____ implements QueryTokenStream {
protected QueryRenderer current = QueryRenderer.empty();
/**
* Append a collection of {@link QueryToken}s.
*
* @param tokens
* @return {@code this} builder.
*/
QueryRendererBuilder append(List<? extends QueryToken> tokens) {
return append(QueryRenderer.from(tokens));
}
/**
* Append a QueryRenderer.
*
* @param stream
* @return {@code this} builder.
*/
QueryRendererBuilder append(QueryTokenStream stream) {
if (stream.isEmpty()) {
return this;
}
current = current.append(stream);
return this;
}
/**
* Append a QueryRenderer inline.
*
* @param stream
* @return {@code this} builder.
*/
QueryRendererBuilder appendInline(QueryTokenStream stream) {
if (stream.isEmpty()) {
return this;
}
current = current.append(QueryRenderer.inline(stream));
return this;
}
/**
* Append a QueryRendererBuilder as expression.
*
* @param builder
* @return {@code this} builder.
*/
QueryRendererBuilder appendExpression(QueryRendererBuilder builder) {
return appendExpression(builder.current);
}
/**
* Append a QueryRenderer as expression.
*
* @param tokens
* @return {@code this} builder.
*/
QueryRendererBuilder appendExpression(QueryTokenStream tokens) {
if (tokens.isEmpty()) {
return this;
}
current = current.append(QueryRenderer.ofExpression(tokens));
return this;
}
@Override
public List<QueryToken> toList() {
return current.toList();
}
@Override
public Stream<QueryToken> stream() {
return current.stream();
}
@Override
public @Nullable QueryToken getFirst() {
return current.getFirst();
}
@Override
public @Nullable QueryToken getLast() {
return current.getLast();
}
@Override
public boolean isExpression() {
return current.isExpression();
}
@Override
public boolean isEmpty() {
return current.isEmpty();
}
@Override
public int size() {
return current.size();
}
@Override
public Iterator<QueryToken> iterator() {
return current.iterator();
}
@Override
public String toString() {
return current.render();
}
public QueryRenderer build() {
return current;
}
public QueryRenderer toInline() {
return new InlineRenderer(current);
}
}
private static
|
QueryRendererBuilder
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/StringSplitterTest.java
|
{
"start": 9285,
"end": 9711
}
|
class ____ {
void f() {
for (String s : Splitter.on('c').split("")) {}
for (String s : Splitter.on("abc").split("")) {}
}
}
""")
.doTest(TestMode.TEXT_MATCH);
}
@Test
public void negative() {
CompilationTestHelper.newInstance(StringSplitter.class, getClass())
.addSourceLines(
"Test.java",
"
|
Test
|
java
|
spring-projects__spring-framework
|
spring-jdbc/src/main/java/org/springframework/jdbc/datasource/DataSourceUtils.java
|
{
"start": 19528,
"end": 22369
}
|
class ____ implements TransactionSynchronization {
private final ConnectionHolder connectionHolder;
private final DataSource dataSource;
private final int order;
private boolean holderActive = true;
public ConnectionSynchronization(ConnectionHolder connectionHolder, DataSource dataSource) {
this.connectionHolder = connectionHolder;
this.dataSource = dataSource;
this.order = getConnectionSynchronizationOrder(dataSource);
}
@Override
public int getOrder() {
return this.order;
}
@Override
public void suspend() {
if (this.holderActive) {
TransactionSynchronizationManager.unbindResource(this.dataSource);
if (this.connectionHolder.hasConnection() && !this.connectionHolder.isOpen()) {
// Release Connection on suspend if the application doesn't keep
// a handle to it anymore. We will fetch a fresh Connection if the
// application accesses the ConnectionHolder again after resume,
// assuming that it will participate in the same transaction.
releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
this.connectionHolder.setConnection(null);
}
}
}
@Override
public void resume() {
if (this.holderActive) {
TransactionSynchronizationManager.bindResource(this.dataSource, this.connectionHolder);
}
}
@Override
public void beforeCompletion() {
// Release Connection early if the holder is not open anymore
// (that is, not used by another resource like a Hibernate Session
// that has its own cleanup via transaction synchronization),
// to avoid issues with strict JTA implementations that expect
// the close call before transaction completion.
if (!this.connectionHolder.isOpen()) {
TransactionSynchronizationManager.unbindResource(this.dataSource);
this.holderActive = false;
if (this.connectionHolder.hasConnection()) {
releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
}
}
}
@Override
public void afterCompletion(int status) {
// If we haven't closed the Connection in beforeCompletion,
// close it now. The holder might have been used for other
// cleanup in the meantime, for example by a Hibernate Session.
if (this.holderActive) {
// The thread-bound ConnectionHolder might not be available anymore,
// since afterCompletion might get called from a different thread.
TransactionSynchronizationManager.unbindResourceIfPossible(this.dataSource);
this.holderActive = false;
if (this.connectionHolder.hasConnection()) {
releaseConnection(this.connectionHolder.getConnection(), this.dataSource);
// Reset the ConnectionHolder: It might remain bound to the thread.
this.connectionHolder.setConnection(null);
}
}
this.connectionHolder.reset();
}
}
}
|
ConnectionSynchronization
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_3/ArrayGroupedCollection.java
|
{
"start": 130,
"end": 215
}
|
class ____<TKey, TItem> extends KeyedCollection<TKey, TItem[]> {
}
|
ArrayGroupedCollection
|
java
|
quarkusio__quarkus
|
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/profile/IfBuildProfileStereotypeTest.java
|
{
"start": 4897,
"end": 5189
}
|
class ____ extends TransitiveDevOnlyMyService {
@Override
public String hello() {
return MyServiceDevOnlyTransitiveOnSuperclassNotInheritable.class.getSimpleName();
}
}
@ApplicationScoped
static
|
MyServiceDevOnlyTransitiveOnSuperclassNotInheritable
|
java
|
apache__commons-lang
|
src/test/java/org/apache/commons/lang3/reflect/MethodUtilsTest.java
|
{
"start": 6164,
"end": 7115
}
|
class ____ {
public static String bar() {
return "bar()";
}
public static String bar(final double d) {
return "bar(double)";
}
public static String bar(final int i) {
return "bar(int)";
}
public static String bar(final Integer i) {
return "bar(Integer)";
}
public static String bar(final Integer i, final String... s) {
return "bar(Integer, String...)";
}
public static String bar(final long... s) {
return "bar(long...)";
}
public static String bar(final Object o) {
return "bar(Object)";
}
public static String bar(final String s) {
return "bar(String)";
}
public static String bar(final String... s) {
return "bar(String...)";
}
// This method is overloaded for the wrapper
|
TestBean
|
java
|
spring-projects__spring-security
|
core/src/test/java/org/springframework/security/authentication/DefaultAuthenticationEventPublisherTests.java
|
{
"start": 2384,
"end": 10436
}
|
class ____ {
DefaultAuthenticationEventPublisher publisher;
@Test
public void expectedDefaultMappingsAreSatisfied() {
this.publisher = new DefaultAuthenticationEventPublisher();
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
Authentication a = mock(Authentication.class);
Exception cause = new Exception();
Object extraInfo = new Object();
this.publisher.publishAuthenticationFailure(new BadCredentialsException(""), a);
this.publisher.publishAuthenticationFailure(new BadCredentialsException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
reset(appPublisher);
this.publisher.publishAuthenticationFailure(new UsernameNotFoundException(""), a);
this.publisher.publishAuthenticationFailure(new UsernameNotFoundException("", cause), a);
this.publisher.publishAuthenticationFailure(new AccountExpiredException(""), a);
this.publisher.publishAuthenticationFailure(new AccountExpiredException("", cause), a);
this.publisher.publishAuthenticationFailure(new ProviderNotFoundException(""), a);
this.publisher.publishAuthenticationFailure(new DisabledException(""), a);
this.publisher.publishAuthenticationFailure(new DisabledException("", cause), a);
this.publisher.publishAuthenticationFailure(new LockedException(""), a);
this.publisher.publishAuthenticationFailure(new LockedException("", cause), a);
this.publisher.publishAuthenticationFailure(new AuthenticationServiceException(""), a);
this.publisher.publishAuthenticationFailure(new AuthenticationServiceException("", cause), a);
this.publisher.publishAuthenticationFailure(new CredentialsExpiredException(""), a);
this.publisher.publishAuthenticationFailure(new CredentialsExpiredException("", cause), a);
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureExpiredEvent.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureProviderNotFoundEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureLockedEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureServiceExceptionEvent.class));
verify(appPublisher, times(2)).publishEvent(isA(AuthenticationFailureCredentialsExpiredEvent.class));
verifyNoMoreInteractions(appPublisher);
}
@Test
public void authenticationSuccessIsPublished() {
this.publisher = new DefaultAuthenticationEventPublisher();
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationSuccess(mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationSuccessEvent.class));
this.publisher.setApplicationEventPublisher(null);
// Should be ignored with null app publisher
this.publisher.publishAuthenticationSuccess(mock(Authentication.class));
}
@Test
public void additionalExceptionMappingsAreSupported() {
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
this.publisher.setAdditionalExceptionMappings(p);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new MockAuthenticationException("test"),
mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
@Test
public void missingEventClassExceptionCausesException() {
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), "NoSuchClass");
assertThatExceptionOfType(RuntimeException.class)
.isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(p));
}
@Test
public void unknownFailureExceptionIsIgnored() {
this.publisher = new DefaultAuthenticationEventPublisher();
Properties p = new Properties();
p.put(MockAuthenticationException.class.getName(), AuthenticationFailureDisabledEvent.class.getName());
this.publisher.setAdditionalExceptionMappings(p);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new AuthenticationException("") {
}, mock(Authentication.class));
verifyNoMoreInteractions(appPublisher);
}
@Test
public void emptyMapCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
this.publisher = new DefaultAuthenticationEventPublisher();
assertThatIllegalArgumentException().isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(mappings));
}
@Test
public void missingExceptionClassCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(null, AuthenticationFailureLockedEvent.class);
this.publisher = new DefaultAuthenticationEventPublisher();
assertThatIllegalArgumentException().isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(mappings));
}
@Test
public void missingEventClassAsMapValueCausesException() {
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(LockedException.class, null);
this.publisher = new DefaultAuthenticationEventPublisher();
assertThatIllegalArgumentException().isThrownBy(() -> this.publisher.setAdditionalExceptionMappings(mappings));
}
@Test
public void additionalExceptionMappingsUsingMapAreSupported() {
this.publisher = new DefaultAuthenticationEventPublisher();
Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings = new HashMap<>();
mappings.put(MockAuthenticationException.class, AuthenticationFailureDisabledEvent.class);
this.publisher.setAdditionalExceptionMappings(mappings);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new MockAuthenticationException("test"),
mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureDisabledEvent.class));
}
@Test
public void defaultAuthenticationFailureEventClassSetNullThen() {
this.publisher = new DefaultAuthenticationEventPublisher();
assertThatIllegalArgumentException()
.isThrownBy(() -> this.publisher.setDefaultAuthenticationFailureEvent(null));
}
@Test
public void defaultAuthenticationFailureEventIsPublished() {
this.publisher = new DefaultAuthenticationEventPublisher();
this.publisher.setDefaultAuthenticationFailureEvent(AuthenticationFailureBadCredentialsEvent.class);
ApplicationEventPublisher appPublisher = mock(ApplicationEventPublisher.class);
this.publisher.setApplicationEventPublisher(appPublisher);
this.publisher.publishAuthenticationFailure(new AuthenticationException("") {
}, mock(Authentication.class));
verify(appPublisher).publishEvent(isA(AuthenticationFailureBadCredentialsEvent.class));
}
@Test
public void defaultAuthenticationFailureEventMissingAppropriateConstructorThen() {
this.publisher = new DefaultAuthenticationEventPublisher();
assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> this.publisher
.setDefaultAuthenticationFailureEvent(AuthenticationFailureEventWithoutAppropriateConstructor.class));
}
private static final
|
DefaultAuthenticationEventPublisherTests
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/EscapeConvertedCharArrayTest.java
|
{
"start": 3486,
"end": 3836
}
|
class ____ implements AttributeConverter<String, char[]> {
@Override
public char[] convertToDatabaseColumn(String attribute) {
return attribute == null ? null : attribute.toCharArray();
}
@Override
public String convertToEntityAttribute(char[] dbData) {
return dbData == null ? null : new String( dbData );
}
}
}
|
StringToCharConverter
|
java
|
apache__camel
|
components/camel-azure/camel-azure-files/src/main/java/org/apache/camel/component/file/azure/FilesToken.java
|
{
"start": 1514,
"end": 6423
}
|
class ____ {
@UriParam(label = "security", description = "part of SAS token", secret = true)
private String sv;
@UriParam(label = "security", description = "part of account SAS token", secret = true)
private String ss;
@UriParam(label = "security", description = "part of SAS token", secret = true)
private String srt;
@UriParam(label = "security", description = "part of SAS token", secret = true)
private String sp;
@UriParam(label = "security", description = "part of SAS token", secret = true)
private String se;
@UriParam(label = "security", description = "part of SAS token", secret = true)
private String st;
@UriParam(label = "security", description = "part of SAS token", secret = true)
private String spr;
@UriParam(label = "security", description = "part of SAS token", secret = true)
private String sig;
@UriParam(label = "security", description = "part of service SAS token", secret = true)
private String si;
@UriParam(label = "security", description = "part of service SAS token", secret = true)
private String sr;
@UriParam(label = "security", description = "part of service SAS token", secret = true)
private String sdd;
@UriParam(label = "security", description = "part of SAS token", secret = true)
private String sip;
public void setSv(String sv) {
this.sv = sv;
}
public void setSs(String ss) {
this.ss = ss;
}
public void setSrt(String srt) {
this.srt = srt;
}
public void setSp(String sp) {
this.sp = sp;
}
public void setSe(String se) {
this.se = se;
}
public void setSt(String st) {
this.st = st;
}
public void setSpr(String spr) {
this.spr = spr;
}
public void setSig(String sig) {
this.sig = sig;
}
public void setSi(String si) {
this.si = si;
}
public void setSr(String sr) {
this.sr = sr;
}
public void setSdd(String sdd) {
this.sdd = sdd;
}
public void setSip(String sip) {
this.sip = sip;
}
boolean isInvalid() {
return sig == null || sv == null || se == null || !(isAccountTokenForFilesService() || isFilesServiceToken());
}
private boolean isAccountTokenForFilesService() {
return ss != null && ss.contains("f");
}
private boolean isFilesServiceToken() {
return sr != null && (sr.contains("f") || sr.contains("s"));
}
// sv=2021-12-02&ss=f&srt=o&sp=rwdlc&se=2023-05-05T19:27:05Z&st=2023-04-28T11:27:05Z&spr=https&sig=TCU0PcBjrxRbKOW%2FLA7HrPLISin6FXLNkRtLvmxkvhY%3D"
// params in Azure order
public String toURIQuery() {
try {
return Stream
.of(e("sv", sv), e("ss", ss), e("srt", srt), e("sp", sp), e("se", se), e("st", st),
e("spr", spr), e("sig", sig), e("si", si), e("sr", sr), e("sdd", sdd), e("sip", sip))
.filter(Objects::nonNull)
.collect(Collectors.joining("&"));
} catch (URISyntaxException e) {
return null;
}
}
private String e(String param, String value) throws URISyntaxException {
if (value == null || value.isBlank()) {
return null;
}
return param + "=" + FilesURIStrings.encodeTokenValue(value);
}
@Override
public int hashCode() {
return Objects.hash(sdd, se, si, sig, sip, sp, spr, sr, srt, ss, st, sv);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
FilesToken other = (FilesToken) obj;
return Objects.equals(sdd, other.sdd) && Objects.equals(se, other.se)
&& Objects.equals(si, other.si) && Objects.equals(sig, other.sig)
&& Objects.equals(sip, other.sip) && Objects.equals(sp, other.sp)
&& Objects.equals(spr, other.spr) && Objects.equals(sr, other.sr)
&& Objects.equals(srt, other.srt) && Objects.equals(ss, other.ss)
&& Objects.equals(st, other.st) && Objects.equals(sv, other.sv);
}
String getSv() {
return sv;
}
String getSs() {
return ss;
}
String getSrt() {
return srt;
}
String getSp() {
return sp;
}
String getSe() {
return se;
}
String getSt() {
return st;
}
String getSpr() {
return spr;
}
String getSig() {
return sig;
}
String getSi() {
return si;
}
String getSr() {
return sr;
}
String getSdd() {
return sdd;
}
String getSip() {
return sip;
}
}
|
FilesToken
|
java
|
elastic__elasticsearch
|
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/AuthenticationFailureHandler.java
|
{
"start": 1909,
"end": 6782
}
|
interface ____ {
/**
* This method is called when there has been an authentication failure for the given REST request and authentication
* token.
*
* @param request The request that was being authenticated when the exception occurred
* @param token The token that was extracted from the request
* @param context The context of the request that failed authentication that could not be authenticated
* @return ElasticsearchSecurityException with the appropriate headers and message
*/
ElasticsearchSecurityException failedAuthentication(HttpPreRequest request, AuthenticationToken token, ThreadContext context);
/**
* This method is called when there has been an authentication failure for the given message and token
*
* @param message The transport message that could not be authenticated
* @param token The token that was extracted from the message
* @param action The name of the action that the message is trying to perform
* @param context The context of the request that failed authentication that could not be authenticated
* @return ElasticsearchSecurityException with the appropriate headers and message
*/
ElasticsearchSecurityException failedAuthentication(
TransportRequest message,
AuthenticationToken token,
String action,
ThreadContext context
);
/**
* The method is called when an exception has occurred while processing the REST request. This could be an error that
* occurred while attempting to extract a token or while attempting to authenticate the request
*
* @param request The request that was being authenticated when the exception occurred
* @param e The exception that was thrown
* @param context The context of the request that failed authentication that could not be authenticated
* @return ElasticsearchSecurityException with the appropriate headers and message
*/
ElasticsearchSecurityException exceptionProcessingRequest(HttpPreRequest request, Exception e, ThreadContext context);
/**
* The method is called when an exception has occurred while processing the transport message. This could be an error that
* occurred while attempting to extract a token or while attempting to authenticate the request
*
* @param message The message that was being authenticated when the exception occurred
* @param action The name of the action that the message is trying to perform
* @param e The exception that was thrown
* @param context The context of the request that failed authentication that could not be authenticated
* @return ElasticsearchSecurityException with the appropriate headers and message
*/
ElasticsearchSecurityException exceptionProcessingRequest(TransportRequest message, String action, Exception e, ThreadContext context);
/**
* This method is called when a REST request is received and no authentication token could be extracted AND anonymous
* access is disabled. If anonymous access is enabled, this method will not be called
*
* @param request The request that did not have a token
* @param context The context of the request that failed authentication that could not be authenticated
* @return ElasticsearchSecurityException with the appropriate headers and message
*/
ElasticsearchSecurityException missingToken(HttpPreRequest request, ThreadContext context);
/**
* This method is called when a transport message is received and no authentication token could be extracted AND
* anonymous access is disabled. If anonymous access is enabled this method will not be called
*
* @param message The message that did not have a token
* @param action The name of the action that the message is trying to perform
* @param context The context of the request that failed authentication that could not be authenticated
* @return ElasticsearchSecurityException with the appropriate headers and message
*/
ElasticsearchSecurityException missingToken(TransportRequest message, String action, ThreadContext context);
/**
* This method is called when anonymous access is enabled, a request does not pass authorization with the anonymous
* user, AND the anonymous service is configured to throw an authentication exception instead of an authorization
* exception
*
* @param action the action that failed authorization for anonymous access
* @param context The context of the request that failed authentication that could not be authenticated
* @return ElasticsearchSecurityException with the appropriate headers and message
*/
ElasticsearchSecurityException authenticationRequired(String action, ThreadContext context);
}
|
AuthenticationFailureHandler
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-nfs/src/main/java/org/apache/hadoop/nfs/nfs3/response/MKDIR3Response.java
|
{
"start": 1122,
"end": 2672
}
|
class ____ extends NFS3Response {
private final FileHandle objFileHandle;
private final Nfs3FileAttributes objAttr;
private final WccData dirWcc;
public MKDIR3Response(int status) {
this(status, null, null, new WccData(null, null));
}
public MKDIR3Response(int status, FileHandle handle, Nfs3FileAttributes attr,
WccData dirWcc) {
super(status);
this.objFileHandle = handle;
this.objAttr = attr;
this.dirWcc = dirWcc;
}
public FileHandle getObjFileHandle() {
return objFileHandle;
}
public Nfs3FileAttributes getObjAttr() {
return objAttr;
}
public WccData getDirWcc() {
return dirWcc;
}
public static MKDIR3Response deserialize(XDR xdr) {
int status = xdr.readInt();
FileHandle objFileHandle = new FileHandle();
Nfs3FileAttributes objAttr = null;
WccData dirWcc;
if (status == Nfs3Status.NFS3_OK) {
xdr.readBoolean();
objFileHandle.deserialize(xdr);
xdr.readBoolean();
objAttr = Nfs3FileAttributes.deserialize(xdr);
}
dirWcc = WccData.deserialize(xdr);
return new MKDIR3Response(status, objFileHandle, objAttr, dirWcc);
}
@Override
public XDR serialize(XDR out, int xid, Verifier verifier) {
super.serialize(out, xid, verifier);
if (getStatus() == Nfs3Status.NFS3_OK) {
out.writeBoolean(true); // Handle follows
objFileHandle.serialize(out);
out.writeBoolean(true); // Attributes follow
objAttr.serialize(out);
}
dirWcc.serialize(out);
return out;
}
}
|
MKDIR3Response
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/action/admin/cluster/storedscripts/GetStoredScriptRequest.java
|
{
"start": 933,
"end": 2304
}
|
class ____ extends MasterNodeReadRequest<GetStoredScriptRequest> {
protected String id;
GetStoredScriptRequest(TimeValue masterNodeTimeout) {
super(masterNodeTimeout);
}
public GetStoredScriptRequest(TimeValue masterNodeTimeout, String id) {
super(masterNodeTimeout);
this.id = id;
}
public GetStoredScriptRequest(StreamInput in) throws IOException {
super(in);
id = in.readString();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(id);
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (id == null || id.isEmpty()) {
validationException = addValidationError("must specify id for stored script", validationException);
} else if (id.contains("#")) {
validationException = addValidationError("id cannot contain '#' for stored script", validationException);
}
return validationException;
}
public String id() {
return id;
}
public GetStoredScriptRequest id(String id) {
this.id = id;
return this;
}
@Override
public String toString() {
return "get script [" + id + "]";
}
}
|
GetStoredScriptRequest
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLCreateTableStatement.java
|
{
"start": 1486,
"end": 53471
}
|
class ____ extends SQLStatementImpl implements SQLDDLStatement, SQLCreateStatement {
protected int features;
protected SQLExprTableSource tableSource;
protected List<SQLTableElement> tableElementList = new ArrayList<SQLTableElement>();
// for postgresql
protected SQLExprTableSource inherits;
protected SQLSelect select;
protected SQLExpr comment;
protected SQLExprTableSource like;
protected Boolean compress;
protected Boolean logging;
protected SQLName tablespace;
protected SQLPartitionBy partitionBy;
protected SQLPartitionOf partitionOf;
protected SQLPartitionBy localPartitioning;
protected SQLUnique unique;
protected SQLExpr storedAs;
protected SQLExpr storedBy;
protected SQLExpr location;
protected SQLExpr engine;
protected SQLOrderBy orderBy;
protected boolean onCommitPreserveRows;
protected boolean onCommitDeleteRows;
// for odps & hive
protected SQLExternalRecordFormat rowFormat;
protected final List<SQLColumnDefinition> partitionColumns = new ArrayList<SQLColumnDefinition>(2);
protected ClusteringType clusteringType;
protected final List<SQLSelectOrderByItem> clusteredBy = new ArrayList<SQLSelectOrderByItem>();
protected final List<SQLSelectOrderByItem> sortedBy = new ArrayList<SQLSelectOrderByItem>();
protected boolean isAutoBucket;
protected int buckets;
protected int shards;
protected final List<SQLAssignItem> tableOptions = new ArrayList<SQLAssignItem>();
// protected final List<SQLAssignItem> tblProperties = new ArrayList<SQLAssignItem>();
protected boolean replace;
protected boolean ignore;
protected boolean single; // polardbx
protected SQLExpr lifeCycle;
public SQLCreateTableStatement() {
isAutoBucket = false;
}
public SQLCreateTableStatement(DbType dbType) {
super(dbType);
isAutoBucket = false;
}
@Override
protected void accept0(SQLASTVisitor v) {
if (v.visit(this)) {
acceptChild(v);
}
v.endVisit(this);
}
protected void acceptChild(SQLASTVisitor v) {
this.acceptChild(v, tableSource);
this.acceptChild(v, tableElementList);
this.acceptChild(v, inherits);
this.acceptChild(v, select);
this.acceptChild(v, comment);
this.acceptChild(v, like);
this.acceptChild(v, tablespace);
this.acceptChild(v, partitionBy);
this.acceptChild(v, localPartitioning);
this.acceptChild(v, storedAs);
this.acceptChild(v, storedBy);
this.acceptChild(v, location);
this.acceptChild(v, unique);
this.acceptChild(v, partitionColumns);
this.acceptChild(v, clusteredBy);
this.acceptChild(v, sortedBy);
this.acceptChild(v, tableOptions);
// this.acceptChild(v, tblProperties);
this.acceptChild(v, lifeCycle);
}
public boolean isAutoBucket() {
return isAutoBucket;
}
public void setAutoBucket(boolean autoBucket) {
isAutoBucket = autoBucket;
}
public SQLExpr getEngine() {
return engine;
}
public void setEngine(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.engine = x;
}
public SQLOrderBy getOrderBy() {
return orderBy;
}
public void setOrderBy(SQLOrderBy orderBy) {
if (orderBy != null) {
orderBy.setParent(this);
}
this.orderBy = orderBy;
}
public SQLExpr getComment() {
return comment;
}
public void setComment(SQLExpr comment) {
if (comment != null) {
comment.setParent(this);
}
this.comment = comment;
}
public SQLName getName() {
if (tableSource == null) {
return null;
}
return (SQLName) tableSource.getExpr();
}
public String getTableName() {
SQLName name = getName();
if (name == null) {
return null;
}
return name.getSimpleName();
}
public String getSchema() {
SQLName name = getName();
if (name == null) {
return null;
}
if (name instanceof SQLPropertyExpr) {
return ((SQLPropertyExpr) name).getOwnernName();
}
return null;
}
public void setSchema(String name) {
if (this.tableSource == null) {
return;
}
tableSource.setSchema(name);
}
public void setName(SQLName name) {
this.setTableSource(new SQLExprTableSource(name));
}
public void setName(String name) {
this.setName(new SQLIdentifierExpr(name));
}
public SQLExprTableSource getTableSource() {
return tableSource;
}
public void setTableSource(SQLExprTableSource tableSource) {
if (tableSource != null) {
tableSource.setParent(this);
}
this.tableSource = tableSource;
}
public void setTableName(String tableName) {
SQLExpr name = SQLUtils.toSQLExpr(tableName, dbType);
setTableSource(new SQLExprTableSource(name));
}
public void config(Feature feature) {
config(feature, true);
}
public boolean isEnabled(Feature feature) {
return feature.isEnabled(this.features);
}
public void config(Feature feature, boolean state) {
this.features = feature.config(this.features, state);
}
public boolean isTemporary() {
return Feature.Temporary.isEnabled(features);
}
public void setTemporary(boolean value) {
this.features = Feature.Temporary.config(features, value);
}
public List<SQLTableElement> getTableElementList() {
return tableElementList;
}
public SQLColumnDefinition getColumn(String columnName) {
long hashCode64 = FnvHash.hashCode64(columnName);
for (SQLTableElement e : tableElementList) {
if (e instanceof SQLColumnDefinition) {
SQLColumnDefinition column = (SQLColumnDefinition) e;
if (column.nameHashCode64() == hashCode64) {
return column;
}
}
}
return null;
}
public List<SQLColumnDefinition> getColumnDefinitions() {
ArrayList<SQLColumnDefinition> column = new ArrayList<SQLColumnDefinition>();
for (SQLTableElement element : this.tableElementList) {
if (element instanceof SQLColumnDefinition) {
column.add((SQLColumnDefinition) element);
}
}
return column;
}
public List<String> getColumnNames(boolean normalized) {
List<String> columnNames = new ArrayList<String>();
for (SQLColumnDefinition definition : getColumnDefinitions()) {
String columnName = (definition.getColumnName());
if (normalized) {
columnName = SQLUtils.normalize(columnName);
}
columnNames.add(columnName);
}
return columnNames;
}
public List<String> getColumnComments() {
List<String> comments = new ArrayList<String>();
for (SQLColumnDefinition definition : getColumnDefinitions()) {
comments.add(((SQLCharExpr) definition.getComment()).getText());
}
return comments;
}
public List<String> getPrimaryKeyNames() {
List<String> keys = new ArrayList<String>();
for (SQLTableElement element : this.tableElementList) {
if (element instanceof MySqlPrimaryKey) {
List<SQLSelectOrderByItem> columns = ((MySqlPrimaryKey) element).getColumns();
for (SQLSelectOrderByItem column : columns) {
keys.add(SQLUtils.normalize(column.getExpr().toString()));
}
}
}
return keys;
}
public void addColumn(String columnName, String dataType) {
SQLColumnDefinition column = new SQLColumnDefinition();
column.setName(columnName);
column.setDataType(
SQLParserUtils.createExprParser(dataType, dbType).parseDataType()
);
addColumn(column);
}
public void addColumn(String name, SQLDataType dataType) {
addColumn(new SQLColumnDefinition(name, dataType));
}
public void addColumn(SQLColumnDefinition column) {
if (column == null) {
throw new IllegalArgumentException();
}
column.setParent(this);
tableElementList.add(column);
}
public boolean isIfNotExists() {
return Feature.IfNotExists.isEnabled(features);
}
public void setIfNotExists(boolean value) {
this.features = Feature.IfNotExists.config(this.features, value);
}
public SQLExprTableSource getInherits() {
return inherits;
}
public void setInherits(SQLExprTableSource inherits) {
if (inherits != null) {
inherits.setParent(this);
}
this.inherits = inherits;
}
public SQLSelect getSelect() {
return select;
}
public void setSelect(SQLSelect select) {
if (select != null) {
select.setParent(this);
}
this.select = select;
}
public SQLUnique getUnique() {
return unique;
}
public void setUnique(SQLUnique unique) {
if (unique != null) {
unique.setParent(this);
}
this.unique = unique;
}
public SQLExprTableSource getLike() {
return like;
}
public void setLike(SQLName like) {
this.setLike(new SQLExprTableSource(like));
}
public void setLike(SQLExprTableSource like) {
if (like != null) {
like.setParent(this);
}
this.like = like;
}
public Boolean getCompress() {
return compress;
}
public void setCompress(Boolean compress) {
this.compress = compress;
}
public Boolean getLogging() {
return logging;
}
public void setLogging(Boolean logging) {
this.logging = logging;
}
public SQLName getTablespace() {
return tablespace;
}
public void setTablespace(SQLName x) {
if (x != null) {
x.setParent(this);
}
this.tablespace = x;
}
public SQLPartitionBy getPartitioning() {
return partitionBy;
}
public SQLPartitionBy getLocalPartitioning() {
return this.localPartitioning;
}
public void setPartitionBy(SQLPartitionBy partitionBy) {
if (partitionBy != null) {
partitionBy.setParent(this);
}
this.partitionBy = partitionBy;
}
public SQLPartitionOf getPartitionOf() {
return partitionOf;
}
public void setPartitionOf(SQLPartitionOf partitionOf) {
if (partitionOf != null) {
partitionOf.setParent(this);
}
this.partitionOf = partitionOf;
}
public void setLocalPartitioning(SQLPartitionBy localPartitioning) {
if (localPartitioning != null) {
localPartitioning.setParent(this);
}
this.localPartitioning = localPartitioning;
}
@Override
public List<SQLObject> getChildren() {
List<SQLObject> children = new ArrayList<SQLObject>();
children.add(tableSource);
children.addAll(tableElementList);
if (inherits != null) {
children.add(inherits);
}
if (select != null) {
children.add(select);
}
return children;
}
@SuppressWarnings("unchecked")
public void addBodyBeforeComment(List<String> comments) {
if (attributes == null) {
attributes = new HashMap<String, Object>(1);
}
List<String> attrComments = (List<String>) attributes.get("rowFormat.body_before_comment");
if (attrComments == null) {
attributes.put("rowFormat.body_before_comment", comments);
} else {
attrComments.addAll(comments);
}
}
@SuppressWarnings("unchecked")
public List<String> getBodyBeforeCommentsDirect() {
if (attributes == null) {
return null;
}
return (List<String>) attributes.get("rowFormat.body_before_comment");
}
public boolean hasBodyBeforeComment() {
List<String> comments = getBodyBeforeCommentsDirect();
if (comments == null) {
return false;
}
return !comments.isEmpty();
}
public String computeName() {
if (tableSource == null) {
return null;
}
SQLExpr expr = tableSource.getExpr();
if (expr instanceof SQLName) {
String name = ((SQLName) expr).getSimpleName();
return SQLUtils.normalize(name);
}
return null;
}
public boolean containsColumn(String columName) {
return findColumn(columName) == null;
}
public SQLColumnDefinition findColumn(String columName) {
if (columName == null) {
return null;
}
long hash = FnvHash.hashCode64(columName);
return findColumn(hash);
}
public SQLColumnDefinition findColumn(long columName_hash) {
for (SQLTableElement element : tableElementList) {
if (element instanceof SQLColumnDefinition) {
SQLColumnDefinition column = (SQLColumnDefinition) element;
if (column.nameHashCode64() == columName_hash) {
return column;
}
}
}
for (SQLColumnDefinition column : partitionColumns) {
if (column.nameHashCode64() == columName_hash) {
return column;
}
}
return null;
}
public boolean isPrimaryColumn(String columnName) {
SQLPrimaryKey pk = this.findPrimaryKey();
if (pk != null && pk.containsColumn(columnName)) {
return true;
}
for (SQLColumnDefinition element : this.getColumnDefinitions()) {
for (SQLColumnConstraint constraint : element.constraints) {
if (constraint instanceof SQLColumnPrimaryKey
&& SQLUtils.normalize(element.getColumnName()).equalsIgnoreCase(SQLUtils.normalize(columnName))) {
return true;
}
}
}
return false;
}
public boolean isPrimaryColumn(long columnNameHash) {
SQLPrimaryKey pk = this.findPrimaryKey();
if (pk == null) {
return false;
}
return pk.containsColumn(columnNameHash);
}
public boolean isOnlyPrimaryKey(long columnNameHash) {
SQLPrimaryKey pk = this.findPrimaryKey();
if (pk == null) {
return false;
}
return pk.containsColumn(columnNameHash) && pk.getColumns().size() == 1;
}
/**
* only for show columns
*/
public boolean isMUL(String columnName) {
for (SQLTableElement element : this.tableElementList) {
if (element instanceof MySqlUnique) {
MySqlUnique unique = (MySqlUnique) element;
SQLExpr column = unique.getColumns().get(0).getExpr();
if (column instanceof SQLIdentifierExpr
&& SQLUtils.nameEquals(columnName, ((SQLIdentifierExpr) column).getName())) {
return unique.getColumns().size() > 1;
} else if (column instanceof SQLMethodInvokeExpr
&& SQLUtils.nameEquals(((SQLMethodInvokeExpr) column).getMethodName(), columnName)) {
return true;
}
} else if (element instanceof MySqlKey) {
MySqlKey unique = (MySqlKey) element;
SQLExpr column = unique.getColumns().get(0).getExpr();
if (column instanceof SQLIdentifierExpr
&& SQLUtils.nameEquals(columnName, ((SQLIdentifierExpr) column).getName())) {
return true;
} else if (column instanceof SQLMethodInvokeExpr
&& SQLUtils.nameEquals(((SQLMethodInvokeExpr) column).getMethodName(), columnName)) {
return true;
}
}
}
return false;
}
/**
* only for show columns
*/
public boolean isUNI(String columnName) {
for (SQLTableElement element : this.tableElementList) {
if (element instanceof MySqlUnique) {
MySqlUnique unique = (MySqlUnique) element;
if (unique.getColumns().isEmpty()) {
continue;
}
SQLExpr column = unique.getColumns().get(0).getExpr();
if (column instanceof SQLIdentifierExpr
&& SQLUtils.nameEquals(columnName, ((SQLIdentifierExpr) column).getName())) {
return unique.getColumns().size() == 1;
} else if (column instanceof SQLMethodInvokeExpr
&& SQLUtils.nameEquals(((SQLMethodInvokeExpr) column).getMethodName(), columnName)) {
return true;
}
}
}
return false;
}
public MySqlUnique findUnique(String columnName) {
for (SQLTableElement element : this.tableElementList) {
if (element instanceof MySqlUnique) {
MySqlUnique unique = (MySqlUnique) element;
if (unique.containsColumn(columnName)) {
return unique;
}
}
}
return null;
}
public SQLTableElement findIndex(String columnName) {
for (SQLTableElement element : tableElementList) {
if (element instanceof SQLUniqueConstraint) {
SQLUniqueConstraint unique = (SQLUniqueConstraint) element;
for (SQLSelectOrderByItem item : unique.getColumns()) {
SQLExpr columnExpr = item.getExpr();
if (columnExpr instanceof SQLIdentifierExpr) {
String keyColumName = ((SQLIdentifierExpr) columnExpr).getName();
keyColumName = SQLUtils.normalize(keyColumName);
if (keyColumName.equalsIgnoreCase(columnName)) {
return element;
}
}
}
} else if (element instanceof MySqlTableIndex) {
List<SQLSelectOrderByItem> indexColumns = ((MySqlTableIndex) element).getColumns();
for (SQLSelectOrderByItem orderByItem : indexColumns) {
SQLExpr columnExpr = orderByItem.getExpr();
if (columnExpr instanceof SQLIdentifierExpr) {
String keyColumName = ((SQLIdentifierExpr) columnExpr).getName();
keyColumName = SQLUtils.normalize(keyColumName);
if (keyColumName.equalsIgnoreCase(columnName)) {
return element;
}
}
}
}
}
return null;
}
public void forEachColumn(Consumer<SQLColumnDefinition> columnConsumer) {
if (columnConsumer == null) {
return;
}
for (SQLTableElement element : this.tableElementList) {
if (element instanceof SQLColumnDefinition) {
columnConsumer.accept((SQLColumnDefinition) element);
}
}
}
public SQLPrimaryKey findPrimaryKey() {
for (SQLTableElement element : this.tableElementList) {
if (element instanceof SQLPrimaryKey) {
return (SQLPrimaryKey) element;
}
}
return null;
}
public List<SQLForeignKeyConstraint> findForeignKey() {
List<SQLForeignKeyConstraint> fkList = new ArrayList<SQLForeignKeyConstraint>();
for (SQLTableElement element : this.tableElementList) {
if (element instanceof SQLForeignKeyConstraint) {
fkList.add((SQLForeignKeyConstraint) element);
}
}
return fkList;
}
public boolean hashForeignKey() {
for (SQLTableElement element : this.tableElementList) {
if (element instanceof SQLForeignKeyConstraint) {
return true;
}
}
return false;
}
public boolean isReferenced(SQLName tableName) {
if (tableName == null) {
return false;
}
return isReferenced(tableName.getSimpleName());
}
public boolean isReferenced(String tableName) {
if (tableName == null) {
return false;
}
tableName = SQLUtils.normalize(tableName);
for (SQLTableElement element : this.tableElementList) {
if (element instanceof SQLForeignKeyConstraint) {
SQLForeignKeyConstraint fk = (SQLForeignKeyConstraint) element;
String refTableName = fk.getReferencedTableName().getSimpleName();
if (SQLUtils.nameEquals(tableName, refTableName)) {
return true;
}
}
}
return false;
}
public SQLAlterTableStatement foreignKeyToAlterTable() {
SQLAlterTableStatement stmt = new SQLAlterTableStatement();
for (int i = this.tableElementList.size() - 1; i >= 0; --i) {
SQLTableElement element = this.tableElementList.get(i);
if (element instanceof SQLForeignKeyConstraint) {
SQLForeignKeyConstraint fk = (SQLForeignKeyConstraint) element;
this.tableElementList.remove(i);
stmt.addItem(new SQLAlterTableAddConstraint(fk));
}
}
if (stmt.getItems().isEmpty()) {
return null;
}
stmt.setDbType(getDbType());
stmt.setTableSource(this.tableSource.clone());
Collections.reverse(stmt.getItems());
return stmt;
}
public static void sort(List<SQLStatement> stmtList) {
Map<String, SQLCreateTableStatement> tables = new HashMap<String, SQLCreateTableStatement>();
Map<String, List<SQLCreateTableStatement>> referencedTables = new HashMap<String, List<SQLCreateTableStatement>>();
for (SQLStatement stmt : stmtList) {
if (stmt instanceof SQLCreateTableStatement) {
SQLCreateTableStatement createTableStmt = (SQLCreateTableStatement) stmt;
String tableName = createTableStmt.getName().getSimpleName();
tableName = SQLUtils.normalize(tableName).toLowerCase();
tables.put(tableName, createTableStmt);
}
}
List<ListDG.Edge> edges = new ArrayList<ListDG.Edge>();
for (SQLCreateTableStatement stmt : tables.values()) {
for (SQLTableElement element : stmt.getTableElementList()) {
if (element instanceof SQLForeignKeyConstraint) {
SQLForeignKeyConstraint fk = (SQLForeignKeyConstraint) element;
String refTableName = fk.getReferencedTableName().getSimpleName();
refTableName = SQLUtils.normalize(refTableName).toLowerCase();
SQLCreateTableStatement refTable = tables.get(refTableName);
if (refTable != null) {
edges.add(new ListDG.Edge(stmt, refTable));
}
List<SQLCreateTableStatement> referencedList = referencedTables.get(refTableName);
if (referencedList == null) {
referencedList = new ArrayList<SQLCreateTableStatement>();
referencedTables.put(refTableName, referencedList);
}
referencedList.add(stmt);
}
}
}
for (SQLStatement stmt : stmtList) {
if (stmt instanceof OracleCreateSynonymStatement) {
OracleCreateSynonymStatement createSynonym = (OracleCreateSynonymStatement) stmt;
SQLName object = createSynonym.getObject();
String refTableName = object.getSimpleName();
SQLCreateTableStatement refTable = tables.get(refTableName);
if (refTable != null) {
edges.add(new ListDG.Edge(stmt, refTable));
}
}
}
ListDG dg = new ListDG(stmtList, edges);
SQLStatement[] tops = new SQLStatement[stmtList.size()];
if (dg.topologicalSort(tops)) {
for (int i = 0, size = stmtList.size(); i < size; ++i) {
stmtList.set(i, tops[size - i - 1]);
}
return;
}
List<SQLAlterTableStatement> alterList = new ArrayList<SQLAlterTableStatement>();
for (int i = edges.size() - 1; i >= 0; --i) {
ListDG.Edge edge = edges.get(i);
SQLCreateTableStatement from = (SQLCreateTableStatement) edge.from;
String fromTableName = from.getName().getSimpleName();
fromTableName = SQLUtils.normalize(fromTableName).toLowerCase();
if (referencedTables.containsKey(fromTableName)) {
edges.remove(i);
Arrays.fill(tops, null);
tops = new SQLStatement[stmtList.size()];
dg = new ListDG(stmtList, edges);
if (dg.topologicalSort(tops)) {
for (int j = 0, size = stmtList.size(); j < size; ++j) {
SQLStatement stmt = tops[size - j - 1];
stmtList.set(j, stmt);
}
SQLAlterTableStatement alter = from.foreignKeyToAlterTable();
alterList.add(alter);
stmtList.add(alter);
return;
}
edges.add(i, edge);
}
}
for (int i = edges.size() - 1; i >= 0; --i) {
ListDG.Edge edge = edges.get(i);
SQLCreateTableStatement from = (SQLCreateTableStatement) edge.from;
String fromTableName = from.getName().getSimpleName();
fromTableName = SQLUtils.normalize(fromTableName).toLowerCase();
if (referencedTables.containsKey(fromTableName)) {
SQLAlterTableStatement alter = from.foreignKeyToAlterTable();
edges.remove(i);
if (alter != null) {
alterList.add(alter);
}
Arrays.fill(tops, null);
tops = new SQLStatement[stmtList.size()];
dg = new ListDG(stmtList, edges);
if (dg.topologicalSort(tops)) {
for (int j = 0, size = stmtList.size(); j < size; ++j) {
SQLStatement stmt = tops[size - j - 1];
stmtList.set(j, stmt);
}
stmtList.addAll(alterList);
return;
}
}
}
}
public void simplify() {
SQLName name = getName();
if (name instanceof SQLPropertyExpr) {
String tableName = ((SQLPropertyExpr) name).getName();
tableName = SQLUtils.normalize(tableName);
String normalized = SQLUtils.normalize(tableName, dbType);
if (tableName != normalized) {
this.setName(normalized);
name = getName();
}
}
if (name instanceof SQLIdentifierExpr) {
SQLIdentifierExpr identExpr = (SQLIdentifierExpr) name;
String tableName = identExpr.getName();
String normalized = SQLUtils.normalize(tableName, dbType);
if (normalized != tableName) {
setName(normalized);
}
}
for (SQLTableElement element : this.tableElementList) {
if (element instanceof SQLColumnDefinition) {
SQLColumnDefinition column = (SQLColumnDefinition) element;
column.simplify();
} else if (element instanceof SQLConstraint) {
((SQLConstraint) element).simplify();
}
}
}
public boolean apply(SQLDropIndexStatement x) {
long indexNameHashCode64 = x.getIndexName().nameHashCode64();
for (int i = tableElementList.size() - 1; i >= 0; i--) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLUniqueConstraint) {
SQLUniqueConstraint unique = (SQLUniqueConstraint) e;
if (unique.getName() != null && unique.getName().nameHashCode64() == indexNameHashCode64) {
tableElementList.remove(i);
return true;
}
} else if (e instanceof MySqlTableIndex) {
MySqlTableIndex tableIndex = (MySqlTableIndex) e;
if (SQLUtils.nameEquals(tableIndex.getName(), x.getIndexName())) {
tableElementList.remove(i);
return true;
}
}
}
return false;
}
public boolean apply(SQLCommentStatement x) {
SQLName on = x.getOn().getName();
SQLExpr comment = x.getComment();
if (comment == null) {
return false;
}
SQLCommentStatement.Type type = x.getType();
if (type == SQLCommentStatement.Type.TABLE) {
if (!SQLUtils.nameEquals(getName(), on)) {
return false;
}
setComment(comment.clone());
return true;
} else if (type == SQLCommentStatement.Type.COLUMN) {
SQLPropertyExpr propertyExpr = (SQLPropertyExpr) on;
if (!SQLUtils.nameEquals(getName(), (SQLName) propertyExpr.getOwner())) {
return false;
}
SQLColumnDefinition column
= this.findColumn(
propertyExpr.nameHashCode64());
if (column != null) {
column.setComment(comment.clone());
}
return true;
}
return false;
}
public boolean apply(SQLAlterTableStatement alter) {
if (!SQLUtils.nameEquals(alter.getName(), this.getName())) {
return false;
}
int applyCount = 0;
for (SQLAlterTableItem item : alter.getItems()) {
if (alterApply(item)) {
applyCount++;
}
}
return applyCount > 0;
}
protected boolean alterApply(SQLAlterTableItem item) {
if (item instanceof SQLAlterTableDropColumnItem) {
return apply((SQLAlterTableDropColumnItem) item);
} else if (item instanceof SQLAlterTableAddColumn) {
return apply((SQLAlterTableAddColumn) item);
} else if (item instanceof SQLAlterTableAddConstraint) {
return apply((SQLAlterTableAddConstraint) item);
} else if (item instanceof SQLAlterTableDropPrimaryKey) {
return apply((SQLAlterTableDropPrimaryKey) item);
} else if (item instanceof SQLAlterTableDropIndex) {
return apply((SQLAlterTableDropIndex) item);
} else if (item instanceof SQLAlterTableDropConstraint) {
return apply((SQLAlterTableDropConstraint) item);
} else if (item instanceof SQLAlterTableDropCheck) {
return apply((SQLAlterTableDropCheck) item);
} else if (item instanceof SQLAlterTableDropKey) {
return apply((SQLAlterTableDropKey) item);
} else if (item instanceof SQLAlterTableDropForeignKey) {
return apply((SQLAlterTableDropForeignKey) item);
} else if (item instanceof SQLAlterTableRename) {
return apply((SQLAlterTableRename) item);
} else if (item instanceof SQLAlterTableRenameColumn) {
return apply((SQLAlterTableRenameColumn) item);
} else if (item instanceof SQLAlterTableAddIndex) {
return apply((SQLAlterTableAddIndex) item);
} else if (item instanceof SQLAlterTableTruncatePartition) {
return apply((SQLAlterTableTruncatePartition) item);
}
return false;
}
// SQLAlterTableRenameColumn
private boolean apply(SQLAlterTableRenameColumn item) {
int columnIndex = columnIndexOf(item.getColumn());
if (columnIndex == -1) {
return false;
}
SQLColumnDefinition column = (SQLColumnDefinition) tableElementList.get(columnIndex);
column.setName(item.getTo().clone());
return true;
}
public boolean renameColumn(String colummName, String newColumnName) {
if (colummName == null || newColumnName == null || newColumnName.length() == 0) {
return false;
}
int columnIndex = columnIndexOf(new SQLIdentifierExpr(colummName));
if (columnIndex == -1) {
return false;
}
SQLColumnDefinition column = (SQLColumnDefinition) tableElementList.get(columnIndex);
column.setName(new SQLIdentifierExpr(newColumnName));
return true;
}
private boolean apply(SQLAlterTableRename item) {
SQLName name = item.getToName();
if (name == null) {
return false;
}
this.setName(name.clone());
return true;
}
private boolean apply(SQLAlterTableDropForeignKey item) {
for (int i = tableElementList.size() - 1; i >= 0; i--) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLForeignKeyConstraint) {
SQLForeignKeyConstraint fk = (SQLForeignKeyConstraint) e;
if (SQLUtils.nameEquals(fk.getName(), item.getIndexName())) {
tableElementList.remove(i);
return true;
}
}
}
return false;
}
private boolean apply(SQLAlterTableDropKey item) {
for (int i = tableElementList.size() - 1; i >= 0; i--) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLUniqueConstraint) {
SQLUniqueConstraint unique = (SQLUniqueConstraint) e;
if (SQLUtils.nameEquals(unique.getName(), item.getKeyName())) {
tableElementList.remove(i);
return true;
}
}
}
return false;
}
private boolean apply(SQLAlterTableDropConstraint item) {
for (int i = tableElementList.size() - 1; i >= 0; i--) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLConstraint) {
SQLConstraint constraint = (SQLConstraint) e;
if (SQLUtils.nameEquals(constraint.getName(), item.getConstraintName())) {
tableElementList.remove(i);
return true;
}
}
}
return false;
}
private boolean apply(SQLAlterTableDropCheck item) {
for (int i = tableElementList.size() - 1; i >= 0; i--) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLConstraint) {
SQLConstraint constraint = (SQLConstraint) e;
if (SQLUtils.nameEquals(constraint.getName(), item.getCheckName())) {
tableElementList.remove(i);
return true;
}
}
}
return false;
}
private boolean apply(SQLAlterTableDropIndex item) {
for (int i = tableElementList.size() - 1; i >= 0; i--) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLUniqueConstraint) {
SQLUniqueConstraint unique = (SQLUniqueConstraint) e;
if (SQLUtils.nameEquals(unique.getName(), item.getIndexName())) {
tableElementList.remove(i);
return true;
}
} else if (e instanceof MySqlTableIndex) {
MySqlTableIndex tableIndex = (MySqlTableIndex) e;
if (SQLUtils.nameEquals(tableIndex.getName(), item.getIndexName())) {
tableElementList.remove(i);
return true;
}
}
}
return false;
}
private boolean apply(SQLAlterTableDropPrimaryKey item) {
for (int i = tableElementList.size() - 1; i >= 0; i--) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLPrimaryKey) {
tableElementList.remove(i);
return true;
}
}
return false;
}
private boolean apply(SQLAlterTableAddConstraint item) {
SQLName name = item.getConstraint().getName();
if (name != null) {
long nameHashCode = name.nameHashCode64();
for (int i = tableElementList.size() - 1; i >= 0; i--) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLConstraint) {
SQLName name1 = ((SQLConstraint) e).getName();
if (name1 != null && name1.nameHashCode64() == nameHashCode) {
return false;
}
}
}
}
tableElementList.add((SQLTableElement) item.getConstraint());
return true;
}
private boolean apply(SQLAlterTableDropColumnItem item) {
for (SQLName column : item.getColumns()) {
String columnName = column.getSimpleName();
for (int i = tableElementList.size() - 1; i >= 0; --i) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLColumnDefinition) {
if (SQLUtils.nameEquals(columnName, ((SQLColumnDefinition) e).getName().getSimpleName())) {
tableElementList.remove(i);
}
}
}
for (int i = tableElementList.size() - 1; i >= 0; --i) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLUnique) {
SQLUnique unique = (SQLUnique) e;
unique.applyDropColumn(column);
if (unique.getColumns().isEmpty()) {
tableElementList.remove(i);
}
} else if (e instanceof MySqlTableIndex) {
MySqlTableIndex index = (MySqlTableIndex) e;
index.applyDropColumn(column);
if (index.getColumns().isEmpty()) {
tableElementList.remove(i);
}
}
}
}
return true;
}
protected boolean apply(SQLAlterTableTruncatePartition item) {
return false;
}
protected boolean apply(SQLAlterTableAddIndex item) {
return false;
}
private boolean apply(SQLAlterTableAddColumn item) {
int startIndex = tableElementList.size();
if (item.isFirst()) {
startIndex = 0;
}
int afterIndex = columnIndexOf(item.getAfterColumn());
if (afterIndex != -1) {
startIndex = afterIndex + 1;
}
int beforeIndex = columnIndexOf(item.getFirstColumn());
if (beforeIndex != -1) {
startIndex = beforeIndex;
}
for (int i = 0; i < item.getColumns().size(); i++) {
SQLColumnDefinition column = item.getColumns().get(i);
int matchIndex = -1;
for (int j = 0; j < tableElementList.size(); j++) {
SQLTableElement element = tableElementList.get(j);
if (element instanceof SQLColumnDefinition) {
if (column.nameHashCode64() == (((SQLColumnDefinition) element)).nameHashCode64()) {
matchIndex = j;
break;
}
}
}
if (matchIndex != -1) {
return false;
}
tableElementList.add(i + startIndex, column);
column.setParent(this);
}
return true;
}
protected int columnIndexOf(SQLName column) {
if (column == null) {
return -1;
}
String columnName = column.getSimpleName();
for (int i = tableElementList.size() - 1; i >= 0; --i) {
SQLTableElement e = tableElementList.get(i);
if (e instanceof SQLColumnDefinition) {
if (SQLUtils.nameEquals(columnName, ((SQLColumnDefinition) e).getName().getSimpleName())) {
return i;
}
}
}
return -1;
}
public void cloneTo(SQLCreateTableStatement x) {
x.features = features;
if (tableSource != null) {
x.setTableSource(tableSource.clone());
}
for (SQLTableElement e : tableElementList) {
SQLTableElement e2 = e.clone();
e2.setParent(x);
x.tableElementList.add(e2);
}
for (SQLColumnDefinition e : partitionColumns) {
SQLColumnDefinition e2 = e.clone();
e2.setParent(x);
x.partitionColumns.add(e2);
}
if (inherits != null) {
x.setInherits(inherits.clone());
}
if (select != null) {
x.setSelect(select.clone());
}
if (comment != null) {
x.setComment(comment.clone());
}
if (partitionBy != null) {
x.setPartitionBy(partitionBy.clone());
}
if (like != null) {
x.setLike(like.clone());
}
x.compress = compress;
x.logging = logging;
if (tablespace != null) {
x.setTablespace(tablespace.clone());
}
if (partitionBy != null) {
x.setPartitionBy(partitionBy.clone());
}
if (localPartitioning != null) {
x.setLocalPartitioning(localPartitioning.clone());
}
if (storedAs != null) {
x.setStoredAs(storedAs.clone());
}
if (storedBy != null) {
x.setStoredBy(storedBy.clone());
}
if (lifeCycle != null) {
x.setLifeCycle(lifeCycle.clone());
}
if (location != null) {
x.setLocation(location.clone());
}
x.onCommitPreserveRows = onCommitPreserveRows;
x.onCommitDeleteRows = onCommitDeleteRows;
for (SQLAssignItem item : this.tableOptions) {
SQLAssignItem item2 = item.clone();
item2.setParent(item);
x.tableOptions.add(item2);
}
// for (SQLAssignItem item : this.tblProperties) {
// SQLAssignItem item2 = item.clone();
// item2.setParent(item);
// x.tblProperties.add(item2);
// }
if (rowFormat != null) {
x.setRowFormat(rowFormat.clone());
}
if (clusteringType != null) {
x.setClusteringType(clusteringType);
}
for (SQLSelectOrderByItem e : clusteredBy) {
SQLSelectOrderByItem e2 = e.clone();
e2.setParent(x);
x.clusteredBy.add(e2);
}
for (SQLSelectOrderByItem e : sortedBy) {
SQLSelectOrderByItem e2 = e.clone();
e2.setParent(x);
x.sortedBy.add(e2);
}
x.buckets = buckets;
x.shards = shards;
x.afterSemi = afterSemi;
}
public boolean isReplace() {
return replace;
}
public void setReplace(boolean replace) {
this.ignore = false;
this.replace = replace;
}
public boolean isIgnore() {
return ignore;
}
public void setIgnore(boolean ignore) {
this.replace = false;
this.ignore = ignore;
}
public boolean isSingle() {
return single;
}
public void setSingle(boolean single) {
this.single = single;
}
public SQLExpr getStoredAs() {
return storedAs;
}
public void setStoredAs(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.storedAs = x;
}
public SQLExpr getStoredBy() {
return storedBy;
}
public void setStoredBy(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.storedBy = x;
}
public SQLCreateTableStatement clone() {
SQLCreateTableStatement x = new SQLCreateTableStatement(dbType);
cloneTo(x);
return x;
}
public String toString() {
return SQLUtils.toSQLString(this, dbType);
}
public boolean isOnCommitPreserveRows() {
return onCommitPreserveRows;
}
public void setOnCommitPreserveRows(boolean onCommitPreserveRows) {
this.onCommitPreserveRows = onCommitPreserveRows;
}
// for odps & hive
public boolean isExternal() {
return Feature.External.isEnabled(features);
}
public void setExternal(boolean external) {
this.features = Feature.External.config(this.features, external);
}
public ClusteringType getClusteringType() {
return clusteringType;
}
public void setClusteringType(ClusteringType clusteringType) {
this.clusteringType = clusteringType;
}
public List<SQLSelectOrderByItem> getClusteredBy() {
return clusteredBy;
}
public void addClusteredByItem(SQLSelectOrderByItem item) {
item.setParent(this);
this.clusteredBy.add(item);
}
public List<SQLSelectOrderByItem> getSortedBy() {
return sortedBy;
}
public void addSortedByItem(SQLSelectOrderByItem item) {
item.setParent(this);
this.sortedBy.add(item);
}
public int getBuckets() {
return buckets;
}
public void setBuckets(int buckets) {
this.buckets = buckets;
}
public int getShards() {
return shards;
}
public void setShards(int shards) {
this.shards = shards;
}
public List<SQLColumnDefinition> getPartitionColumns() {
return partitionColumns;
}
public void addPartitionColumn(SQLColumnDefinition column) {
if (column != null) {
column.setParent(this);
}
this.partitionColumns.add(column);
}
public List<SQLAssignItem> getTableOptions() {
return tableOptions;
}
@Deprecated
public List<SQLAssignItem> getTblProperties() {
return tableOptions;
}
@Deprecated
public void addTblProperty(String name, SQLExpr value) {
addOption(name, value);
}
public SQLExternalRecordFormat getRowFormat() {
return rowFormat;
}
public void setRowFormat(SQLExternalRecordFormat x) {
if (x != null) {
x.setParent(this);
}
this.rowFormat = x;
}
public boolean isDimension() {
return Feature.Dimension.isEnabled(features);
}
public void setDimension(boolean dimension) {
this.features = Feature.Dimension.config(features, dimension);
}
public SQLExpr getLocation() {
return location;
}
public void setLocation(SQLExpr x) {
if (x != null) {
x.setParent(this);
}
this.location = x;
}
public void addOption(String name, SQLExpr value) {
SQLAssignItem assignItem = new SQLAssignItem(new SQLIdentifierExpr(name), value);
assignItem.setParent(this);
tableOptions.add(assignItem);
}
public SQLExpr getOption(String name) {
if (name == null) {
return null;
}
long hash64 = FnvHash.hashCode64(name);
for (SQLAssignItem item : tableOptions) {
final SQLExpr target = item.getTarget();
if (target instanceof SQLIdentifierExpr) {
if (((SQLIdentifierExpr) target).hashCode64() == hash64) {
return item.getValue();
}
}
}
return null;
}
public boolean removeOption(String name) {
if (name == null) {
return false;
}
long hash64 = FnvHash.hashCode64(name);
for (int i = tableOptions.size() - 1; i >= 0; i--) {
SQLAssignItem item = tableOptions.get(i);
final SQLExpr target = item.getTarget();
if (target instanceof SQLIdentifierExpr) {
if (((SQLIdentifierExpr) target).hashCode64() == hash64) {
tableOptions.remove(i);
return true;
}
}
}
return false;
}
public SQLExpr getTblProperty(String name) {
if (name == null) {
return null;
}
long hash64 = FnvHash.hashCode64(name);
for (SQLAssignItem item : tableOptions) {
final SQLExpr target = item.getTarget();
if (target instanceof SQLIdentifierExpr) {
if (((SQLIdentifierExpr) target).hashCode64() == hash64) {
return item.getValue();
}
}
}
return null;
}
public Object getOptionValue(String name) {
SQLExpr option = getOption(name);
if (option instanceof SQLValuableExpr) {
return ((SQLValuableExpr) option).getValue();
}
return null;
}
public Object getTblPropertyValue(String name) {
SQLExpr option = getTblProperty(name);
if (option instanceof SQLValuableExpr) {
return ((SQLValuableExpr) option).getValue();
}
return null;
}
public Object getOptionOrTblPropertyValue(String name) {
SQLExpr option = getTblProperty(name);
if (option == null) {
option = getOption(name);
}
if (option instanceof SQLValuableExpr) {
return ((SQLValuableExpr) option).getValue();
}
return null;
}
public String getCatalog() {
return null;
}
public boolean containsDuplicateColumnNames() {
return containsDuplicateColumnNames(false);
}
public boolean containsDuplicateColumnNames(boolean throwException) {
Map<Long, SQLTableElement> columnMap = new HashMap<Long, SQLTableElement>();
for (SQLTableElement item : tableElementList) {
if (item instanceof SQLColumnDefinition) {
SQLName columnName = ((SQLColumnDefinition) item).getName();
long nameHashCode64 = columnName.nameHashCode64();
SQLTableElement old = columnMap.put(nameHashCode64, item);
if (old != null) {
if (throwException) {
throw new ParserException("Table contains duplicate column names : "
+ SQLUtils.normalize(columnName.getSimpleName()));
}
return true;
}
}
}
return false;
}
public DDLObjectType getDDLObjectType() {
return DDLObjectType.TABLE;
}
public SQLExpr getLifeCycle() {
return lifeCycle;
}
public void setLifeCycle(SQLExpr x) {
if (x instanceof SQLNumberExpr) {
Number number = ((SQLNumberExpr) x).getNumber();
if (number instanceof BigDecimal) {
x = new SQLIntegerExpr(((BigDecimal) number).intValueExact());
}
}
if (x != null) {
x.setParent(this);
}
this.lifeCycle = x;
}
public
|
SQLCreateTableStatement
|
java
|
spring-projects__spring-framework
|
spring-jdbc/src/main/java/org/springframework/jdbc/core/metadata/HsqlTableMetaDataProvider.java
|
{
"start": 978,
"end": 1411
}
|
class ____ extends GenericTableMetaDataProvider {
public HsqlTableMetaDataProvider(DatabaseMetaData databaseMetaData) throws SQLException {
super(databaseMetaData);
}
@Override
public boolean isGetGeneratedKeysSimulated() {
return true;
}
@Override
public String getSimpleQueryForGetGeneratedKey(String tableName, String keyColumnName) {
return "select max(identity()) from " + tableName;
}
}
|
HsqlTableMetaDataProvider
|
java
|
elastic__elasticsearch
|
x-pack/plugin/identity-provider/src/main/java/org/elasticsearch/xpack/idp/saml/sp/ServiceProviderCacheSettings.java
|
{
"start": 661,
"end": 1557
}
|
class ____ {
private static final int CACHE_SIZE_DEFAULT = 1000;
private static final TimeValue CACHE_TTL_DEFAULT = TimeValue.timeValueMinutes(60);
public static final Setting<Integer> CACHE_SIZE = Setting.intSetting(
"xpack.idp.sp.cache.size",
CACHE_SIZE_DEFAULT,
Setting.Property.NodeScope
);
public static final Setting<TimeValue> CACHE_TTL = Setting.timeSetting(
"xpack.idp.sp.cache.ttl",
CACHE_TTL_DEFAULT,
Setting.Property.NodeScope
);
static <K, V> Cache<K, V> buildCache(Settings settings) {
return CacheBuilder.<K, V>builder()
.setMaximumWeight(CACHE_SIZE.get(settings))
.setExpireAfterAccess(CACHE_TTL.get(settings))
.build();
}
public static List<Setting<?>> getSettings() {
return List.of(CACHE_SIZE, CACHE_TTL);
}
}
|
ServiceProviderCacheSettings
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/http/server/observation/OpenTelemetryServerHttpObservationDocumentation.java
|
{
"start": 2253,
"end": 3877
}
|
enum ____ implements KeyName {
/**
* Name of the HTTP request method or {@value KeyValue#NONE_VALUE} if the
* request was not received properly. Normalized to known methods defined in internet standards.
*/
METHOD {
@Override
public String asString() {
return "http.request.method";
}
},
/**
* HTTP response raw status code, or {@code "UNKNOWN"} if no response was
* created.
*/
STATUS {
@Override
public String asString() {
return "http.response.status_code";
}
},
/**
* URI pattern for the matching handler if available, falling back to
* {@code REDIRECTION} for 3xx responses, {@code NOT_FOUND} for 404
* responses, {@code root} for requests with no path info, and
* {@code UNKNOWN} for all other requests.
*/
ROUTE {
@Override
public String asString() {
return "http.route";
}
},
/**
* Fully qualified name of the exception thrown during the exchange, or
* {@value KeyValue#NONE_VALUE} if no exception was thrown.
*/
EXCEPTION {
@Override
public String asString() {
return "error.type";
}
},
/**
* The scheme of the original client request, if known (e.g. from Forwarded#proto, X-Forwarded-Proto, or a similar header). Otherwise, the scheme of the immediate peer request.
*/
SCHEME {
@Override
public String asString() {
return "url.scheme";
}
},
/**
* Outcome of the HTTP server exchange.
* @see org.springframework.http.HttpStatus.Series
*/
OUTCOME {
@Override
public String asString() {
return "outcome";
}
}
}
public
|
LowCardinalityKeyNames
|
java
|
apache__kafka
|
metadata/src/main/java/org/apache/kafka/controller/QuorumFeatures.java
|
{
"start": 1187,
"end": 1286
}
|
class ____ the local node's supported feature flags as well as the quorum node IDs.
*/
public final
|
of
|
java
|
spring-projects__spring-boot
|
module/spring-boot-micrometer-metrics/src/main/java/org/springframework/boot/micrometer/metrics/autoconfigure/export/humio/HumioPropertiesConfigAdapter.java
|
{
"start": 1043,
"end": 1765
}
|
class ____ extends StepRegistryPropertiesConfigAdapter<HumioProperties> implements HumioConfig {
HumioPropertiesConfigAdapter(HumioProperties properties) {
super(properties);
}
@Override
public String prefix() {
return "management.humio.metrics.export";
}
@Override
public @Nullable String get(String k) {
return null;
}
@Override
public String uri() {
return obtain(HumioProperties::getUri, HumioConfig.super::uri);
}
@Override
public @Nullable Map<String, String> tags() {
return get(HumioProperties::getTags, HumioConfig.super::tags);
}
@Override
public @Nullable String apiToken() {
return get(HumioProperties::getApiToken, HumioConfig.super::apiToken);
}
}
|
HumioPropertiesConfigAdapter
|
java
|
spring-projects__spring-framework
|
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncManager.java
|
{
"start": 7880,
"end": 8997
}
|
class ____ and hash code.
* @param interceptors one or more interceptors to register
*/
public void registerCallableInterceptors(CallableProcessingInterceptor... interceptors) {
Assert.notNull(interceptors, "A CallableProcessingInterceptor is required");
for (CallableProcessingInterceptor interceptor : interceptors) {
String key = interceptor.getClass().getName() + ":" + interceptor.hashCode();
this.callableInterceptors.put(key, interceptor);
}
}
/**
* Register a {@link DeferredResultProcessingInterceptor} under the given key.
* @param key the key
* @param interceptor the interceptor to register
*/
public void registerDeferredResultInterceptor(Object key, DeferredResultProcessingInterceptor interceptor) {
Assert.notNull(key, "Key is required");
Assert.notNull(interceptor, "DeferredResultProcessingInterceptor is required");
this.deferredResultInterceptors.put(key, interceptor);
}
/**
* Register one or more {@link DeferredResultProcessingInterceptor DeferredResultProcessingInterceptors}
* without a specified key. The default key is derived from the interceptor
|
name
|
java
|
eclipse-vertx__vert.x
|
vertx-core/src/main/java/io/vertx/core/tracing/TracingPolicy.java
|
{
"start": 645,
"end": 916
}
|
enum ____ {
/**
* Do not propagate a trace, this is equivalent of disabling tracing.
*/
IGNORE,
/**
* Propagate an existing trace.
*/
PROPAGATE,
/**
* Reuse an existing trace or create a new trace when no one exist.
*/
ALWAYS
}
|
TracingPolicy
|
java
|
apache__camel
|
components/camel-aws/camel-aws2-sns/src/test/java/org/apache/camel/component/aws2/sns/integration/SnsComponentFifoManualIT.java
|
{
"start": 1777,
"end": 3236
}
|
class ____ extends CamelTestSupport {
@Test
public void sendInOnly() {
Exchange exchange = template.send("direct:start", ExchangePattern.InOnly, new Processor() {
public void process(Exchange exchange) {
exchange.getIn().setHeader(Sns2Constants.SUBJECT, "This is my subject");
exchange.getIn().setBody("This is my message text.");
}
});
assertNotNull(exchange.getIn().getHeader(Sns2Constants.MESSAGE_ID));
}
@Test
public void sendInOut() {
Exchange exchange = template.send("direct:start", ExchangePattern.InOut, new Processor() {
public void process(Exchange exchange) {
exchange.getIn().setHeader(Sns2Constants.SUBJECT, "This is my subject");
exchange.getIn().setBody("This is my message text.");
}
});
assertNotNull(exchange.getMessage().getHeader(Sns2Constants.MESSAGE_ID));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.to("aws2-sns://Order.fifo?accessKey=RAW({{aws.manual.access.key}})&secretKey=RAW({{aws.manual.secret.key}})®ion=eu-west-1&subject=The+subject+message&messageGroupIdStrategy=useExchangeId&autoCreateTopic=true");
}
};
}
}
|
SnsComponentFifoManualIT
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/jsontype/PolymorphicDeserSubtypeCheck5016Test.java
|
{
"start": 1176,
"end": 1258
}
|
class ____ extends Plant {
public String name = "tree";
}
static
|
Tree
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/ParameterResolverTests.java
|
{
"start": 12883,
"end": 13398
}
|
class ____ {
private final TestInfo outerTestInfo;
private final CustomType outerCustomType;
AnnotatedParameterConstructorInjectionTestCase(TestInfo testInfo, @CustomAnnotation CustomType customType) {
this.outerTestInfo = testInfo;
this.outerCustomType = customType;
}
@Test
void test() {
assertNotNull(this.outerTestInfo);
assertNotNull(this.outerCustomType);
}
@Nested
// See https://github.com/junit-team/junit-framework/issues/1345
|
AnnotatedParameterConstructorInjectionTestCase
|
java
|
greenrobot__greendao
|
DaoCore/src/main/java/org/greenrobot/greendao/async/AsyncOperationExecutor.java
|
{
"start": 1226,
"end": 14615
}
|
class ____ implements Runnable, Handler.Callback {
private static ExecutorService executorService = Executors.newCachedThreadPool();
private final BlockingQueue<AsyncOperation> queue;
private volatile boolean executorRunning;
private volatile int maxOperationCountToMerge;
private volatile AsyncOperationListener listener;
private volatile AsyncOperationListener listenerMainThread;
private volatile int waitForMergeMillis;
private int countOperationsEnqueued;
private int countOperationsCompleted;
private Handler handlerMainThread;
private int lastSequenceNumber;
AsyncOperationExecutor() {
queue = new LinkedBlockingQueue<AsyncOperation>();
maxOperationCountToMerge = 50;
waitForMergeMillis = 50;
}
public void enqueue(AsyncOperation operation) {
synchronized (this) {
operation.sequenceNumber = ++lastSequenceNumber;
queue.add(operation);
countOperationsEnqueued++;
if (!executorRunning) {
executorRunning = true;
executorService.execute(this);
}
}
}
public int getMaxOperationCountToMerge() {
return maxOperationCountToMerge;
}
public void setMaxOperationCountToMerge(int maxOperationCountToMerge) {
this.maxOperationCountToMerge = maxOperationCountToMerge;
}
public int getWaitForMergeMillis() {
return waitForMergeMillis;
}
public void setWaitForMergeMillis(int waitForMergeMillis) {
this.waitForMergeMillis = waitForMergeMillis;
}
public AsyncOperationListener getListener() {
return listener;
}
public void setListener(AsyncOperationListener listener) {
this.listener = listener;
}
public AsyncOperationListener getListenerMainThread() {
return listenerMainThread;
}
public void setListenerMainThread(AsyncOperationListener listenerMainThread) {
this.listenerMainThread = listenerMainThread;
}
public synchronized boolean isCompleted() {
return countOperationsEnqueued == countOperationsCompleted;
}
/**
* Waits until all enqueued operations are complete. If the thread gets interrupted, any
* {@link InterruptedException} will be rethrown as a {@link DaoException}.
*/
public synchronized void waitForCompletion() {
while (!isCompleted()) {
try {
wait();
} catch (InterruptedException e) {
throw new DaoException("Interrupted while waiting for all operations to complete", e);
}
}
}
/**
* Waits until all enqueued operations are complete, but at most the given amount of milliseconds. If the thread
* gets interrupted, any {@link InterruptedException} will be rethrown as a {@link DaoException}.
*
* @return true if operations completed in the given time frame.
*/
public synchronized boolean waitForCompletion(int maxMillis) {
if (!isCompleted()) {
try {
wait(maxMillis);
} catch (InterruptedException e) {
throw new DaoException("Interrupted while waiting for all operations to complete", e);
}
}
return isCompleted();
}
@Override
public void run() {
try {
try {
while (true) {
AsyncOperation operation = queue.poll(1, TimeUnit.SECONDS);
if (operation == null) {
synchronized (this) {
// Check again, this time in synchronized to be in sync with enqueue(AsyncOperation)
operation = queue.poll();
if (operation == null) {
// set flag while still inside synchronized
executorRunning = false;
return;
}
}
}
if (operation.isMergeTx()) {
// Wait some ms for another operation to merge because a TX is expensive
AsyncOperation operation2 = queue.poll(waitForMergeMillis, TimeUnit.MILLISECONDS);
if (operation2 != null) {
if (operation.isMergeableWith(operation2)) {
mergeTxAndExecute(operation, operation2);
} else {
// Cannot merge, execute both
executeOperationAndPostCompleted(operation);
executeOperationAndPostCompleted(operation2);
}
continue;
}
}
executeOperationAndPostCompleted(operation);
}
} catch (InterruptedException e) {
DaoLog.w(Thread.currentThread().getName() + " was interruppted", e);
}
} finally {
executorRunning = false;
}
}
/** Also checks for other operations in the queue that can be merged into the transaction. */
private void mergeTxAndExecute(AsyncOperation operation1, AsyncOperation operation2) {
ArrayList<AsyncOperation> mergedOps = new ArrayList<AsyncOperation>();
mergedOps.add(operation1);
mergedOps.add(operation2);
Database db = operation1.getDatabase();
db.beginTransaction();
boolean success = false;
try {
for (int i = 0; i < mergedOps.size(); i++) {
AsyncOperation operation = mergedOps.get(i);
executeOperation(operation);
if (operation.isFailed()) {
// Operation may still have changed the DB, roll back everything
break;
}
if (i == mergedOps.size() - 1) {
AsyncOperation peekedOp = queue.peek();
if (i < maxOperationCountToMerge && operation.isMergeableWith(peekedOp)) {
AsyncOperation removedOp = queue.remove();
if (removedOp != peekedOp) {
// Paranoia check, should not occur unless threading is broken
throw new DaoException("Internal error: peeked op did not match removed op");
}
mergedOps.add(removedOp);
} else {
// No more ops in the queue to merge, finish it
db.setTransactionSuccessful();
success = true;
break;
}
}
}
} finally {
try {
db.endTransaction();
} catch (RuntimeException e) {
DaoLog.i("Async transaction could not be ended, success so far was: " + success, e);
success = false;
}
}
if (success) {
int mergedCount = mergedOps.size();
for (AsyncOperation asyncOperation : mergedOps) {
asyncOperation.mergedOperationsCount = mergedCount;
handleOperationCompleted(asyncOperation);
}
} else {
DaoLog.i("Reverted merged transaction because one of the operations failed. Executing operations one by " +
"one instead...");
for (AsyncOperation asyncOperation : mergedOps) {
asyncOperation.reset();
executeOperationAndPostCompleted(asyncOperation);
}
}
}
private void handleOperationCompleted(AsyncOperation operation) {
operation.setCompleted();
AsyncOperationListener listenerToCall = listener;
if (listenerToCall != null) {
listenerToCall.onAsyncOperationCompleted(operation);
}
if (listenerMainThread != null) {
if (handlerMainThread == null) {
handlerMainThread = new Handler(Looper.getMainLooper(), this);
}
Message msg = handlerMainThread.obtainMessage(1, operation);
handlerMainThread.sendMessage(msg);
}
synchronized (this) {
countOperationsCompleted++;
if (countOperationsCompleted == countOperationsEnqueued) {
notifyAll();
}
}
}
private void executeOperationAndPostCompleted(AsyncOperation operation) {
executeOperation(operation);
handleOperationCompleted(operation);
}
@SuppressWarnings({"unchecked", "rawtypes"})
private void executeOperation(AsyncOperation operation) {
operation.timeStarted = System.currentTimeMillis();
try {
switch (operation.type) {
case Delete:
operation.dao.delete(operation.parameter);
break;
case DeleteInTxIterable:
operation.dao.deleteInTx((Iterable<Object>) operation.parameter);
break;
case DeleteInTxArray:
operation.dao.deleteInTx((Object[]) operation.parameter);
break;
case Insert:
operation.dao.insert(operation.parameter);
break;
case InsertInTxIterable:
operation.dao.insertInTx((Iterable<Object>) operation.parameter);
break;
case InsertInTxArray:
operation.dao.insertInTx((Object[]) operation.parameter);
break;
case InsertOrReplace:
operation.dao.insertOrReplace(operation.parameter);
break;
case InsertOrReplaceInTxIterable:
operation.dao.insertOrReplaceInTx((Iterable<Object>) operation.parameter);
break;
case InsertOrReplaceInTxArray:
operation.dao.insertOrReplaceInTx((Object[]) operation.parameter);
break;
case Update:
operation.dao.update(operation.parameter);
break;
case UpdateInTxIterable:
operation.dao.updateInTx((Iterable<Object>) operation.parameter);
break;
case UpdateInTxArray:
operation.dao.updateInTx((Object[]) operation.parameter);
break;
case TransactionRunnable:
executeTransactionRunnable(operation);
break;
case TransactionCallable:
executeTransactionCallable(operation);
break;
case QueryList:
operation.result = ((Query) operation.parameter).forCurrentThread().list();
break;
case QueryUnique:
operation.result = ((Query) operation.parameter).forCurrentThread().unique();
break;
case DeleteByKey:
operation.dao.deleteByKey(operation.parameter);
break;
case DeleteAll:
operation.dao.deleteAll();
break;
case Load:
operation.result = operation.dao.load(operation.parameter);
break;
case LoadAll:
operation.result = operation.dao.loadAll();
break;
case Count:
operation.result = operation.dao.count();
break;
case Refresh:
operation.dao.refresh(operation.parameter);
break;
default:
throw new DaoException("Unsupported operation: " + operation.type);
}
} catch (Throwable th) {
operation.throwable = th;
}
operation.timeCompleted = System.currentTimeMillis();
// Do not set it to completed here because it might be a merged TX
}
private void executeTransactionRunnable(AsyncOperation operation) {
Database db = operation.getDatabase();
db.beginTransaction();
try {
((Runnable) operation.parameter).run();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
@SuppressWarnings("unchecked")
private void executeTransactionCallable(AsyncOperation operation) throws Exception {
Database db = operation.getDatabase();
db.beginTransaction();
try {
operation.result = ((Callable<Object>) operation.parameter).call();
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
}
@Override
public boolean handleMessage(Message msg) {
AsyncOperationListener listenerToCall = listenerMainThread;
if (listenerToCall != null) {
listenerToCall.onAsyncOperationCompleted((AsyncOperation) msg.obj);
}
return false;
}
}
|
AsyncOperationExecutor
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/EmptyCatchTest.java
|
{
"start": 6420,
"end": 6741
}
|
class ____ {
@Test
public void testNG() {
try {
System.err.println();
// BUG: Diagnostic contains:
} catch (Exception doNotCare) {
}
}
}
""")
.doTest();
}
}
|
SomeTest
|
java
|
apache__camel
|
core/camel-management-api/src/main/java/org/apache/camel/api/management/mbean/ManagedBeanMBean.java
|
{
"start": 916,
"end": 1116
}
|
interface ____ extends ManagedProcessorMBean {
@ManagedAttribute(description = "The method name on the bean to use")
String getMethod();
@ManagedAttribute(description = "The
|
ManagedBeanMBean
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/javadoc/InvalidInlineTagTest.java
|
{
"start": 2080,
"end": 2397
}
|
class ____ {
// BUG: Diagnostic contains:
/** {@SoFarOutsideEditLimit} */
void test() {}
}
""")
.doTest();
}
@Test
public void isAType() {
refactoring
.addInputLines(
"SomeType.java",
"""
|
Test
|
java
|
quarkusio__quarkus
|
independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/commands/handlers/MultipleExtensionsFoundException.java
|
{
"start": 241,
"end": 827
}
|
class ____ extends RuntimeException {
private final String keyword;
private final Collection<Extension> extensions;
public MultipleExtensionsFoundException(String keyword, Collection<Extension> extensions) {
this.keyword = Objects.requireNonNull(keyword, "Keyword must not be null");
this.extensions = Objects.requireNonNull(extensions, "Extensions should not be null");
}
public String getKeyword() {
return keyword;
}
public Collection<Extension> getExtensions() {
return extensions;
}
}
|
MultipleExtensionsFoundException
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/SequenceFileInputFilter.java
|
{
"start": 6517,
"end": 9176
}
|
class ____ extends FilterBase {
private int frequency;
private static final MessageDigest DIGESTER;
public static final int MD5_LEN = 16;
private byte [] digest = new byte[MD5_LEN];
static {
try {
DIGESTER = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/** set the filtering frequency in configuration
*
* @param conf configuration
* @param frequency filtering frequency
*/
public static void setFrequency(Configuration conf, int frequency) {
if (frequency <= 0)
throw new IllegalArgumentException(
"Negative " + FILTER_FREQUENCY + ": " + frequency);
conf.setInt(FILTER_FREQUENCY, frequency);
}
public MD5Filter() { }
/** configure the filter according to configuration
*
* @param conf configuration
*/
public void setConf(Configuration conf) {
this.frequency = conf.getInt(FILTER_FREQUENCY, 10);
if (this.frequency <= 0) {
throw new RuntimeException(
"Negative " + FILTER_FREQUENCY + ": " + this.frequency);
}
this.conf = conf;
}
/** Filtering method
* If MD5(key) % frequency==0, return true; otherwise return false
* @see Filter#accept(Object)
*/
public boolean accept(Object key) {
try {
long hashcode;
if (key instanceof Text) {
hashcode = MD5Hashcode((Text)key);
} else if (key instanceof BytesWritable) {
hashcode = MD5Hashcode((BytesWritable)key);
} else {
ByteBuffer bb;
bb = Text.encode(key.toString());
hashcode = MD5Hashcode(bb.array(), 0, bb.limit());
}
if (hashcode / frequency * frequency == hashcode)
return true;
} catch(Exception e) {
LOG.warn(e.toString());
throw new RuntimeException(e);
}
return false;
}
private long MD5Hashcode(Text key) throws DigestException {
return MD5Hashcode(key.getBytes(), 0, key.getLength());
}
private long MD5Hashcode(BytesWritable key) throws DigestException {
return MD5Hashcode(key.getBytes(), 0, key.getLength());
}
synchronized private long MD5Hashcode(byte[] bytes,
int start, int length) throws DigestException {
DIGESTER.update(bytes, 0, length);
DIGESTER.digest(digest, 0, MD5_LEN);
long hashcode=0;
for (int i = 0; i < 8; i++)
hashcode |= ((digest[i] & 0xffL) << (8 * (7 - i)));
return hashcode;
}
}
private static
|
MD5Filter
|
java
|
google__dagger
|
javatests/artifacts/dagger-ksp/transitive-annotation-app/src/test/java/app/MyComponentTest.java
|
{
"start": 921,
"end": 3113
}
|
class ____ {
private MyComponent component;
@Before
public void setup() {
component = DaggerMyComponent.factory()
.create(new MyComponentModule(new Dep()), new MyComponentDependency());
}
@Test
public void testFooIsScoped() {
assertThat(component.foo()).isEqualTo(component.foo());
}
@Test
public void testAssistedFoo() {
assertThat(component.assistedFooFactory().create(5)).isNotNull();
}
@Test
public void testScopedQualifiedBindsTypeIsScoped() {
assertThat(component.scopedQualifiedBindsType())
.isEqualTo(component.scopedQualifiedBindsType());
}
@Test
public void testScopedUnqualifiedBindsTypeIsScoped() {
assertThat(component.scopedUnqualifiedBindsType())
.isEqualTo(component.scopedUnqualifiedBindsType());
}
@Test
public void testUnscopedQualifiedBindsTypeIsNotScoped() {
assertThat(component.unscopedQualifiedBindsType())
.isNotEqualTo(component.unscopedQualifiedBindsType());
}
@Test
public void testUnscopedUnqualifiedBindsTypeIsNotScoped() {
assertThat(component.unscopedUnqualifiedBindsType())
.isNotEqualTo(component.unscopedUnqualifiedBindsType());
}
@Test
public void testScopedQualifiedProvidesTypeIsScoped() {
assertThat(component.scopedQualifiedProvidesType())
.isEqualTo(component.scopedQualifiedProvidesType());
}
@Test
public void testScopedUnqualifiedProvidesTypeIsScoped() {
assertThat(component.scopedUnqualifiedProvidesType())
.isEqualTo(component.scopedUnqualifiedProvidesType());
}
@Test
public void testUnscopedQualifiedProvidesTypeIsNotScoped() {
assertThat(component.unscopedQualifiedProvidesType())
.isNotEqualTo(component.unscopedQualifiedProvidesType());
}
@Test
public void testUnscopedUnqualifiedProvidesTypeIsNotScoped() {
assertThat(component.unscopedUnqualifiedProvidesType())
.isNotEqualTo(component.unscopedUnqualifiedProvidesType());
}
@Test
public void testMyComponentDependencyBinding() {
assertThat(component.qualifiedMyComponentDependencyBinding())
.isNotEqualTo(component.unqualifiedMyComponentDependencyBinding());
}
}
|
MyComponentTest
|
java
|
apache__camel
|
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/PulsarEndpointBuilderFactory.java
|
{
"start": 56290,
"end": 59142
}
|
interface ____ {
/**
* Pulsar (camel-pulsar)
* Send and receive messages from/to Apache Pulsar messaging system.
*
* Category: messaging
* Since: 2.24
* Maven coordinates: org.apache.camel:camel-pulsar
*
* @return the dsl builder for the headers' name.
*/
default PulsarHeaderNameBuilder pulsar() {
return PulsarHeaderNameBuilder.INSTANCE;
}
/**
* Pulsar (camel-pulsar)
* Send and receive messages from/to Apache Pulsar messaging system.
*
* Category: messaging
* Since: 2.24
* Maven coordinates: org.apache.camel:camel-pulsar
*
* Syntax: <code>pulsar:persistence://tenant/namespace/topic</code>
*
* Path parameter: persistence (required)
* Whether the topic is persistent or non-persistent
* There are 2 enums and the value can be one of: persistent,
* non-persistent
*
* Path parameter: tenant (required)
* The tenant
*
* Path parameter: namespace (required)
* The namespace
*
* Path parameter: topic (required)
* The topic
*
* @param path persistence://tenant/namespace/topic
* @return the dsl builder
*/
default PulsarEndpointBuilder pulsar(String path) {
return PulsarEndpointBuilderFactory.endpointBuilder("pulsar", path);
}
/**
* Pulsar (camel-pulsar)
* Send and receive messages from/to Apache Pulsar messaging system.
*
* Category: messaging
* Since: 2.24
* Maven coordinates: org.apache.camel:camel-pulsar
*
* Syntax: <code>pulsar:persistence://tenant/namespace/topic</code>
*
* Path parameter: persistence (required)
* Whether the topic is persistent or non-persistent
* There are 2 enums and the value can be one of: persistent,
* non-persistent
*
* Path parameter: tenant (required)
* The tenant
*
* Path parameter: namespace (required)
* The namespace
*
* Path parameter: topic (required)
* The topic
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path persistence://tenant/namespace/topic
* @return the dsl builder
*/
default PulsarEndpointBuilder pulsar(String componentName, String path) {
return PulsarEndpointBuilderFactory.endpointBuilder(componentName, path);
}
}
/**
* The builder of headers' name for the Pulsar component.
*/
public static
|
PulsarBuilders
|
java
|
grpc__grpc-java
|
netty/src/main/java/io/grpc/netty/NettyServerBuilder.java
|
{
"start": 2744,
"end": 7192
}
|
class ____ extends ForwardingServerBuilder<NettyServerBuilder> {
// 1MiB
public static final int DEFAULT_FLOW_CONTROL_WINDOW = 1024 * 1024;
static final long MAX_CONNECTION_IDLE_NANOS_DISABLED = Long.MAX_VALUE;
static final long MAX_CONNECTION_AGE_NANOS_DISABLED = Long.MAX_VALUE;
static final long MAX_CONNECTION_AGE_GRACE_NANOS_INFINITE = Long.MAX_VALUE;
static final int MAX_RST_COUNT_DISABLED = 0;
private static final long MIN_MAX_CONNECTION_IDLE_NANO = TimeUnit.SECONDS.toNanos(1L);
private static final long MIN_MAX_CONNECTION_AGE_NANO = TimeUnit.SECONDS.toNanos(1L);
private static final long AS_LARGE_AS_INFINITE = TimeUnit.DAYS.toNanos(1000L);
private static final ObjectPool<? extends EventLoopGroup> DEFAULT_BOSS_EVENT_LOOP_GROUP_POOL =
SharedResourcePool.forResource(Utils.DEFAULT_BOSS_EVENT_LOOP_GROUP);
private static final ObjectPool<? extends EventLoopGroup> DEFAULT_WORKER_EVENT_LOOP_GROUP_POOL =
SharedResourcePool.forResource(Utils.DEFAULT_WORKER_EVENT_LOOP_GROUP);
private final ServerImplBuilder serverImplBuilder;
private final List<SocketAddress> listenAddresses = new ArrayList<>();
private TransportTracer.Factory transportTracerFactory = TransportTracer.getDefaultFactory();
private ChannelFactory<? extends ServerChannel> channelFactory =
Utils.DEFAULT_SERVER_CHANNEL_FACTORY;
private final Map<ChannelOption<?>, Object> channelOptions = new HashMap<>();
private final Map<ChannelOption<?>, Object> childChannelOptions = new HashMap<>();
private ObjectPool<? extends EventLoopGroup> bossEventLoopGroupPool =
DEFAULT_BOSS_EVENT_LOOP_GROUP_POOL;
private ObjectPool<? extends EventLoopGroup> workerEventLoopGroupPool =
DEFAULT_WORKER_EVENT_LOOP_GROUP_POOL;
private boolean forceHeapBuffer;
private ProtocolNegotiator.ServerFactory protocolNegotiatorFactory;
private final boolean freezeProtocolNegotiatorFactory;
private int maxConcurrentCallsPerConnection = Integer.MAX_VALUE;
private boolean autoFlowControl = true;
private int flowControlWindow = DEFAULT_FLOW_CONTROL_WINDOW;
private int maxMessageSize = DEFAULT_MAX_MESSAGE_SIZE;
private int maxHeaderListSize = GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE;
private int softLimitHeaderListSize = GrpcUtil.DEFAULT_MAX_HEADER_LIST_SIZE;
private long keepAliveTimeInNanos = DEFAULT_SERVER_KEEPALIVE_TIME_NANOS;
private long keepAliveTimeoutInNanos = DEFAULT_SERVER_KEEPALIVE_TIMEOUT_NANOS;
private long maxConnectionIdleInNanos = MAX_CONNECTION_IDLE_NANOS_DISABLED;
private long maxConnectionAgeInNanos = MAX_CONNECTION_AGE_NANOS_DISABLED;
private long maxConnectionAgeGraceInNanos = MAX_CONNECTION_AGE_GRACE_NANOS_INFINITE;
private boolean permitKeepAliveWithoutCalls;
private long permitKeepAliveTimeInNanos = TimeUnit.MINUTES.toNanos(5);
private int maxRstCount;
private long maxRstPeriodNanos;
private Attributes eagAttributes = Attributes.EMPTY;
/**
* Creates a server builder that will bind to the given port.
*
* @param port the port on which the server is to be bound.
* @return the server builder.
*/
public static NettyServerBuilder forPort(int port) {
return forAddress(new InetSocketAddress(port));
}
/**
* Creates a server builder that will bind to the given port.
*
* @param port the port on which the server is to be bound.
* @return the server builder.
*/
public static NettyServerBuilder forPort(int port, ServerCredentials creds) {
return forAddress(new InetSocketAddress(port), creds);
}
/**
* Creates a server builder configured with the given {@link SocketAddress}.
*
* @param address the socket address on which the server is to be bound.
* @return the server builder
*/
public static NettyServerBuilder forAddress(SocketAddress address) {
return new NettyServerBuilder(address);
}
/**
* Creates a server builder configured with the given {@link SocketAddress}.
*
* @param address the socket address on which the server is to be bound.
* @return the server builder
*/
public static NettyServerBuilder forAddress(SocketAddress address, ServerCredentials creds) {
ProtocolNegotiators.FromServerCredentialsResult result = ProtocolNegotiators.from(creds);
if (result.error != null) {
throw new IllegalArgumentException(result.error);
}
return new NettyServerBuilder(address, result.negotiator);
}
private final
|
NettyServerBuilder
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/writeAsArray/WriteAsArray_Eishay.java
|
{
"start": 320,
"end": 733
}
|
class ____ extends TestCase {
public void test_0 () throws Exception {
MediaContent content = EishayDecodeBytes.instance.getContent();
String text = JSON.toJSONString(content, SerializerFeature.BeanToArray);
System.out.println(text.getBytes().length);
JSON.parseObject(text, MediaContent.class, Feature.SupportArrayToBean);
}
public static
|
WriteAsArray_Eishay
|
java
|
apache__logging-log4j2
|
log4j-osgi-test/src/test/java/org/apache/logging/log4j/osgi/tests/AbstractLoadBundleTest.java
|
{
"start": 6216,
"end": 8545
}
|
class ____ as API Level");
doOnBundlesAndVerifyState(Bundle::stop, Bundle.RESOLVED, core, api);
doOnBundlesAndVerifyState(Bundle::uninstall, Bundle.UNINSTALLED, compat, core, api);
}
/**
* Tests whether the {@link ServiceLoaderUtil} finds services in other bundles.
*/
@Test
public void testServiceLoader() throws BundleException, ReflectiveOperationException {
final Bundle api = getApiBundle();
final Bundle core = getCoreBundle();
final Bundle apiTests = getApiTestsBundle();
final Class<?> osgiServiceLocator = api.loadClass("org.apache.logging.log4j.util.OsgiServiceLocator");
assertTrue((boolean) osgiServiceLocator.getMethod("isAvailable").invoke(null), "OsgiServiceLocator is active");
doOnBundlesAndVerifyState(Bundle::start, Bundle.ACTIVE, api, core, apiTests);
final Class<?> osgiServiceLocatorTest =
apiTests.loadClass("org.apache.logging.log4j.test.util.OsgiServiceLocatorTest");
final Method loadProviders = osgiServiceLocatorTest.getDeclaredMethod("loadProviders");
final Object obj = loadProviders.invoke(null);
assertTrue(obj instanceof Stream);
@SuppressWarnings("unchecked")
final List<Object> services = ((Stream<Object>) obj).collect(Collectors.toList());
assertEquals(1, services.size());
assertEquals(
"org.apache.logging.log4j.core.impl.Log4jProvider",
services.get(0).getClass().getName());
doOnBundlesAndVerifyState(Bundle::stop, Bundle.RESOLVED, apiTests, core, api);
doOnBundlesAndVerifyState(Bundle::uninstall, Bundle.UNINSTALLED, apiTests, core, api);
}
private static void doOnBundlesAndVerifyState(
final ThrowingConsumer<Bundle> operation, final int expectedState, final Bundle... bundles) {
for (final Bundle bundle : bundles) {
try {
operation.accept(bundle);
} catch (final Throwable error) {
final String message = String.format("operation failure for bundle `%s`", bundle);
throw new RuntimeException(message, error);
}
assertEquals(expectedState, bundle.getState(), String.format("`%s` bundle state mismatch", bundle));
}
}
}
|
loader
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/util/lang/Consumer.java
|
{
"start": 706,
"end": 754
}
|
interface ____<T> {
void accept(T t);
}
|
Consumer
|
java
|
google__dagger
|
dagger-spi/main/java/dagger/internal/codegen/extension/Optionals.java
|
{
"start": 914,
"end": 2456
}
|
class ____ {
/**
* A {@link Comparator} that puts empty {@link Optional}s before present ones, and compares
* present {@link Optional}s by their values.
*/
public static <C extends Comparable<C>> Comparator<Optional<C>> optionalComparator() {
return Comparator.comparing((Optional<C> optional) -> optional.isPresent())
.thenComparing(Optional::get);
}
public static <T> Comparator<Optional<T>> emptiesLast(Comparator<? super T> valueComparator) {
checkNotNull(valueComparator);
return Comparator.comparing(o -> o.orElse(null), Comparator.nullsLast(valueComparator));
}
/** Returns the first argument that is present, or empty if none are. */
@SafeVarargs
public static <T> Optional<T> firstPresent(
Optional<T> first, Optional<T> second, Optional<T>... rest) {
return asList(first, second, rest).stream()
.filter(Optional::isPresent)
.findFirst()
.orElse(Optional.empty());
}
/**
* Walks a chain of present optionals as defined by successive calls to {@code nextFunction},
* returning the value of the final optional that is present. The first optional in the chain is
* the result of {@code nextFunction(start)}.
*/
public static <T> T rootmostValue(T start, Function<T, Optional<T>> nextFunction) {
T current = start;
for (Optional<T> next = nextFunction.apply(start);
next.isPresent();
next = nextFunction.apply(current)) {
current = next.get();
}
return current;
}
private Optionals() {}
}
|
Optionals
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/resources/HttpOpParam.java
|
{
"start": 1286,
"end": 1374
}
|
enum ____ {
GET, PUT, POST, DELETE
}
/** Http operation interface. */
public
|
Type
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-mawo/hadoop-yarn-applications-mawo-core/src/main/java/org/apache/hadoop/applications/mawo/server/common/SimpleTask.java
|
{
"start": 963,
"end": 1790
}
|
class ____ extends AbstractTask {
/**
* Simple Task default initializer.
*/
public SimpleTask() {
super();
this.setTaskType(TaskType.SIMPLE);
}
/**
* Set up Simple Task with Task object.
* @param task : Task object
*/
public SimpleTask(final Task task) {
this(task.getTaskId(), task.getEnvironment(), task.getTaskCmd(),
task.getTimeout());
}
/**
* Create Simple Task with Task details.
* @param taskId : task identifier
* @param environment : task environment
* @param taskCMD : task command
* @param timeout : task timeout
*/
public SimpleTask(final TaskId taskId, final Map<String, String> environment,
final String taskCMD, final long timeout) {
super(taskId, environment, taskCMD, timeout);
this.setTaskType(TaskType.SIMPLE);
}
}
|
SimpleTask
|
java
|
netty__netty
|
transport-native-kqueue/src/test/java/io/netty/channel/kqueue/KQueueDomainSocketFdTest.java
|
{
"start": 1671,
"end": 4580
}
|
class ____ extends AbstractSocketTest {
@Override
protected SocketAddress newSocketAddress() {
return KQueueSocketTestPermutation.newSocketAddress();
}
@Override
protected List<TestsuitePermutation.BootstrapComboFactory<ServerBootstrap, Bootstrap>> newFactories() {
return KQueueSocketTestPermutation.INSTANCE.domainSocket();
}
@Test
@Timeout(value = 30000, unit = TimeUnit.MILLISECONDS)
public void testSendRecvFd(TestInfo testInfo) throws Throwable {
run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
@Override
public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
testSendRecvFd(serverBootstrap, bootstrap);
}
});
}
public void testSendRecvFd(ServerBootstrap sb, Bootstrap cb) throws Throwable {
final BlockingQueue<Object> queue = new LinkedBlockingQueue<Object>(1);
sb.childHandler(new ChannelInboundHandlerAdapter() {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
// Create new channel and obtain a file descriptor from it.
final KQueueDomainSocketChannel ch = new KQueueDomainSocketChannel();
ctx.writeAndFlush(ch.fd()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (!future.isSuccess()) {
Throwable cause = future.cause();
queue.offer(cause);
}
}
});
}
});
cb.handler(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
FileDescriptor fd = (FileDescriptor) msg;
queue.offer(fd);
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
queue.add(cause);
ctx.close();
}
});
cb.option(KQueueChannelOption.DOMAIN_SOCKET_READ_MODE,
DomainSocketReadMode.FILE_DESCRIPTORS);
Channel sc = sb.bind().sync().channel();
Channel cc = cb.connect(sc.localAddress()).sync().channel();
Object received = queue.take();
cc.close().sync();
sc.close().sync();
if (received instanceof FileDescriptor) {
FileDescriptor fd = (FileDescriptor) received;
assertTrue(fd.isOpen());
fd.close();
assertFalse(fd.isOpen());
assertNull(queue.poll());
} else {
throw (Throwable) received;
}
}
}
|
KQueueDomainSocketFdTest
|
java
|
junit-team__junit5
|
platform-tests/src/test/java/org/junit/platform/engine/support/hierarchical/HierarchicalTestExecutorTests.java
|
{
"start": 32687,
"end": 32978
}
|
class ____ extends AbstractTestDescriptor
implements Node<MyEngineExecutionContext> {
MyContainerAndTestTestCase(UniqueId uniqueId) {
super(uniqueId, uniqueId.toString());
}
@Override
public Type getType() {
return Type.CONTAINER_AND_TEST;
}
}
}
|
MyContainerAndTestTestCase
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/inject/guice/AssistedInjectScopingTest.java
|
{
"start": 2352,
"end": 2670
}
|
class ____ {
@AssistedInject
public TestClass3(String param) {}
}
/** Multiple constructors, but only one with @Inject, and that one matches. */
// BUG: Diagnostic contains: remove this line
@Singleton
public
|
TestClass3
|
java
|
apache__flink
|
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/operations/converters/table/SqlAlterTableDropConstraintConverter.java
|
{
"start": 1548,
"end": 3366
}
|
class ____
extends AbstractAlterTableConverter<SqlAlterTableDropConstraint> {
@Override
protected Operation convertToOperation(
SqlAlterTableDropConstraint dropConstraint,
ResolvedCatalogTable oldTable,
ConvertContext context) {
Optional<UniqueConstraint> pkConstraint = oldTable.getResolvedSchema().getPrimaryKey();
if (pkConstraint.isEmpty()) {
throw new ValidationException(
String.format(
"%sThe base table does not define any primary key.", EX_MSG_PREFIX));
}
SqlIdentifier constraintIdentifier = dropConstraint.getConstraintName();
String constraintName = pkConstraint.get().getName();
if (constraintIdentifier != null
&& !constraintIdentifier.getSimple().equals(constraintName)) {
throw new ValidationException(
String.format(
"%sThe base table does not define a primary key constraint named '%s'. "
+ "Available constraint name: ['%s'].",
EX_MSG_PREFIX, constraintIdentifier.getSimple(), constraintName));
}
Schema.Builder schemaBuilder = Schema.newBuilder();
SchemaReferencesManager.buildUpdatedColumn(
schemaBuilder, oldTable, (builder, column) -> builder.fromColumns(List.of(column)));
SchemaReferencesManager.buildUpdatedWatermark(schemaBuilder, oldTable);
return buildAlterTableChangeOperation(
dropConstraint,
List.of(TableChange.dropConstraint(constraintName)),
schemaBuilder.build(),
oldTable,
context.getCatalogManager());
}
}
|
SqlAlterTableDropConstraintConverter
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-gridmix/src/test/java/org/apache/hadoop/mapred/gridmix/TestResourceUsageEmulators.java
|
{
"start": 10274,
"end": 11185
}
|
class ____
extends ResourceUsageMatcherRunner {
FakeResourceUsageMatcherRunner(TaskInputOutputContext context,
ResourceUsageMetrics metrics) {
super(context, metrics);
}
// test ResourceUsageMatcherRunner
void test() throws Exception {
super.match();
}
}
/**
* Test {@link LoadJob.ResourceUsageMatcherRunner}.
*/
@Test
@SuppressWarnings("unchecked")
public void testResourceUsageMatcherRunner() throws Exception {
Configuration conf = new Configuration();
FakeProgressive progress = new FakeProgressive();
// set the resource calculator plugin
conf.setClass(TTConfig.TT_RESOURCE_CALCULATOR_PLUGIN,
DummyResourceCalculatorPlugin.class,
ResourceCalculatorPlugin.class);
// set the resources
// set the resource implementation
|
FakeResourceUsageMatcherRunner
|
java
|
spring-projects__spring-framework
|
spring-web/src/test/java/org/springframework/http/server/reactive/EchoHandlerIntegrationTests.java
|
{
"start": 2078,
"end": 2278
}
|
class ____ implements HttpHandler {
@Override
public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) {
return response.writeWith(request.getBody());
}
}
}
|
EchoHandler
|
java
|
spring-projects__spring-boot
|
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/ImportAutoConfigurationImportSelectorTests.java
|
{
"start": 12746,
"end": 13198
}
|
class ____ extends ImportAutoConfigurationImportSelector {
@Override
protected Collection<String> loadFactoryNames(Class<?> source) {
if (source == MetaImportAutoConfiguration.class) {
return Arrays.asList(AnotherImportedAutoConfiguration.class.getName(),
ImportedAutoConfiguration.class.getName());
}
return super.loadFactoryNames(source);
}
}
@AutoConfiguration
public static final
|
TestImportAutoConfigurationImportSelector
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/TestAuxServices.java
|
{
"start": 6597,
"end": 8929
}
|
class ____ extends AuxiliaryService implements Service
{
private final char idef;
private final int expected_appId;
private int remaining_init;
private int remaining_stop;
private ByteBuffer meta = null;
private ArrayList<Integer> stoppedApps;
private ContainerId containerId;
private Resource resource;
LightService(String name, char idef, int expected_appId) {
this(name, idef, expected_appId, null);
}
LightService(String name, char idef, int expected_appId, ByteBuffer meta) {
super(name);
this.idef = idef;
this.expected_appId = expected_appId;
this.meta = meta;
this.stoppedApps = new ArrayList<Integer>();
}
@SuppressWarnings("unchecked")
public ArrayList<Integer> getAppIdsStopped() {
return (ArrayList<Integer>)this.stoppedApps.clone();
}
@Override
protected void serviceInit(Configuration conf) throws Exception {
remaining_init = conf.getInt(idef + ".expected.init", 0);
remaining_stop = conf.getInt(idef + ".expected.stop", 0);
super.serviceInit(conf);
}
@Override
protected void serviceStop() throws Exception {
assertEquals(0, remaining_init);
assertEquals(0, remaining_stop);
super.serviceStop();
}
@Override
public void initializeApplication(ApplicationInitializationContext context) {
ByteBuffer data = context.getApplicationDataForService();
assertEquals(idef, data.getChar());
assertEquals(expected_appId, data.getInt());
assertEquals(expected_appId, context.getApplicationId().getId());
}
@Override
public void stopApplication(ApplicationTerminationContext context) {
stoppedApps.add(context.getApplicationId().getId());
}
@Override
public ByteBuffer getMetaData() {
return meta;
}
@Override
public void initializeContainer(
ContainerInitializationContext initContainerContext) {
containerId = initContainerContext.getContainerId();
resource = initContainerContext.getResource();
}
@Override
public void stopContainer(
ContainerTerminationContext stopContainerContext) {
containerId = stopContainerContext.getContainerId();
resource = stopContainerContext.getResource();
}
}
static
|
LightService
|
java
|
assertj__assertj-core
|
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/optional/OptionalAssert_flatMap_Test.java
|
{
"start": 1022,
"end": 1979
}
|
class ____ {
private static final Function<String, Optional<String>> UPPER_CASE_OPTIONAL_STRING = s -> (s == null)
? Optional.empty()
: Optional.of(s.toUpperCase());
@Test
void should_fail_when_optional_is_null() {
// GIVEN
@SuppressWarnings("OptionalAssignedToNull")
Optional<String> actual = null;
// WHEN
var assertionError = expectAssertionError(() -> assertThat(actual).flatMap(UPPER_CASE_OPTIONAL_STRING));
// THEN
then(assertionError).hasMessage(actualIsNull());
}
@Test
void should_pass_when_optional_is_empty() {
assertThat(Optional.<String> empty()).flatMap(UPPER_CASE_OPTIONAL_STRING).isEmpty();
}
@Test
void should_pass_when_optional_contains_a_value() {
assertThat(Optional.of("present")).contains("present")
.flatMap(UPPER_CASE_OPTIONAL_STRING)
.contains("PRESENT");
}
}
|
OptionalAssert_flatMap_Test
|
java
|
apache__camel
|
core/camel-api/src/main/java/org/apache/camel/spi/CamelEvent.java
|
{
"start": 5663,
"end": 5843
}
|
interface ____ extends CamelContextEvent {
@Override
default Type getType() {
return Type.RoutesStarted;
}
}
|
CamelContextRoutesStartedEvent
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestSlowDatanodeReport.java
|
{
"start": 1929,
"end": 6351
}
|
class ____ {
private static final Logger LOG = LoggerFactory.getLogger(TestSlowDatanodeReport.class);
private MiniDFSCluster cluster;
@BeforeEach
public void testSetup() throws Exception {
Configuration conf = new Configuration();
conf.set(DFS_DATANODE_OUTLIERS_REPORT_INTERVAL_KEY, "1000");
conf.set(DFS_DATANODE_PEER_STATS_ENABLED_KEY, "true");
conf.set(DFS_DATANODE_MIN_OUTLIER_DETECTION_NODES_KEY, "1");
conf.set(DFS_DATANODE_PEER_METRICS_MIN_OUTLIER_DETECTION_SAMPLES_KEY, "1");
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(3).build();
cluster.waitActive();
}
@AfterEach
public void tearDown() throws Exception {
cluster.shutdown();
}
@Test
public void testSingleNodeReport() throws Exception {
List<DataNode> dataNodes = cluster.getDataNodes();
DataNode slowNode = dataNodes.get(1);
OutlierMetrics outlierMetrics = new OutlierMetrics(1.245, 2.69375, 4.5667, 15.5);
dataNodes.get(0).getPeerMetrics().setTestOutliers(
ImmutableMap.of(slowNode.getDatanodeHostname() + ":" + slowNode.getIpcPort(),
outlierMetrics));
DistributedFileSystem distributedFileSystem = cluster.getFileSystem();
Assertions.assertEquals(3, distributedFileSystem.getDataNodeStats().length);
GenericTestUtils.waitFor(() -> {
try {
DatanodeInfo[] slowNodeInfo = distributedFileSystem.getSlowDatanodeStats();
LOG.info("Slow Datanode report: {}", Arrays.asList(slowNodeInfo));
return slowNodeInfo.length == 1;
} catch (IOException e) {
LOG.error("Failed to retrieve slownode report", e);
return false;
}
}, 2000, 180000, "Slow nodes could not be detected");
LOG.info("Slow peer report: {}", cluster.getNameNode().getSlowPeersReport());
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport().length() > 0);
Assertions.assertTrue(
cluster.getNameNode().getSlowPeersReport().contains(slowNode.getDatanodeHostname()));
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport().contains("15.5"));
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport().contains("1.245"));
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport().contains("2.69375"));
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport().contains("4.5667"));
}
@Test
public void testMultiNodesReport() throws Exception {
List<DataNode> dataNodes = cluster.getDataNodes();
OutlierMetrics outlierMetrics1 = new OutlierMetrics(2.498237, 19.2495, 23.568204, 14.5);
OutlierMetrics outlierMetrics2 = new OutlierMetrics(3.2535, 22.4945, 44.5667, 18.7);
dataNodes.get(0).getPeerMetrics().setTestOutliers(ImmutableMap.of(
dataNodes.get(1).getDatanodeHostname() + ":" + dataNodes.get(1).getIpcPort(),
outlierMetrics1));
dataNodes.get(1).getPeerMetrics().setTestOutliers(ImmutableMap.of(
dataNodes.get(2).getDatanodeHostname() + ":" + dataNodes.get(2).getIpcPort(),
outlierMetrics2));
DistributedFileSystem distributedFileSystem = cluster.getFileSystem();
Assertions.assertEquals(3, distributedFileSystem.getDataNodeStats().length);
GenericTestUtils.waitFor(() -> {
try {
DatanodeInfo[] slowNodeInfo = distributedFileSystem.getSlowDatanodeStats();
LOG.info("Slow Datanode report: {}", Arrays.asList(slowNodeInfo));
return slowNodeInfo.length == 2;
} catch (IOException e) {
LOG.error("Failed to retrieve slownode report", e);
return false;
}
}, 2000, 200000, "Slow nodes could not be detected");
LOG.info("Slow peer report: {}", cluster.getNameNode().getSlowPeersReport());
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport().length() > 0);
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport()
.contains(dataNodes.get(1).getDatanodeHostname()));
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport()
.contains(dataNodes.get(2).getDatanodeHostname()));
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport().contains("14.5"));
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport().contains("18.7"));
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport().contains("23.568204"));
Assertions.assertTrue(cluster.getNameNode().getSlowPeersReport().contains("22.4945"));
}
}
|
TestSlowDatanodeReport
|
java
|
processing__processing4
|
app/src/processing/app/Util.java
|
{
"start": 21866,
"end": 26183
}
|
class ____ found in a folder, add its containing set
* of folders to the package list. If another folder is found,
* walk down into that folder and continue.
*/
static private void packageListFromFolder(File dir, String sofar,
StringList list) {
boolean foundClass = false;
String[] filenames = dir.list();
if (filenames != null) {
for (String filename : filenames) {
if (filename.equals(".") || filename.equals("..")) continue;
File sub = new File(dir, filename);
if (sub.isDirectory()) {
String nowfar =
(sofar == null) ? filename : (sofar + "." + filename);
packageListFromFolder(sub, nowfar, list);
} else if (!foundClass) { // if no classes found in this folder yet
if (filename.endsWith(".class")) {
list.appendUnique(sofar);
foundClass = true;
}
}
}
} else {
System.err.println("Could not read " + dir);
}
}
/**
* Extract the contents of a .zip archive into a folder.
* Ignores (does not extract) any __MACOSX files from macOS archives.
*/
static public void unzip(File zipFile, File dest) throws IOException {
FileInputStream fis = new FileInputStream(zipFile);
CheckedInputStream checksum = new CheckedInputStream(fis, new Adler32());
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(checksum));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
final String name = entry.getName();
if (!name.startsWith(("__MACOSX"))) {
File currentFile = new File(dest, name);
if (entry.isDirectory()) {
currentFile.mkdirs();
} else {
File parentDir = currentFile.getParentFile();
// Sometimes the directory entries aren't already created
if (!parentDir.exists()) {
parentDir.mkdirs();
}
currentFile.createNewFile();
unzipEntry(zis, currentFile);
}
}
}
}
static protected void unzipEntry(ZipInputStream zin, File f) throws IOException {
FileOutputStream out = new FileOutputStream(f);
byte[] b = new byte[512];
int len;
while ((len = zin.read(b)) != -1) {
out.write(b, 0, len);
}
out.flush();
out.close();
}
static public byte[] gzipEncode(byte[] what) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream output = new GZIPOutputStream(baos);
PApplet.saveStream(output, new ByteArrayInputStream(what));
output.close();
return baos.toByteArray();
}
static public boolean containsNonASCII(String what) {
for (char c : what.toCharArray()) {
if (c < 32 || c > 127) return true;
}
return false;
}
// . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
static public String sanitizeHtmlTags(String str) {
return str.replaceAll("<", "<")
.replaceAll(">", ">");
}
/**
* This has a [link](http://example.com/) in [it](http://example.org/).
* <p>
* Becomes...
* <p>
* This has a <a href="http://example.com/">link</a> in <a
* href="http://example.org/">it</a>.
*/
static public String markDownLinksToHtml(String str) {
Pattern p = Pattern.compile("\\[(.*?)]\\((.*?)\\)");
Matcher m = p.matcher(str);
StringBuilder sb = new StringBuilder();
int start = 0;
while (m.find(start)) {
sb.append(str, start, m.start());
String text = m.group(1);
String url = m.group(2);
sb.append("<a href=\"");
sb.append(url);
sb.append("\">");
sb.append(text);
sb.append("</a>");
start = m.end();
}
sb.append(str.substring(start));
return sb.toString();
}
static public String removeMarkDownLinks(String str) {
StringBuilder name = new StringBuilder();
if (str != null) {
int parentheses = 0;
for (char c : str.toCharArray()) {
if (c == '[' || c == ']') {
// pass
} else if (c == '(') {
parentheses++;
} else if (c == ')') {
parentheses--;
} else if (parentheses == 0) {
name.append(c);
}
}
}
return name.toString();
}
}
|
is
|
java
|
alibaba__nacos
|
client/src/test/java/com/alibaba/nacos/client/config/NacosConfigServiceTest.java
|
{
"start": 2591,
"end": 20517
}
|
class ____ {
private NacosConfigService nacosConfigService;
private ClientWorker mockWoker;
private void setFinal(Field field, Object ins, Object newValue) throws Exception {
field.setAccessible(true);
field.set(ins, newValue);
field.setAccessible(false);
}
@BeforeEach
void mock() throws Exception {
final Properties properties = new Properties();
properties.put("serverAddr", "1.1.1.1");
nacosConfigService = new NacosConfigService(properties);
mockWoker = Mockito.mock(ClientWorker.class);
setFinal(NacosConfigService.class.getDeclaredField("worker"), nacosConfigService, mockWoker);
}
@AfterEach
void clean() {
LocalConfigInfoProcessor.cleanAllSnapshot();
}
@Test
void testGetConfigFromServer() throws NacosException {
final String dataId = "1";
final String group = "2";
final String tenant = "public";
final int timeout = 3000;
ConfigResponse response = new ConfigResponse();
response.setContent("aa");
response.setConfigType("bb");
Mockito.when(mockWoker.getServerConfig(dataId, group, tenant, timeout, false)).thenReturn(response);
final String config = nacosConfigService.getConfig(dataId, group, timeout);
assertEquals("aa", config);
Mockito.verify(mockWoker, Mockito.times(1)).getServerConfig(dataId, group, tenant, timeout, false);
}
@Test
void testGetConfigFromFailOver() throws NacosException {
final String dataId = "1failover";
final String group = "2";
final String tenant = "public";
MockedStatic<LocalConfigInfoProcessor> localConfigInfoProcessorMockedStatic = Mockito.mockStatic(
LocalConfigInfoProcessor.class);
try {
String contentFailOver = "failOverContent" + System.currentTimeMillis();
localConfigInfoProcessorMockedStatic.when(
() -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant)))
.thenReturn(contentFailOver);
final int timeout = 3000;
final String config = nacosConfigService.getConfig(dataId, group, timeout);
assertEquals(contentFailOver, config);
} finally {
localConfigInfoProcessorMockedStatic.close();
}
}
@Test
void testGetConfigFromLocalCache() throws NacosException {
final String dataId = "1localcache";
final String group = "2";
final String tenant = "public";
MockedStatic<LocalConfigInfoProcessor> localConfigInfoProcessorMockedStatic = Mockito.mockStatic(
LocalConfigInfoProcessor.class);
try {
String contentFailOver = "localCacheContent" + System.currentTimeMillis();
//fail over null
localConfigInfoProcessorMockedStatic.when(
() -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant)))
.thenReturn(null);
//snapshot content
localConfigInfoProcessorMockedStatic.when(
() -> LocalConfigInfoProcessor.getSnapshot(any(), eq(dataId), eq(group), eq(tenant)))
.thenReturn(contentFailOver);
//form server error.
final int timeout = 3000;
Mockito.when(mockWoker.getServerConfig(dataId, group, tenant, timeout, false))
.thenThrow(new NacosException());
final String config = nacosConfigService.getConfig(dataId, group, timeout);
assertEquals(contentFailOver, config);
} finally {
localConfigInfoProcessorMockedStatic.close();
}
}
@Test
void testGetConfig403() throws NacosException {
final String dataId = "1localcache403";
final String group = "2";
final String tenant = "public";
MockedStatic<LocalConfigInfoProcessor> localConfigInfoProcessorMockedStatic = Mockito.mockStatic(
LocalConfigInfoProcessor.class);
try {
//fail over null
localConfigInfoProcessorMockedStatic.when(
() -> LocalConfigInfoProcessor.getFailover(any(), eq(dataId), eq(group), eq(tenant)))
.thenReturn(null);
//form server error.
final int timeout = 3000;
Mockito.when(mockWoker.getServerConfig(dataId, group, tenant, timeout, false))
.thenThrow(new NacosException(NacosException.NO_RIGHT, "no right"));
try {
nacosConfigService.getConfig(dataId, group, timeout);
assertTrue(false);
} catch (NacosException e) {
assertEquals(NacosException.NO_RIGHT, e.getErrCode());
}
} finally {
localConfigInfoProcessorMockedStatic.close();
}
}
@Test
void testGetConfigAndSignListener() throws NacosException {
final String dataId = "1";
final String group = "2";
final String tenant = "";
final String content = "123";
final int timeout = 3000;
final Listener listener = new Listener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
}
};
Properties properties = new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR, "aaa");
final NacosClientProperties nacosProperties = NacosClientProperties.PROTOTYPE.derive(properties);
ConfigServerListManager mgr = new ConfigServerListManager(nacosProperties);
mgr.start();
ConfigTransportClient client = new ConfigTransportClient(nacosProperties, mgr) {
@Override
public void startInternal() throws NacosException {
// NOOP
}
@Override
public String getName() {
return "TestConfigTransportClient";
}
@Override
public void notifyListenConfig() {
// NOOP
}
@Override
public void executeConfigListen() {
// NOOP
}
@Override
public void removeCache(String dataId, String group) {
// NOOP
}
@Override
public ConfigResponse queryConfig(String dataId, String group, String tenant, long readTimeous,
boolean notify) throws NacosException {
ConfigResponse configResponse = new ConfigResponse();
configResponse.setContent(content);
configResponse.setDataId(dataId);
configResponse.setGroup(group);
configResponse.setTenant(tenant);
return configResponse;
}
@Override
public boolean publishConfig(String dataId, String group, String tenant, String appName, String tag,
String betaIps, String content, String encryptedDataKey, String casMd5, String type)
throws NacosException {
return false;
}
@Override
public boolean removeConfig(String dataId, String group, String tenant, String tag) throws NacosException {
return false;
}
};
Mockito.when(mockWoker.getAgent()).thenReturn(client);
final String config = nacosConfigService.getConfigAndSignListener(dataId, group, timeout, listener);
assertEquals(content, config);
Mockito.verify(mockWoker, Mockito.times(1))
.addTenantListenersWithContent(dataId, group, content, null, Collections.singletonList(listener));
assertEquals(content, config);
Mockito.verify(mockWoker, Mockito.times(1))
.addTenantListenersWithContent(dataId, group, content, null, Arrays.asList(listener));
}
@Test
void testAddListener() throws NacosException {
String dataId = "1";
String group = "2";
Listener listener = new Listener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
}
};
nacosConfigService.addListener(dataId, group, listener);
Mockito.verify(mockWoker, Mockito.times(1)).addTenantListeners(dataId, group, Arrays.asList(listener));
}
@Test
void testPublishConfig() throws NacosException {
String dataId = "1";
String group = "2";
String content = "123";
String namespace = "public";
String type = ConfigType.getDefaultType().getType();
Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type))
.thenReturn(true);
final boolean b = nacosConfigService.publishConfig(dataId, group, content);
assertTrue(b);
Mockito.verify(mockWoker, Mockito.times(1))
.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type);
}
@Test
void testPublishConfig2() throws NacosException {
String dataId = "1";
String group = "2";
String content = "123";
String namespace = "public";
String type = ConfigType.PROPERTIES.getType();
Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type))
.thenReturn(true);
final boolean b = nacosConfigService.publishConfig(dataId, group, content, type);
assertTrue(b);
Mockito.verify(mockWoker, Mockito.times(1))
.publishConfig(dataId, group, namespace, null, null, null, content, "", null, type);
}
@Test
void testPublishConfigCas() throws NacosException {
String dataId = "1";
String group = "2";
String content = "123";
String namespace = "public";
String casMd5 = "96147704e3cb8be8597d55d75d244a02";
String type = ConfigType.getDefaultType().getType();
Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type))
.thenReturn(true);
final boolean b = nacosConfigService.publishConfigCas(dataId, group, content, casMd5);
assertTrue(b);
Mockito.verify(mockWoker, Mockito.times(1))
.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type);
}
@Test
void testPublishConfigCas2() throws NacosException {
String dataId = "1";
String group = "2";
String content = "123";
String namespace = "public";
String casMd5 = "96147704e3cb8be8597d55d75d244a02";
String type = ConfigType.PROPERTIES.getType();
Mockito.when(mockWoker.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type))
.thenReturn(true);
final boolean b = nacosConfigService.publishConfigCas(dataId, group, content, casMd5, type);
assertTrue(b);
Mockito.verify(mockWoker, Mockito.times(1))
.publishConfig(dataId, group, namespace, null, null, null, content, "", casMd5, type);
}
@Test
void testRemoveConfig() throws NacosException {
String dataId = "1";
String group = "2";
String tenant = "public";
Mockito.when(mockWoker.removeConfig(dataId, group, tenant, null)).thenReturn(true);
final boolean b = nacosConfigService.removeConfig(dataId, group);
assertTrue(b);
Mockito.verify(mockWoker, Mockito.times(1)).removeConfig(dataId, group, tenant, null);
}
@Test
void testRemoveListener() {
String dataId = "1";
String group = "2";
Listener listener = new Listener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
}
};
nacosConfigService.removeListener(dataId, group, listener);
Mockito.verify(mockWoker, Mockito.times(1)).removeTenantListener(dataId, group, listener);
}
@Test
void testGetServerStatus() {
Mockito.when(mockWoker.isHealthServer()).thenReturn(true);
assertEquals("UP", nacosConfigService.getServerStatus());
Mockito.verify(mockWoker, Mockito.times(1)).isHealthServer();
Mockito.when(mockWoker.isHealthServer()).thenReturn(false);
assertEquals("DOWN", nacosConfigService.getServerStatus());
Mockito.verify(mockWoker, Mockito.times(2)).isHealthServer();
}
@Test
void testFuzzyWatch1() throws NacosException {
String groupNamePattern = "default_group";
FuzzyWatchEventWatcher fuzzyWatchEventWatcher = new FuzzyWatchEventWatcher() {
@Override
public void onEvent(ConfigFuzzyWatchChangeEvent event) {
}
@Override
public Executor getExecutor() {
return null;
}
};
ConfigFuzzyWatchContext context = Mockito.mock(ConfigFuzzyWatchContext.class);
Mockito.when(mockWoker.addTenantFuzzyWatcher(anyString(), anyString(), any())).thenReturn(context);
nacosConfigService.fuzzyWatch(groupNamePattern, fuzzyWatchEventWatcher);
Mockito.verify(mockWoker, Mockito.times(1))
.addTenantFuzzyWatcher(ALL_PATTERN, groupNamePattern, fuzzyWatchEventWatcher);
Mockito.verify(context, Mockito.times(1)).createNewFuture();
}
@Test
void testFuzzyWatch2() throws NacosException {
String groupNamePattern = "default_group";
String dataIdPattern = "dataId*";
FuzzyWatchEventWatcher fuzzyWatchEventWatcher = new FuzzyWatchEventWatcher() {
@Override
public void onEvent(ConfigFuzzyWatchChangeEvent event) {
}
@Override
public Executor getExecutor() {
return null;
}
};
ConfigFuzzyWatchContext context = Mockito.mock(ConfigFuzzyWatchContext.class);
Mockito.when(mockWoker.addTenantFuzzyWatcher(anyString(), anyString(), any())).thenReturn(context);
nacosConfigService.fuzzyWatch(dataIdPattern, groupNamePattern, fuzzyWatchEventWatcher);
Mockito.verify(mockWoker, Mockito.times(1))
.addTenantFuzzyWatcher(dataIdPattern, groupNamePattern, fuzzyWatchEventWatcher);
Mockito.verify(context, Mockito.times(1)).createNewFuture();
}
@Test
void testFuzzyWatch3() throws NacosException {
String groupNamePattern = "group";
String dataIdPattern = "dataId*";
String namespace = "public";
FuzzyWatchEventWatcher fuzzyWatchEventWatcher = new FuzzyWatchEventWatcher() {
@Override
public void onEvent(ConfigFuzzyWatchChangeEvent event) {
}
@Override
public Executor getExecutor() {
return null;
}
};
String patternKey = FuzzyGroupKeyPattern.generatePattern(dataIdPattern, groupNamePattern, namespace);
ConfigFuzzyWatchContext context = new ConfigFuzzyWatchContext("", patternKey);
Mockito.when(mockWoker.addTenantFuzzyWatcher(anyString(), anyString(), any())).thenReturn(context);
Future<Set<String>> setFuture = nacosConfigService.fuzzyWatchWithGroupKeys(groupNamePattern,
fuzzyWatchEventWatcher);
Mockito.verify(mockWoker, Mockito.times(1))
.addTenantFuzzyWatcher(ALL_PATTERN, groupNamePattern, fuzzyWatchEventWatcher);
Assertions.assertNotNull(setFuture);
}
@Test
void testFuzzyWatch4() throws NacosException {
String groupNamePattern = "group";
String dataIdPattern = "dataId*";
String namespace = "public";
FuzzyWatchEventWatcher fuzzyWatchEventWatcher = new FuzzyWatchEventWatcher() {
@Override
public void onEvent(ConfigFuzzyWatchChangeEvent event) {
}
@Override
public Executor getExecutor() {
return null;
}
};
String patternKey = FuzzyGroupKeyPattern.generatePattern(dataIdPattern, groupNamePattern, namespace);
ConfigFuzzyWatchContext context = new ConfigFuzzyWatchContext("", patternKey);
Mockito.when(mockWoker.addTenantFuzzyWatcher(anyString(), anyString(), any())).thenReturn(context);
Future<Set<String>> setFuture = nacosConfigService.fuzzyWatchWithGroupKeys(dataIdPattern, groupNamePattern,
fuzzyWatchEventWatcher);
Mockito.verify(mockWoker, Mockito.times(1))
.addTenantFuzzyWatcher(dataIdPattern, groupNamePattern, fuzzyWatchEventWatcher);
Assertions.assertNotNull(setFuture);
}
@Test
void testShutDown() {
Assertions.assertDoesNotThrow(() -> {
nacosConfigService.shutDown();
});
}
}
|
NacosConfigServiceTest
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/api/extension/ExecutableInvokerIntegrationTests.java
|
{
"start": 1496,
"end": 2036
}
|
class ____ {
static int testInvocations = 0;
@SuppressWarnings("JUnitMalformedDeclaration")
@Test
void testWithResolvedParameter(TestInfo testInfo,
@ExtendWith(ExtensionContextParameterResolver.class) ExtensionContext extensionContext) {
assertNotNull(testInfo);
assertEquals(testInfo.getTestMethod().orElseThrow(), extensionContext.getRequiredTestMethod());
testInvocations++;
}
}
@SuppressWarnings("JUnitMalformedDeclaration")
@ExtendWith(ExecuteConstructorTwiceExtension.class)
static
|
ExecuteTestsTwiceTestCase
|
java
|
spring-projects__spring-framework
|
spring-core/src/main/java/org/springframework/asm/ClassVisitor.java
|
{
"start": 7246,
"end": 7578
}
|
class ____ the nest (see {@link
* Type#getInternalName()}).
*/
public void visitNestHost(final String nestHost) {
if (api < Opcodes.ASM7) {
throw new UnsupportedOperationException("NestHost requires ASM7");
}
if (cv != null) {
cv.visitNestHost(nestHost);
}
}
/**
* Visits the enclosing
|
of
|
java
|
apache__flink
|
flink-tests-java17/src/test/java/org/apache/flink/api/java/typeutils/runtime/PojoRecordSerializerUpgradeTestSpecifications.java
|
{
"start": 4971,
"end": 6313
}
|
class ____
implements TypeSerializerUpgradeTestBase.UpgradeVerifier<
RecordMigrationVerifier.RecordAfterSchemaUpgrade> {
@ClassRelocator.RelocateClass("TestRecordMigration")
@SuppressWarnings("WeakerAccess")
public record RecordAfterSchemaUpgrade(String name, int age, String newField) {}
@Override
public TypeSerializer<RecordAfterSchemaUpgrade> createUpgradedSerializer() {
TypeSerializer<RecordAfterSchemaUpgrade> serializer =
TypeExtractor.createTypeInfo(RecordAfterSchemaUpgrade.class)
.createSerializer(new SerializerConfigImpl());
assertThat(serializer.getClass()).isSameAs(PojoSerializer.class);
return serializer;
}
@Override
public Condition<RecordAfterSchemaUpgrade> testDataCondition() {
return new Condition<>(
new RecordAfterSchemaUpgrade("Gordon", 0, null)::equals,
"value is (Gordon, 0 ,null)");
}
@Override
public Condition<TypeSerializerSchemaCompatibility<RecordAfterSchemaUpgrade>>
schemaCompatibilityCondition(FlinkVersion version) {
return TypeSerializerConditions.isCompatibleAfterMigration();
}
}
}
|
RecordMigrationVerifier
|
java
|
alibaba__druid
|
core/src/test/java/com/alibaba/druid/bvt/pool/TestGetUpdateCount.java
|
{
"start": 4025,
"end": 4758
}
|
class ____ extends MockPreparedStatement {
Integer updateCount;
public MyPreparedStatement(MockConnection conn, String sql) {
super(conn, sql);
}
public boolean execute() throws SQLException {
updateCount = null;
return false;
}
public ResultSet executeQuery() throws SQLException {
updateCount = -1;
return super.executeQuery();
}
@Override
public int getUpdateCount() throws SQLException {
if (updateCount != null) {
throw new SQLException("illegal state");
}
updateCount = 1;
return updateCount;
}
}
}
|
MyPreparedStatement
|
java
|
apache__flink
|
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/shuffle/AllTieredShuffleMasterSnapshots.java
|
{
"start": 1147,
"end": 1854
}
|
class ____ implements Serializable {
/**
* Snapshots of all tires. For each tier, it is a tuple of
* (identifier,TieredShuffleMasterSnapshot)
*/
private final Collection<Tuple2<String, TieredShuffleMasterSnapshot>> snapshots;
public AllTieredShuffleMasterSnapshots(
Collection<Tuple2<String, TieredShuffleMasterSnapshot>> snapshots) {
this.snapshots = snapshots;
}
public Collection<Tuple2<String, TieredShuffleMasterSnapshot>> getSnapshots() {
return snapshots;
}
public static AllTieredShuffleMasterSnapshots empty() {
return new AllTieredShuffleMasterSnapshots(Collections.emptyList());
}
}
|
AllTieredShuffleMasterSnapshots
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.