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
apache__kafka
streams/src/test/java/org/apache/kafka/streams/kstream/internals/graph/GraphGraceSearchUtilTest.java
{ "start": 1718, "end": 10635 }
class ____ { @Test public void shouldThrowOnNull() { try { GraphGraceSearchUtil.findAndVerifyWindowGrace(null); fail("Should have thrown."); } catch (final TopologyException e) { assertThat(e.getMessage(), is("Invalid topology: Window close time is only defined for windowed computations. Got [].")); } } @Test public void shouldFailIfThereIsNoGraceAncestor() { // doesn't matter if this ancestor is stateless or stateful. The important thing it that there is // no grace period defined on any ancestor of the node final ProcessorGraphNode<String, Long> gracelessAncestor = new ProcessorGraphNode<>( "graceless", new ProcessorParameters<>( () -> new Processor<String, Long, String, Long>() { @Override public void process(final Record<String, Long> record) {} }, "graceless" ) ); final ProcessorGraphNode<String, Long> node = new ProcessorGraphNode<>( "stateless", new ProcessorParameters<>( () -> new Processor<String, Long, String, Long>() { @Override public void process(final Record<String, Long> record) {} }, "stateless" ) ); gracelessAncestor.addChild(node); try { GraphGraceSearchUtil.findAndVerifyWindowGrace(node); fail("should have thrown."); } catch (final TopologyException e) { assertThat(e.getMessage(), is("Invalid topology: Window close time is only defined for windowed computations. Got [graceless->stateless].")); } } @Test public void shouldExtractGraceFromKStreamWindowAggregateNode() { final TimeWindows windows = TimeWindows.ofSizeAndGrace(ofMillis(10L), ofMillis(1234L)); final ProcessorGraphNode<String, Long> node = new GracePeriodGraphNode<>( "asdf", new ProcessorParameters<>( new KStreamWindowAggregate<String, Long, Integer, TimeWindow>( windows, mockStoreFactory("asdf"), EmitStrategy.onWindowUpdate(), null, null ), "asdf" ), windows.gracePeriodMs() ); final long extracted = GraphGraceSearchUtil.findAndVerifyWindowGrace(node); assertThat(extracted, is(1234L)); } @Test public void shouldExtractGraceFromKStreamSessionWindowAggregateNode() { final SessionWindows windows = SessionWindows.ofInactivityGapAndGrace(ofMillis(10L), ofMillis(1234L)); final ProcessorGraphNode<String, Long> node = new GracePeriodGraphNode<>( "asdf", new ProcessorParameters<>( new KStreamSessionWindowAggregate<String, Long, Integer>( windows, mockStoreFactory("asdf"), EmitStrategy.onWindowUpdate(), null, null, null ), "asdf" ), windows.gracePeriodMs() + windows.inactivityGap() ); final long extracted = GraphGraceSearchUtil.findAndVerifyWindowGrace(node); assertThat(extracted, is(1244L)); } @Test public void shouldExtractGraceFromSessionAncestorThroughStatefulParent() { final SessionWindows windows = SessionWindows.ofInactivityGapAndGrace(ofMillis(10L), ofMillis(1234L)); final ProcessorGraphNode<String, Long> graceGrandparent = new GracePeriodGraphNode<>( "asdf", new ProcessorParameters<>(new KStreamSessionWindowAggregate<String, Long, Integer>( windows, mockStoreFactory("asdf"), EmitStrategy.onWindowUpdate(), null, null, null ), "asdf"), windows.gracePeriodMs() + windows.inactivityGap() ); final ProcessorGraphNode<String, Long> statefulParent = new ProcessorGraphNode<>( "stateful", new ProcessorParameters<>( () -> new Processor<String, Long, String, Long>() { @Override public void process(final Record<String, Long> record) {} }, "dummy" ) ); graceGrandparent.addChild(statefulParent); final ProcessorGraphNode<String, Long> node = new ProcessorGraphNode<>( "stateless", new ProcessorParameters<>( () -> new Processor<String, Long, String, Long>() { @Override public void process(final Record<String, Long> record) {} }, "dummyChild-graceless" ) ); statefulParent.addChild(node); final long extracted = GraphGraceSearchUtil.findAndVerifyWindowGrace(node); assertThat(extracted, is(1244L)); } @Test public void shouldExtractGraceFromSessionAncestorThroughStatelessParent() { final SessionWindows windows = SessionWindows.ofInactivityGapAndGrace(ofMillis(10L), ofMillis(1234L)); final ProcessorGraphNode<String, Long> graceGrandparent = new GracePeriodGraphNode<>( "asdf", new ProcessorParameters<>( new KStreamSessionWindowAggregate<String, Long, Integer>( windows, mockStoreFactory("asdf"), EmitStrategy.onWindowUpdate(), null, null, null ), "asdf" ), windows.gracePeriodMs() + windows.inactivityGap() ); final ProcessorGraphNode<String, Long> statelessParent = new ProcessorGraphNode<>( "statelessParent", new ProcessorParameters<>( () -> new Processor<String, Long, String, Long>() { @Override public void process(final Record<String, Long> record) {} }, "statelessParent" ) ); graceGrandparent.addChild(statelessParent); final ProcessorGraphNode<String, Long> node = new ProcessorGraphNode<>( "stateless", new ProcessorParameters<>( () -> new Processor<String, Long, String, Long>() { @Override public void process(final Record<String, Long> record) {} }, "stateless" ) ); statelessParent.addChild(node); final long extracted = GraphGraceSearchUtil.findAndVerifyWindowGrace(node); assertThat(extracted, is(1244L)); } @Test public void shouldUseMaxIfMultiParentsDoNotAgreeOnGrace() { final SessionWindows leftWindows = SessionWindows.ofInactivityGapAndGrace(ofMillis(10L), ofMillis(1234L)); final ProcessorGraphNode<String, Long> leftParent = new GracePeriodGraphNode<>( "asdf", new ProcessorParameters<>( new KStreamSessionWindowAggregate<String, Long, Integer>( leftWindows, mockStoreFactory("asdf"), EmitStrategy.onWindowUpdate(), null, null, null ), "asdf" ), leftWindows.gracePeriodMs() + leftWindows.inactivityGap() ); final TimeWindows rightWindows = TimeWindows.ofSizeAndGrace(ofMillis(10L), ofMillis(4321L)); final ProcessorGraphNode<String, Long> rightParent = new GracePeriodGraphNode<>( "asdf", new ProcessorParameters<>( new KStreamWindowAggregate<String, Long, Integer, TimeWindow>( rightWindows, mockStoreFactory("asdf"), EmitStrategy.onWindowUpdate(), null, null ), "asdf" ), rightWindows.gracePeriodMs() ); final ProcessorGraphNode<String, Long> node = new ProcessorGraphNode<>( "stateless", new ProcessorParameters<>( () -> new Processor<String, Long, String, Long>() { @Override public void process(final Record<String, Long> record) {} }, "stateless" ) ); leftParent.addChild(node); rightParent.addChild(node); final long extracted = GraphGraceSearchUtil.findAndVerifyWindowGrace(node); assertThat(extracted, is(4321L)); } }
GraphGraceSearchUtilTest
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/runtime/stream/sql/FunctionITCase.java
{ "start": 4614, "end": 4811 }
class ____ meant for testing the core function support. Use {@code * org.apache.flink.table.planner.functions.BuiltInFunctionTestBase} for testing individual function * implementations. */ public
is
java
quarkusio__quarkus
independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/commands/handlers/ListExtensionsCommandHandler.java
{ "start": 1307, "end": 1449 }
class ____ thread-safe. It lists extensions according to the options passed in as properties of * {@link QuarkusCommandInvocation} */ public
are
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MissingOverrideTest.java
{ "start": 3120, "end": 3283 }
class ____ { static void f() {} } """) .addSourceLines( "Test.java", """ public
Super
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableMapNotification.java
{ "start": 1840, "end": 3896 }
class ____<T, R> extends SinglePostCompleteSubscriber<T, R> { private static final long serialVersionUID = 2757120512858778108L; final Function<? super T, ? extends R> onNextMapper; final Function<? super Throwable, ? extends R> onErrorMapper; final Supplier<? extends R> onCompleteSupplier; MapNotificationSubscriber(Subscriber<? super R> actual, Function<? super T, ? extends R> onNextMapper, Function<? super Throwable, ? extends R> onErrorMapper, Supplier<? extends R> onCompleteSupplier) { super(actual); this.onNextMapper = onNextMapper; this.onErrorMapper = onErrorMapper; this.onCompleteSupplier = onCompleteSupplier; } @Override public void onNext(T t) { R p; try { p = Objects.requireNonNull(onNextMapper.apply(t), "The onNext publisher returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); downstream.onError(e); return; } produced++; downstream.onNext(p); } @Override public void onError(Throwable t) { R p; try { p = Objects.requireNonNull(onErrorMapper.apply(t), "The onError publisher returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); downstream.onError(new CompositeException(t, e)); return; } complete(p); } @Override public void onComplete() { R p; try { p = Objects.requireNonNull(onCompleteSupplier.get(), "The onComplete publisher returned is null"); } catch (Throwable e) { Exceptions.throwIfFatal(e); downstream.onError(e); return; } complete(p); } } }
MapNotificationSubscriber
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/config/TransactionManagementConfigUtils.java
{ "start": 2079, "end": 2377 }
class ____ of the AspectJ transaction management aspect. * @since 5.1 */ public static final String JTA_TRANSACTION_ASPECT_CLASS_NAME = "org.springframework.transaction.aspectj.JtaAnnotationTransactionAspect"; /** * The name of the AspectJ transaction management @{@code Configuration}
name
java
google__guava
android/guava/src/com/google/common/hash/BloomFilterStrategies.java
{ "start": 1528, "end": 5888 }
enum ____ implements BloomFilter.Strategy { /** * See "Less Hashing, Same Performance: Building a Better Bloom Filter" by Adam Kirsch and Michael * Mitzenmacher. The paper argues that this trick doesn't significantly deteriorate the * performance of a Bloom filter (yet only needs two 32bit hash functions). */ MURMUR128_MITZ_32() { @Override public <T extends @Nullable Object> boolean put( @ParametricNullness T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits) { long bitSize = bits.bitSize(); long hash64 = Hashing.murmur3_128().hashObject(object, funnel).asLong(); int hash1 = (int) hash64; int hash2 = (int) (hash64 >>> 32); boolean bitsChanged = false; for (int i = 1; i <= numHashFunctions; i++) { int combinedHash = hash1 + (i * hash2); // Flip all the bits if it's negative (guaranteed positive number) if (combinedHash < 0) { combinedHash = ~combinedHash; } bitsChanged |= bits.set(combinedHash % bitSize); } return bitsChanged; } @Override public <T extends @Nullable Object> boolean mightContain( @ParametricNullness T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits) { long bitSize = bits.bitSize(); long hash64 = Hashing.murmur3_128().hashObject(object, funnel).asLong(); int hash1 = (int) hash64; int hash2 = (int) (hash64 >>> 32); for (int i = 1; i <= numHashFunctions; i++) { int combinedHash = hash1 + (i * hash2); // Flip all the bits if it's negative (guaranteed positive number) if (combinedHash < 0) { combinedHash = ~combinedHash; } if (!bits.get(combinedHash % bitSize)) { return false; } } return true; } }, /** * This strategy uses all 128 bits of {@link Hashing#murmur3_128} when hashing. It looks different * from the implementation in MURMUR128_MITZ_32 because we're avoiding the multiplication in the * loop and doing a (much simpler) += hash2. We're also changing the index to a positive number by * AND'ing with Long.MAX_VALUE instead of flipping the bits. */ MURMUR128_MITZ_64() { @Override public <T extends @Nullable Object> boolean put( @ParametricNullness T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits) { long bitSize = bits.bitSize(); byte[] bytes = Hashing.murmur3_128().hashObject(object, funnel).getBytesInternal(); long hash1 = lowerEight(bytes); long hash2 = upperEight(bytes); boolean bitsChanged = false; long combinedHash = hash1; for (int i = 0; i < numHashFunctions; i++) { // Make the combined hash positive and indexable bitsChanged |= bits.set((combinedHash & Long.MAX_VALUE) % bitSize); combinedHash += hash2; } return bitsChanged; } @Override public <T extends @Nullable Object> boolean mightContain( @ParametricNullness T object, Funnel<? super T> funnel, int numHashFunctions, LockFreeBitArray bits) { long bitSize = bits.bitSize(); byte[] bytes = Hashing.murmur3_128().hashObject(object, funnel).getBytesInternal(); long hash1 = lowerEight(bytes); long hash2 = upperEight(bytes); long combinedHash = hash1; for (int i = 0; i < numHashFunctions; i++) { // Make the combined hash positive and indexable if (!bits.get((combinedHash & Long.MAX_VALUE) % bitSize)) { return false; } combinedHash += hash2; } return true; } private /* static */ long lowerEight(byte[] bytes) { return Longs.fromBytes( bytes[7], bytes[6], bytes[5], bytes[4], bytes[3], bytes[2], bytes[1], bytes[0]); } private /* static */ long upperEight(byte[] bytes) { return Longs.fromBytes( bytes[15], bytes[14], bytes[13], bytes[12], bytes[11], bytes[10], bytes[9], bytes[8]); } }; /** * Models a lock-free array of bits. * * <p>We use this instead of java.util.BitSet because we need access to the array of longs and we * need compare-and-swap. */ static final
BloomFilterStrategies
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/StaticExpression.java
{ "start": 949, "end": 1152 }
interface ____ extends Expression { /** * Gets the constant value */ Object getValue(); /** * Sets the constant value */ void setValue(Object value); }
StaticExpression
java
elastic__elasticsearch
x-pack/plugin/ql/src/main/java/org/elasticsearch/xpack/ql/expression/function/TwoOptionalArguments.java
{ "start": 325, "end": 515 }
interface ____ that a function accepts two optional arguments (the last two). * This is used by the {@link FunctionRegistry} to perform validation of function declaration. */ public
indicating
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/plugins/spi/NamedXContentProviderTests.java
{ "start": 1011, "end": 2434 }
class ____ extends ESTestCase { public void testSpiFileExists() throws IOException { String serviceFile = "/META-INF/services/" + NamedXContentProvider.class.getName(); List<String> implementations = new ArrayList<>(); try (InputStream input = NamedXContentProviderTests.class.getResourceAsStream(serviceFile)) { Streams.readAllLines(input, implementations::add); } assertEquals(1, implementations.size()); assertEquals(TestNamedXContentProvider.class.getName(), implementations.get(0)); } public void testNamedXContents() { final List<NamedXContentRegistry.Entry> namedXContents = new ArrayList<>(); for (NamedXContentProvider service : ServiceLoader.load(NamedXContentProvider.class)) { namedXContents.addAll(service.getNamedXContentParsers()); } assertEquals(2, namedXContents.size()); List<Predicate<NamedXContentRegistry.Entry>> predicates = new ArrayList<>(2); predicates.add(e -> Suggest.Suggestion.class.equals(e.categoryClass) && "phrase_aggregation".equals(e.name.getPreferredName())); predicates.add(e -> Suggest.Suggestion.class.equals(e.categoryClass) && "test_suggestion".equals(e.name.getPreferredName())); predicates.forEach(predicate -> assertEquals(1, namedXContents.stream().filter(predicate).count())); } public static
NamedXContentProviderTests
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/rm/ContainerRequestCreator.java
{ "start": 1253, "end": 2326 }
class ____ { private ContainerRequestCreator() {} static ContainerRequestEvent createRequest(JobId jobId, int taskAttemptId, Resource resource, String[] hosts) { return createRequest(jobId, taskAttemptId, resource, hosts, false, false); } static ContainerRequestEvent createRequest(JobId jobId, int taskAttemptId, Resource resource, String[] hosts, boolean earlierFailedAttempt, boolean reduce) { final TaskId taskId; if (reduce) { taskId = MRBuilderUtils.newTaskId(jobId, 0, TaskType.REDUCE); } else { taskId = MRBuilderUtils.newTaskId(jobId, 0, TaskType.MAP); } TaskAttemptId attemptId = MRBuilderUtils.newTaskAttemptId(taskId, taskAttemptId); if (earlierFailedAttempt) { return ContainerRequestEvent .createContainerRequestEventForFailedContainer(attemptId, resource); } return new ContainerRequestEvent(attemptId, resource, hosts, new String[]{NetworkTopology.DEFAULT_RACK}); } }
ContainerRequestCreator
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/KubernetesServicesComponentBuilderFactory.java
{ "start": 6134, "end": 7292 }
class ____ extends AbstractComponentBuilder<KubernetesServicesComponent> implements KubernetesServicesComponentBuilder { @Override protected KubernetesServicesComponent buildConcreteComponent() { return new KubernetesServicesComponent(); } @Override protected boolean setPropertyOnComponent( Component component, String name, Object value) { switch (name) { case "kubernetesClient": ((KubernetesServicesComponent) component).setKubernetesClient((io.fabric8.kubernetes.client.KubernetesClient) value); return true; case "bridgeErrorHandler": ((KubernetesServicesComponent) component).setBridgeErrorHandler((boolean) value); return true; case "lazyStartProducer": ((KubernetesServicesComponent) component).setLazyStartProducer((boolean) value); return true; case "autowiredEnabled": ((KubernetesServicesComponent) component).setAutowiredEnabled((boolean) value); return true; default: return false; } } } }
KubernetesServicesComponentBuilderImpl
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/utils/DummyStreamExecutionEnvironment.java
{ "start": 3587, "end": 3616 }
class ____ removed. */ public
is
java
elastic__elasticsearch
x-pack/plugin/kql/src/main/java/org/elasticsearch/xpack/kql/parser/KqlBaseParser.java
{ "start": 45334, "end": 47377 }
class ____ extends ParserRuleContext { public FieldNameContext fieldName() { return getRuleContext(FieldNameContext.class,0); } public TerminalNode COLON() { return getToken(KqlBaseParser.COLON, 0); } public FieldQueryValueContext fieldQueryValue() { return getRuleContext(FieldQueryValueContext.class,0); } public FieldQueryContext(ParserRuleContext parent, int invokingState) { super(parent, invokingState); } @Override public int getRuleIndex() { return RULE_fieldQuery; } @Override public void enterRule(ParseTreeListener listener) { if ( listener instanceof KqlBaseListener ) ((KqlBaseListener)listener).enterFieldQuery(this); } @Override public void exitRule(ParseTreeListener listener) { if ( listener instanceof KqlBaseListener ) ((KqlBaseListener)listener).exitFieldQuery(this); } @Override public <T> T accept(ParseTreeVisitor<? extends T> visitor) { if ( visitor instanceof KqlBaseVisitor ) return ((KqlBaseVisitor<? extends T>)visitor).visitFieldQuery(this); else return visitor.visitChildren(this); } } public final FieldQueryContext fieldQuery() throws RecognitionException { FieldQueryContext _localctx = new FieldQueryContext(_ctx, getState()); enterRule(_localctx, 26, RULE_fieldQuery); try { enterOuterAlt(_localctx, 1); { setState(125); fieldName(); setState(126); match(COLON); setState(127); fieldQueryValue(); } } catch (RecognitionException re) { _localctx.exception = re; _errHandler.reportError(this, re); _errHandler.recover(this, re); } finally { exitRule(); } return _localctx; } @SuppressWarnings("CheckReturnValue") public static
FieldQueryContext
java
elastic__elasticsearch
x-pack/plugin/text-structure/src/test/java/org/elasticsearch/xpack/textstructure/structurefinder/XmlTextStructureFinderFactoryTests.java
{ "start": 373, "end": 2163 }
class ____ extends TextStructureTestCase { private final TextStructureFinderFactory factory = new XmlTextStructureFinderFactory(); // No need to check NDJSON because it comes earlier in the order we check formats public void testCanCreateFromSampleGivenXml() { assertTrue(factory.canCreateFromSample(explanation, XML_SAMPLE, 0.0)); } public void testCanCreateFromMessages() { List<String> messages = Arrays.asList(XML_SAMPLE.split("\n\n")); assertTrue(factory.canCreateFromMessages(explanation, messages, 0.0)); } public void testCanCreateFromMessages_multipleXmlDocsPerMessage() { List<String> messages = List.of(XML_SAMPLE, XML_SAMPLE, XML_SAMPLE); assertFalse(factory.canCreateFromMessages(explanation, messages, 0.0)); } public void testCanCreateFromMessages_emptyMessages() { List<String> messages = List.of("", "", ""); assertFalse(factory.canCreateFromMessages(explanation, messages, 0.0)); } public void testCanCreateFromSampleGivenCsv() { assertFalse(factory.canCreateFromSample(explanation, CSV_SAMPLE, 0.0)); } public void testCanCreateFromSampleGivenTsv() { assertFalse(factory.canCreateFromSample(explanation, TSV_SAMPLE, 0.0)); } public void testCanCreateFromSampleGivenSemiColonDelimited() { assertFalse(factory.canCreateFromSample(explanation, SEMI_COLON_DELIMITED_SAMPLE, 0.0)); } public void testCanCreateFromSampleGivenPipeDelimited() { assertFalse(factory.canCreateFromSample(explanation, PIPE_DELIMITED_SAMPLE, 0.0)); } public void testCanCreateFromSampleGivenText() { assertFalse(factory.canCreateFromSample(explanation, TEXT_SAMPLE, 0.0)); } }
XmlTextStructureFinderFactoryTests
java
elastic__elasticsearch
x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/action/ShardFollowNodeTaskTests.java
{ "start": 62057, "end": 72398 }
class ____ { private String remoteCluster = null; private ShardId followShardId = new ShardId("follow_index", "", 0); private ShardId leaderShardId = new ShardId("leader_index", "", 0); private int maxReadRequestOperationCount = Integer.MAX_VALUE; private ByteSizeValue maxReadRequestSize = ByteSizeValue.ofBytes(Long.MAX_VALUE); private int maxOutstandingReadRequests = Integer.MAX_VALUE; private int maxWriteRequestOperationCount = Integer.MAX_VALUE; private ByteSizeValue maxWriteRequestSize = ByteSizeValue.ofBytes(Long.MAX_VALUE); private int maxOutstandingWriteRequests = Integer.MAX_VALUE; private int maxWriteBufferCount = Integer.MAX_VALUE; private ByteSizeValue maxWriteBufferSize = ByteSizeValue.ofBytes(Long.MAX_VALUE); private TimeValue maxRetryDelay = TimeValue.ZERO; private TimeValue readPollTimeout = TimeValue.ZERO; private Map<String, String> headers = Collections.emptyMap(); } private ShardFollowNodeTask createShardFollowTask(ShardFollowTaskParams params) { AtomicBoolean stopped = new AtomicBoolean(false); ShardFollowTask followTask = new ShardFollowTask( params.remoteCluster, params.followShardId, params.leaderShardId, params.maxReadRequestOperationCount, params.maxWriteRequestOperationCount, params.maxOutstandingReadRequests, params.maxOutstandingWriteRequests, params.maxReadRequestSize, params.maxWriteRequestSize, params.maxWriteBufferCount, params.maxWriteBufferSize, params.maxRetryDelay, params.readPollTimeout, params.headers ); shardChangesRequests = new ArrayList<>(); bulkShardOperationRequests = new ArrayList<>(); readFailures = new LinkedList<>(); writeFailures = new LinkedList<>(); mappingUpdateFailures = new LinkedList<>(); mappingVersions = new LinkedList<>(); settingsUpdateFailures = new LinkedList<>(); settingsVersions = new LinkedList<>(); aliasesUpdateFailures = new LinkedList<>(); aliasesVersions = new LinkedList<>(); leaderGlobalCheckpoints = new LinkedList<>(); followerGlobalCheckpoints = new LinkedList<>(); maxSeqNos = new LinkedList<>(); responseSizes = new LinkedList<>(); pendingBulkShardRequests = new LinkedList<>(); return new ShardFollowNodeTask( 1L, "type", ShardFollowTask.NAME, "description", null, Collections.emptyMap(), followTask, scheduler, System::nanoTime ) { @Override protected void innerUpdateMapping(long minRequiredMappingVersion, LongConsumer handler, Consumer<Exception> errorHandler) { Exception failure = mappingUpdateFailures.poll(); if (failure != null) { errorHandler.accept(failure); return; } final Long mappingVersion = mappingVersions.poll(); if (mappingVersion != null) { handler.accept(mappingVersion); } } @Override protected void innerUpdateSettings(LongConsumer handler, Consumer<Exception> errorHandler) { Exception failure = settingsUpdateFailures.poll(); if (failure != null) { errorHandler.accept(failure); return; } final Long settingsVersion = settingsVersions.poll(); if (settingsVersion != null) { handler.accept(settingsVersion); } } @Override protected void innerUpdateAliases(final LongConsumer handler, final Consumer<Exception> errorHandler) { final Exception failure = aliasesUpdateFailures.poll(); if (failure != null) { errorHandler.accept(failure); return; } final Long aliasesVersion = aliasesVersions.poll(); if (aliasesVersion != null) { handler.accept(aliasesVersion); } } @Override protected void innerSendBulkShardOperationsRequest( String followerHistoryUUID, final List<Translog.Operation> operations, final long maxSeqNoOfUpdates, final Consumer<BulkShardOperationsResponse> handler, final Consumer<Exception> errorHandler ) { bulkShardOperationRequests.add(operations); Exception writeFailure = ShardFollowNodeTaskTests.this.writeFailures.poll(); if (writeFailure != null) { errorHandler.accept(writeFailure); return; } Long followerGlobalCheckpoint = followerGlobalCheckpoints.poll(); if (followerGlobalCheckpoint != null) { final BulkShardOperationsResponse response = new BulkShardOperationsResponse(); response.setGlobalCheckpoint(followerGlobalCheckpoint); response.setMaxSeqNo(followerGlobalCheckpoint); handler.accept(response); } else { pendingBulkShardRequests.add(ActionListener.wrap(handler::accept, errorHandler)); } } @Override protected void innerSendShardChangesRequest( long from, int requestBatchSize, Consumer<ShardChangesAction.Response> handler, Consumer<Exception> errorHandler ) { beforeSendShardChangesRequest.accept(getStatus()); shardChangesRequests.add(new long[] { from, requestBatchSize }); Exception readFailure = ShardFollowNodeTaskTests.this.readFailures.poll(); if (readFailure != null) { errorHandler.accept(readFailure); } else if (simulateResponse.get()) { final int responseSize = responseSizes.size() == 0 ? 0 : responseSizes.poll(); final Translog.Operation[] operations = new Translog.Operation[responseSize]; for (int i = 0; i < responseSize; i++) { operations[i] = new Translog.NoOp(from + i, 0, "test"); } final ShardChangesAction.Response response = new ShardChangesAction.Response( mappingVersions.poll(), 0L, 0L, leaderGlobalCheckpoints.poll(), maxSeqNos.poll(), randomNonNegativeLong(), operations, 1L ); handler.accept(response); } } @Override protected Scheduler.Cancellable scheduleBackgroundRetentionLeaseRenewal(final LongSupplier followerGlobalCheckpoint) { if (scheduleRetentionLeaseRenewal.get()) { final ScheduledThreadPoolExecutor testScheduler = Scheduler.initScheduler(Settings.EMPTY, "test-scheduler"); final ScheduledFuture<?> future = testScheduler.scheduleWithFixedDelay( () -> retentionLeaseRenewal.accept(followerGlobalCheckpoint.getAsLong()), 0, TimeValue.timeValueMillis(200).millis(), TimeUnit.MILLISECONDS ); return new Scheduler.Cancellable() { @Override public boolean cancel() { final boolean cancel = future.cancel(true); testScheduler.shutdown(); return cancel; } @Override public boolean isCancelled() { return future.isCancelled(); } }; } else { return new Scheduler.Cancellable() { @Override public boolean cancel() { return true; } @Override public boolean isCancelled() { return true; } }; } } @Override protected boolean isStopped() { return super.isStopped() || stopped.get(); } @Override public void markAsCompleted() { stopped.set(true); } }; } private static ShardChangesAction.Response generateShardChangesResponse( long fromSeqNo, long toSeqNo, long mappingVersion, long settingsVersion, long aliasesVersion, long leaderGlobalCheckPoint ) { List<Translog.Operation> ops = new ArrayList<>(); for (long seqNo = fromSeqNo; seqNo <= toSeqNo; seqNo++) { String id = UUIDs.randomBase64UUID(); ops.add(TranslogOperationsUtils.indexOp(id, seqNo, 0)); } return new ShardChangesAction.Response( mappingVersion, settingsVersion, aliasesVersion, leaderGlobalCheckPoint, leaderGlobalCheckPoint, randomNonNegativeLong(), ops.toArray(new Translog.Operation[0]), 1L ); } void startTask(ShardFollowNodeTask task, long leaderGlobalCheckpoint, long followerGlobalCheckpoint) { // The call the updateMapping is a noop, so noting happens. task.start("uuid", leaderGlobalCheckpoint, leaderGlobalCheckpoint, followerGlobalCheckpoint, followerGlobalCheckpoint); } }
ShardFollowTaskParams
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsSpringRunnerTests.java
{ "start": 3720, "end": 3952 }
class ____ implements TestExecutionListener { @Override public void beforeTestClass(TestContext testContext) { fail("always failing beforeTestClass()"); } } protected static
AlwaysFailingBeforeTestClassTestExecutionListener
java
apache__camel
components/camel-crypto/src/main/java/org/apache/camel/component/crypto/DigitalSignatureComponent.java
{ "start": 1213, "end": 2727 }
class ____ extends DefaultComponent { @Metadata(label = "advanced") private DigitalSignatureConfiguration configuration = new DigitalSignatureConfiguration(); public DigitalSignatureComponent() { } public DigitalSignatureComponent(CamelContext context) { super(context); } @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { ObjectHelper.notNull(getCamelContext(), "CamelContext"); DigitalSignatureConfiguration config = getConfiguration().copy(); config.setCamelContext(getCamelContext()); try { config.setCryptoOperation(new URI(remaining).getScheme()); } catch (Exception e) { throw new MalformedURLException( String.format("An invalid crypto uri was provided '%s'." + " Check the uri matches the format crypto:sign or crypto:verify", uri)); } Endpoint endpoint = new DigitalSignatureEndpoint(uri, this, config); setProperties(endpoint, parameters); return endpoint; } public DigitalSignatureConfiguration getConfiguration() { return configuration; } /** * To use the shared DigitalSignatureConfiguration as configuration */ public void setConfiguration(DigitalSignatureConfiguration configuration) { this.configuration = configuration; } }
DigitalSignatureComponent
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/v2/app/speculate/LegacyTaskRuntimeEstimator.java
{ "start": 1485, "end": 4965 }
class ____ extends StartEndTimesBase { private final Map<TaskAttempt, AtomicLong> attemptRuntimeEstimates = new ConcurrentHashMap<TaskAttempt, AtomicLong>(); private final ConcurrentHashMap<TaskAttempt, AtomicLong> attemptRuntimeEstimateVariances = new ConcurrentHashMap<TaskAttempt, AtomicLong>(); @Override public void updateAttempt(TaskAttemptStatus status, long timestamp) { super.updateAttempt(status, timestamp); TaskAttemptId attemptID = status.id; TaskId taskID = attemptID.getTaskId(); JobId jobID = taskID.getJobId(); Job job = context.getJob(jobID); if (job == null) { return; } Task task = job.getTask(taskID); if (task == null) { return; } TaskAttempt taskAttempt = task.getAttempt(attemptID); if (taskAttempt == null) { return; } Long boxedStart = startTimes.get(attemptID); long start = boxedStart == null ? Long.MIN_VALUE : boxedStart; // We need to do two things. // 1: If this is a completion, we accumulate statistics in the superclass // 2: If this is not a completion, we learn more about it. // This is not a completion, but we're cooking. // if (taskAttempt.getState() == TaskAttemptState.RUNNING) { // See if this task is already in the registry AtomicLong estimateContainer = attemptRuntimeEstimates.get(taskAttempt); AtomicLong estimateVarianceContainer = attemptRuntimeEstimateVariances.get(taskAttempt); if (estimateContainer == null) { if (attemptRuntimeEstimates.get(taskAttempt) == null) { attemptRuntimeEstimates.put(taskAttempt, new AtomicLong()); estimateContainer = attemptRuntimeEstimates.get(taskAttempt); } } if (estimateVarianceContainer == null) { attemptRuntimeEstimateVariances.putIfAbsent(taskAttempt, new AtomicLong()); estimateVarianceContainer = attemptRuntimeEstimateVariances.get(taskAttempt); } long estimate = -1; long varianceEstimate = -1; // This code assumes that we'll never consider starting a third // speculative task attempt if two are already running for this task if (start > 0 && timestamp > start) { estimate = (long) ((timestamp - start) / Math.max(0.0001, status.progress)); varianceEstimate = (long) (estimate * status.progress / 10); } if (estimateContainer != null) { estimateContainer.set(estimate); } if (estimateVarianceContainer != null) { estimateVarianceContainer.set(varianceEstimate); } } } private long storedPerAttemptValue (Map<TaskAttempt, AtomicLong> data, TaskAttemptId attemptID) { TaskId taskID = attemptID.getTaskId(); JobId jobID = taskID.getJobId(); Job job = context.getJob(jobID); Task task = job.getTask(taskID); if (task == null) { return -1L; } TaskAttempt taskAttempt = task.getAttempt(attemptID); if (taskAttempt == null) { return -1L; } AtomicLong estimate = data.get(taskAttempt); return estimate == null ? -1L : estimate.get(); } @Override public long estimatedRuntime(TaskAttemptId attemptID) { return storedPerAttemptValue(attemptRuntimeEstimates, attemptID); } @Override public long runtimeEstimateVariance(TaskAttemptId attemptID) { return storedPerAttemptValue(attemptRuntimeEstimateVariances, attemptID); } }
LegacyTaskRuntimeEstimator
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/SmppsComponentBuilderFactory.java
{ "start": 1398, "end": 1888 }
interface ____ { /** * SMPP (Secure) (camel-smpp) * Send and receive SMS messages using a SMSC (Short Message Service * Center). * * Category: mobile * Since: 2.2 * Maven coordinates: org.apache.camel:camel-smpp * * @return the dsl builder */ static SmppsComponentBuilder smpps() { return new SmppsComponentBuilderImpl(); } /** * Builder for the SMPP (Secure) component. */
SmppsComponentBuilderFactory
java
grpc__grpc-java
api/src/main/java/io/grpc/NameResolverRegistry.java
{ "start": 1496, "end": 6448 }
class ____ { private static final Logger logger = Logger.getLogger(NameResolverRegistry.class.getName()); private static NameResolverRegistry instance; private final NameResolver.Factory factory = new NameResolverFactory(); private static final String UNKNOWN_SCHEME = "unknown"; @GuardedBy("this") private String defaultScheme = UNKNOWN_SCHEME; @GuardedBy("this") private final LinkedHashSet<NameResolverProvider> allProviders = new LinkedHashSet<>(); /** Generated from {@code allProviders}. Is mapping from scheme key to the highest priority * {@link NameResolverProvider}. Is replaced instead of mutating. */ @GuardedBy("this") private ImmutableMap<String, NameResolverProvider> effectiveProviders = ImmutableMap.of(); public synchronized String getDefaultScheme() { return defaultScheme; } public NameResolverProvider getProviderForScheme(String scheme) { if (scheme == null) { return null; } return providers().get(scheme.toLowerCase(Locale.US)); } /** * Register a provider. * * <p>If the provider's {@link NameResolverProvider#isAvailable isAvailable()} returns * {@code false}, this method will throw {@link IllegalArgumentException}. * * <p>Providers will be used in priority order. In case of ties, providers are used in * registration order. */ public synchronized void register(NameResolverProvider provider) { addProvider(provider); refreshProviders(); } private synchronized void addProvider(NameResolverProvider provider) { checkArgument(provider.isAvailable(), "isAvailable() returned false"); allProviders.add(provider); } /** * Deregisters a provider. No-op if the provider is not in the registry. * * @param provider the provider that was added to the register via {@link #register}. */ public synchronized void deregister(NameResolverProvider provider) { allProviders.remove(provider); refreshProviders(); } private synchronized void refreshProviders() { Map<String, NameResolverProvider> refreshedProviders = new HashMap<>(); int maxPriority = Integer.MIN_VALUE; String refreshedDefaultScheme = UNKNOWN_SCHEME; // We prefer first-registered providers for (NameResolverProvider provider : allProviders) { String scheme = provider.getScheme(); NameResolverProvider existing = refreshedProviders.get(scheme); if (existing == null || existing.priority() < provider.priority()) { refreshedProviders.put(scheme, provider); } if (maxPriority < provider.priority()) { maxPriority = provider.priority(); refreshedDefaultScheme = provider.getScheme(); } } effectiveProviders = ImmutableMap.copyOf(refreshedProviders); defaultScheme = refreshedDefaultScheme; } /** * Returns the default registry that loads providers via the Java service loader mechanism. */ public static synchronized NameResolverRegistry getDefaultRegistry() { if (instance == null) { List<NameResolverProvider> providerList = ServiceProviders.loadAll( NameResolverProvider.class, getHardCodedClasses(), NameResolverProvider.class.getClassLoader(), new NameResolverPriorityAccessor()); if (providerList.isEmpty()) { logger.warning("No NameResolverProviders found via ServiceLoader, including for DNS. This " + "is probably due to a broken build. If using ProGuard, check your configuration"); } instance = new NameResolverRegistry(); for (NameResolverProvider provider : providerList) { logger.fine("Service loader found " + provider); instance.addProvider(provider); } instance.refreshProviders(); } return instance; } /** * Returns effective providers map from scheme to the highest priority NameResolverProvider of * that scheme. */ @VisibleForTesting synchronized Map<String, NameResolverProvider> providers() { return effectiveProviders; } public NameResolver.Factory asFactory() { return factory; } @VisibleForTesting static List<Class<?>> getHardCodedClasses() { // Class.forName(String) is used to remove the need for ProGuard configuration. Note that // ProGuard does not detect usages of Class.forName(String, boolean, ClassLoader): // https://sourceforge.net/p/proguard/bugs/418/ ArrayList<Class<?>> list = new ArrayList<>(); try { list.add(Class.forName("io.grpc.internal.DnsNameResolverProvider")); } catch (ClassNotFoundException e) { logger.log(Level.FINE, "Unable to find DNS NameResolver", e); } try { list.add(Class.forName("io.grpc.binder.internal.IntentNameResolverProvider")); } catch (ClassNotFoundException e) { logger.log(Level.FINE, "Unable to find IntentNameResolverProvider", e); } return Collections.unmodifiableList(list); } private final
NameResolverRegistry
java
grpc__grpc-java
services/src/generated/test/grpc/io/grpc/reflection/testing/DynamicServiceGrpc.java
{ "start": 5225, "end": 5368 }
class ____ the server implementation of the service DynamicService. * <pre> * A DynamicService * </pre> */ public static abstract
for
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/filter/WeightCalculatorWebFilterTests.java
{ "start": 5692, "end": 6028 }
class ____ extends WeightCalculatorWebFilter { private WeightConfig weightConfig; TestWeightCalculatorWebFilter() { super(null, new ConfigurationService(null, () -> null, () -> null)); } @Override void addWeightConfig(WeightConfig weightConfig) { this.weightConfig = weightConfig; } } }
TestWeightCalculatorWebFilter
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/aggregate/JsonObjectAggFunction.java
{ "start": 2457, "end": 6387 }
class ____ extends BuiltInAggregateFunction<String, JsonObjectAggFunction.Accumulator> { private static final long serialVersionUID = 1L; private static final StringData NULL_STRING_DATA = StringData.fromBytes(new byte[] {}); private static final NullNode NULL_NODE = getNodeFactory().nullNode(); private final transient List<DataType> argumentTypes; private final boolean skipNulls; public JsonObjectAggFunction(LogicalType[] argumentTypes, boolean skipNulls) { this.argumentTypes = Arrays.stream(argumentTypes) .map(DataTypeUtils::toInternalDataType) .collect(Collectors.toList()); this.skipNulls = skipNulls; } @Override public List<DataType> getArgumentDataTypes() { return argumentTypes; } @Override public DataType getOutputDataType() { return DataTypes.STRING(); } @Override public DataType getAccumulatorDataType() { return DataTypes.STRUCTURED( Accumulator.class, DataTypes.FIELD( "map", MapView.newMapViewDataType( DataTypes.STRING().notNull().toInternal(), DataTypes.STRING().toInternal()))); } @Override public Accumulator createAccumulator() { return new Accumulator(); } public void resetAccumulator(Accumulator acc) { acc.map.clear(); } public void accumulate(Accumulator acc, StringData keyData, @Nullable StringData valueData) throws Exception { assertKeyNotPresent(acc, keyData); if (valueData == null) { if (!skipNulls) { // We cannot use null for StringData here, since it's not supported by the // StringDataSerializer, instead use a StringData with an empty byte[] acc.map.put(keyData, NULL_STRING_DATA); } } else { acc.map.put(keyData, valueData); } } public void retract(Accumulator acc, StringData keyData, @Nullable StringData valueData) throws Exception { acc.map.remove(keyData); } public void merge(Accumulator acc, Iterable<Accumulator> others) throws Exception { for (final Accumulator other : others) { for (final StringData key : other.map.keys()) { assertKeyNotPresent(acc, key); acc.map.put(key, other.map.get(key)); } } } @Override public String getValue(Accumulator acc) { final ObjectNode rootNode = createObjectNode(); try { for (final StringData key : acc.map.keys()) { final StringData value = acc.map.get(key); final JsonNode valueNode = value.toBytes().length == 0 ? NULL_NODE : getNodeFactory().rawValueNode(new RawValue(value.toString())); rootNode.set(key.toString(), valueNode); } } catch (Exception e) { throw new TableException("The accumulator state could not be serialized.", e); } return serializeJson(rootNode); } private static void assertKeyNotPresent(Accumulator acc, StringData keyData) throws Exception { if (acc.map.contains(keyData)) { throw new TableException( String.format( "Key '%s' is already present. Duplicate keys are not allowed in JSON_OBJECTAGG. Please ensure that keys are unique.", keyData.toString())); } } // --------------------------------------------------------------------------------------------- /** Accumulator for {@link JsonObjectAggFunction}. */ public static
JsonObjectAggFunction
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/Issue1407.java
{ "start": 194, "end": 1767 }
class ____ extends TestCase { public void test_for_issue() throws Exception { final String key = "k"; final IdentityHashMap map = new IdentityHashMap(2); final Random ran = new Random(); new Thread() { public void run() { while(true) { String kk = (key + ran.nextInt(2)); if (map.get(kk) != null) { // System.out.println("\tskip_a " + kk); continue; } // synchronized(map) { map.put(kk, kk); System.out.println("\tput_a " + kk); // } Object val = map.get(kk); if(val == null) { System.err.println("err_a : " + kk); } } } }.start(); new Thread() { public void run() { while(true) { String kk = (key + ran.nextInt(2)); // synchronized(map) { if (map.get(kk) != null) { // System.out.println("\tskip_b " + kk); continue; } map.put(kk, kk); System.out.println("\tput_b " + kk); // } Object val = map.get(kk); if(val == null) { System.err.println("err_b : " + kk); } } } }.start(); Thread.sleep(1000 * 1000); } }
Issue1407
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/factories/TestProcedureCatalogFactory.java
{ "start": 10284, "end": 10899 }
class ____ implements Procedure { public Row[] call(ProcedureContext procedureContext) throws Exception { StreamExecutionEnvironment env = procedureContext.getExecutionEnvironment(); Configuration config = (Configuration) env.getConfiguration(); List<Row> rows = new ArrayList<>(); config.toMap() .forEach( (k, v) -> { rows.add(Row.of(k, v)); }); return rows.toArray(new Row[0]); } } /** A simple pojo
EnvironmentConfProcedure
java
google__error-prone
core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTest.java
{ "start": 66524, "end": 67115 }
class ____ { CoinductiveWithMethod f; abstract CoinductiveWithMethod foo(); } } """) .doTest(); } @Test public void annotatedAtGenericTypeUse() { compilationHelper .addSourceLines( "AnnotatedAtGenericTypeUseTest.java", """ package com.google.errorprone.dataflow.nullnesspropagation; import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker; import org.checkerframework.checker.nullness.qual.Nullable; import org.checkerframework.checker.nullness.qual.NonNull; public
CoinductiveWithMethod
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/mutationquery/MutationQueriesWhereAndFilterTest.java
{ "start": 7348, "end": 7795 }
class ____ { @Id private Long id; @Column( name = "where_deleted" ) private boolean whereDeleted; @Column( name = "filter_deleted" ) private boolean filterDeleted; @ManyToMany @JoinTable( name = "users_roles", joinColumns = @JoinColumn( name = "user_id" ), inverseJoinColumns = @JoinColumn( name = "role_id" ) ) private List<RoleEntity> roles; } @Entity( name = "TablePerClassUser" ) public static
TablePerClassBase
java
apache__avro
lang/java/thrift/src/test/java/org/apache/avro/thrift/test/Foo.java
{ "start": 11558, "end": 12245 }
class ____<I extends Iface> extends org.apache.thrift.ProcessFunction<I, add_args> { public add() { super("add"); } public add_args getEmptyArgsInstance() { return new add_args(); } protected boolean isOneway() { return false; } @Override protected boolean rethrowUnhandledExceptions() { return false; } public add_result getResult(I iface, add_args args) throws org.apache.thrift.TException { add_result result = new add_result(); result.success = iface.add(args.num1, args.num2); result.setSuccessIsSet(true); return result; } } public static
add
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/main/java/org/apache/hadoop/mapreduce/jobhistory/JobHistoryEventHandler.java
{ "start": 65863, "end": 72779 }
class ____ { private Path historyFile; private Path confFile; private EventWriter writer; JobIndexInfo jobIndexInfo; JobSummary jobSummary; Timer flushTimer; FlushTimerTask flushTimerTask; private boolean isTimerShutDown = false; private String forcedJobStateOnShutDown; MetaInfo(Path historyFile, Path conf, EventWriter writer, String user, String jobName, JobId jobId, String forcedJobStateOnShutDown, String queueName) { this.historyFile = historyFile; this.confFile = conf; this.writer = writer; this.jobIndexInfo = new JobIndexInfo(-1, -1, user, jobName, jobId, -1, -1, null, queueName); this.jobSummary = new JobSummary(); this.flushTimer = new Timer("FlushTimer", true); this.forcedJobStateOnShutDown = forcedJobStateOnShutDown; } Path getHistoryFile() { return historyFile; } Path getConfFile() { return confFile; } JobIndexInfo getJobIndexInfo() { return jobIndexInfo; } JobSummary getJobSummary() { return jobSummary; } boolean isWriterActive() { return writer != null; } boolean isTimerShutDown() { return isTimerShutDown; } String getForcedJobStateOnShutDown() { return forcedJobStateOnShutDown; } @Override public String toString() { return "Job MetaInfo for "+ jobSummary.getJobId() + " history file " + historyFile; } void closeWriter() throws IOException { LOG.debug("Closing Writer"); synchronized (lock) { if (writer != null) { writer.close(); } writer = null; } } void writeEvent(HistoryEvent event) throws IOException { LOG.debug("Writing event"); synchronized (lock) { if (writer != null) { writer.write(event); processEventForFlush(event); maybeFlush(event); } } } void processEventForFlush(HistoryEvent historyEvent) throws IOException { if (EnumSet.of(EventType.MAP_ATTEMPT_FINISHED, EventType.MAP_ATTEMPT_FAILED, EventType.MAP_ATTEMPT_KILLED, EventType.REDUCE_ATTEMPT_FINISHED, EventType.REDUCE_ATTEMPT_FAILED, EventType.REDUCE_ATTEMPT_KILLED, EventType.TASK_FINISHED, EventType.TASK_FAILED, EventType.JOB_FINISHED, EventType.JOB_FAILED, EventType.JOB_KILLED).contains(historyEvent.getEventType())) { numUnflushedCompletionEvents++; if (!isTimerActive) { resetFlushTimer(); if (!isTimerShutDown) { flushTimerTask = new FlushTimerTask(this); flushTimer.schedule(flushTimerTask, flushTimeout); isTimerActive = true; } } } } void resetFlushTimer() throws IOException { if (flushTimerTask != null) { IOException exception = flushTimerTask.getException(); flushTimerTask.stop(); if (exception != null) { throw exception; } flushTimerTask = null; } isTimerActive = false; } void maybeFlush(HistoryEvent historyEvent) throws IOException { if ((eventQueue.size() < minQueueSizeForBatchingFlushes && numUnflushedCompletionEvents > 0) || numUnflushedCompletionEvents >= maxUnflushedCompletionEvents || isJobCompletionEvent(historyEvent)) { this.flush(); } } void flush() throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Flushing " + toString()); } synchronized (lock) { if (numUnflushedCompletionEvents != 0) { // skipped timer cancel. writer.flush(); numUnflushedCompletionEvents = 0; resetFlushTimer(); } } } void shutDownTimer() throws IOException { if (LOG.isDebugEnabled()) { LOG.debug("Shutting down timer "+ toString()); } synchronized (lock) { isTimerShutDown = true; flushTimer.cancel(); if (flushTimerTask != null && flushTimerTask.getException() != null) { throw flushTimerTask.getException(); } } } } protected void moveTmpToDone(Path tmpPath) throws IOException { if (tmpPath != null) { String tmpFileName = tmpPath.getName(); String fileName = getFileNameFromTmpFN(tmpFileName); Path path = new Path(tmpPath.getParent(), fileName); doneDirFS.rename(tmpPath, path); LOG.info("Moved tmp to done: " + tmpPath + " to " + path); } } // TODO If the FS objects are the same, this should be a rename instead of a // copy. protected boolean moveToDoneNow(Path fromPath, Path toPath) throws IOException { boolean success = false; // check if path exists, in case of retries it may not exist if (stagingDirFS.exists(fromPath)) { LOG.info("Copying " + fromPath.toString() + " to " + toPath.toString()); // TODO temporarily removing the existing dst doneDirFS.delete(toPath, true); boolean copied = FileUtil.copy(stagingDirFS, fromPath, doneDirFS, toPath, false, getConfig()); doneDirFS.setPermission(toPath, new FsPermission(JobHistoryUtils. getConfiguredHistoryIntermediateUserDoneDirPermissions( getConfig()))); if (copied) { LOG.info("Copied from: " + fromPath.toString() + " to done location: " + toPath.toString()); success = true; } else { LOG.info("Copy failed from: " + fromPath.toString() + " to done location: " + toPath.toString()); } } return success; } private String getTempFileName(String srcFile) { return srcFile + "_tmp"; } private String getFileNameFromTmpFN(String tmpFileName) { //TODO. Some error checking here. return tmpFileName.substring(0, tmpFileName.length()-4); } public void setForcejobCompletion(boolean forceJobCompletion) { this.forceJobCompletion = forceJobCompletion; LOG.info("JobHistoryEventHandler notified that forceJobCompletion is " + forceJobCompletion); } private String createJobStateForJobUnsuccessfulCompletionEvent( String forcedJobStateOnShutDown) { if (forcedJobStateOnShutDown == null || forcedJobStateOnShutDown .isEmpty()) { return JobState.KILLED.toString(); } else if (forcedJobStateOnShutDown.equals( JobStateInternal.ERROR.toString()) || forcedJobStateOnShutDown.equals(JobStateInternal.FAILED.toString())) { return JobState.FAILED.toString(); } else if (forcedJobStateOnShutDown.equals(JobStateInternal.SUCCEEDED .toString())) { return JobState.SUCCEEDED.toString(); } return JobState.KILLED.toString(); } @VisibleForTesting boolean getFlushTimerStatus() { return isTimerActive; } private final
MetaInfo
java
apache__flink
flink-kubernetes/src/main/java/org/apache/flink/kubernetes/kubeclient/resources/KubernetesSharedInformer.java
{ "start": 6188, "end": 8557 }
class ____ { private final String resourceKey; private final Map<String, WatchCallback<R>> callbacks = new HashMap<>(); private T resource; private EventHandler(String resourceKey) { this.resourceKey = resourceKey; this.resource = sharedIndexInformer.getIndexer().getByKey(resourceKey); } private void addWatch(String id, WatchCallback<R> callback) { log.info("Starting to watch for {}, watching id:{}", resourceKey, id); callbacks.put(id, callback); if (resource != null) { final List<R> resources = wrapEvent(resource); callback.run(h -> h.onAdded(resources)); } } private boolean removeWatch(String id) { callbacks.remove(id); log.info("Stopped to watch for {}, watching id:{}", resourceKey, id); return callbacks.isEmpty(); } private void handleResourceEvent() { T newResource = sharedIndexInformer.getIndexer().getByKey(resourceKey); T oldResource = this.resource; if (newResource == null) { if (oldResource != null) { onDeleted(oldResource); } } else { if (oldResource == null) { onAdded(newResource); } else if (!oldResource .getMetadata() .getResourceVersion() .equals(newResource.getMetadata().getResourceVersion())) { onModified(newResource); } } this.resource = newResource; } private void onAdded(T obj) { this.callbacks.forEach((id, callback) -> callback.run(h -> h.onAdded(wrapEvent(obj)))); } private void onModified(T obj) { this.callbacks.forEach( (id, callback) -> callback.run(h -> h.onModified(wrapEvent(obj)))); } private void onDeleted(T obj) { this.callbacks.forEach( (id, callback) -> callback.run(h -> h.onDeleted(wrapEvent(obj)))); } private List<R> wrapEvent(T obj) { return Collections.singletonList(eventWrapper.apply(obj)); } } private static final
EventHandler
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnicodeEscapeTest.java
{ "start": 3764, "end": 4107 }
class ____ { private static final String FOO = "\\\\u0020"; } """) .doTest(); } @Test public void everythingObfuscated() { refactoring .addInputLines("A.java", "\\u0063\\u006c\\u0061\\u0073\\u0073\\u0020\\u0041\\u007b\\u007d") .addOutputLines( "A.java", """
Test
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/rest/messages/JobExceptionsInfoWithHistoryTest.java
{ "start": 1487, "end": 2683 }
class ____ extends RestResponseMarshallingTestBase<JobExceptionsInfoWithHistory> { @Override protected Class<JobExceptionsInfoWithHistory> getTestResponseClass() { return JobExceptionsInfoWithHistory.class; } @Override protected JobExceptionsInfoWithHistory getTestResponseInstance() throws Exception { return new JobExceptionsInfoWithHistory( new JobExceptionsInfoWithHistory.JobExceptionHistory( Collections.emptyList(), false)); } /** * {@code taskName} and {@code location} should not be exposed if not set. * * @throws JsonProcessingException is not expected to be thrown */ @Test void testNullFieldsNotSet() throws JsonProcessingException { ObjectMapper objMapper = RestMapperUtils.getStrictObjectMapper(); String json = objMapper.writeValueAsString( new JobExceptionsInfoWithHistory.ExceptionInfo( "exception name", "stacktrace", 0L)); assertThat(json).doesNotContain("taskName"); assertThat(json).doesNotContain("location"); } }
JobExceptionsInfoWithHistoryTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/xml/ejb3/Ejb3XmlTestCase.java
{ "start": 1937, "end": 4880 }
class ____ { private BootstrapContextImpl bootstrapContext; protected Ejb3XmlTestCase() { } @BeforeEach public void init() { bootstrapContext = new BootstrapContextImpl(); } @AfterEach public void destroy() { bootstrapContext.close(); } protected MemberDetails getAttributeMember(Class<?> entityClass, String fieldName, String xmlResourceName) { final ClassDetails classDetails = getClassDetails( entityClass, xmlResourceName ); final FieldDetails fieldByName = classDetails.findFieldByName( fieldName ); if ( !fieldByName.getDirectAnnotationUsages().isEmpty() ) { if ( !fieldByName.hasDirectAnnotationUsage( Transient.class ) ) { return fieldByName; } } // look for the getter for ( MethodDetails method : classDetails.getMethods() ) { if ( method.getMethodKind() == MethodDetails.MethodKind.GETTER && fieldName.equals( method.resolveAttributeName() ) ) { if ( !method.hasDirectAnnotationUsage( Transient.class ) ) { return method; } } } throw new IllegalStateException( "Unable to locate persistent attribute : " + fieldName ); } private ModelsContext sourceModelContext; protected ClassDetails getClassDetails(Class<?> entityClass, String xmlResourceName) { final ManagedResources managedResources = new AdditionalManagedResourcesImpl.Builder().addLoadedClasses( entityClass ) .addXmlMappings( "org/hibernate/orm/test/annotations/xml/ejb3/" + xmlResourceName ) .build(); final PersistenceUnitMetadataImpl persistenceUnitMetadata = new PersistenceUnitMetadataImpl(); final XmlPreProcessingResult xmlPreProcessingResult = XmlPreProcessor.preProcessXmlResources( managedResources, persistenceUnitMetadata ); final ModelsContext modelBuildingContext = new BasicModelsContextImpl( SIMPLE_CLASS_LOADING, false, (contributions, inFlightContext) -> { OrmAnnotationHelper.forEachOrmAnnotation( contributions::registerAnnotation ); } ); final BootstrapContext bootstrapContext = new BootstrapContextImpl(); final GlobalRegistrationsImpl globalRegistrations = new GlobalRegistrationsImpl( modelBuildingContext, bootstrapContext ); final DomainModelCategorizationCollector modelCategorizationCollector = new DomainModelCategorizationCollector( globalRegistrations, modelBuildingContext ); final RootMappingDefaults rootMappingDefaults = new RootMappingDefaults( new MetadataBuilderImpl.MappingDefaultsImpl( new StandardServiceRegistryBuilder().build() ), persistenceUnitMetadata ); final XmlProcessingResult xmlProcessingResult = XmlProcessor.processXml( xmlPreProcessingResult, persistenceUnitMetadata, modelCategorizationCollector::apply, modelBuildingContext, bootstrapContext, rootMappingDefaults ); xmlProcessingResult.apply(); return modelBuildingContext.getClassDetailsRegistry().resolveClassDetails( entityClass.getName() ); } }
Ejb3XmlTestCase
java
netty__netty
transport/src/test/java/io/netty/channel/CompleteChannelFutureTest.java
{ "start": 2410, "end": 3304 }
class ____ extends CompleteChannelFuture { CompleteChannelFutureImpl(Channel channel) { super(channel, null); } @Override public Throwable cause() { throw new UnsupportedOperationException("cause is not supported for " + getClass().getName()); } @Override public boolean isSuccess() { throw new UnsupportedOperationException("isSuccess is not supported for " + getClass().getName()); } @Override public ChannelFuture sync() { throw new UnsupportedOperationException("sync is not supported for " + getClass().getName()); } @Override public ChannelFuture syncUninterruptibly() { throw new UnsupportedOperationException("syncUninterruptibly is not supported for " + getClass().getName()); } } }
CompleteChannelFutureImpl
java
spring-projects__spring-framework
spring-context-support/src/main/java/org/springframework/scheduling/quartz/MethodInvokingJobDetailFactoryBean.java
{ "start": 8191, "end": 9709 }
class ____ extends QuartzJobBean { protected static final Log logger = LogFactory.getLog(MethodInvokingJob.class); private @Nullable MethodInvoker methodInvoker; /** * Set the MethodInvoker to use. */ public void setMethodInvoker(MethodInvoker methodInvoker) { this.methodInvoker = methodInvoker; } /** * Invoke the method via the MethodInvoker. */ @Override protected void executeInternal(JobExecutionContext context) throws JobExecutionException { Assert.state(this.methodInvoker != null, "No MethodInvoker set"); try { context.setResult(this.methodInvoker.invoke()); } catch (InvocationTargetException ex) { if (ex.getTargetException() instanceof JobExecutionException jobExecutionException) { // -> JobExecutionException, to be logged at info level by Quartz throw jobExecutionException; } else { // -> "unhandled exception", to be logged at error level by Quartz throw new JobMethodInvocationFailedException(this.methodInvoker, ex.getTargetException()); } } catch (Exception ex) { // -> "unhandled exception", to be logged at error level by Quartz throw new JobMethodInvocationFailedException(this.methodInvoker, ex); } } } /** * Extension of the MethodInvokingJob, implementing the StatefulJob interface. * Quartz checks whether jobs are stateful and if so, * won't let jobs interfere with each other. */ @PersistJobDataAfterExecution @DisallowConcurrentExecution public static
MethodInvokingJob
java
elastic__elasticsearch
build-tools-internal/src/test/java/org/elasticsearch/gradle/internal/test/rest/transform/length/ReplaceKeyInLengthTests.java
{ "start": 838, "end": 1578 }
class ____ extends TransformTests { @Test public void testLengthKeyChange() throws Exception { String test_original = "/rest/transform/length/length_replace_original.yml"; List<ObjectNode> tests = getTests(test_original); String test_transformed = "/rest/transform/length/length_replace_transformed_key.yml"; List<ObjectNode> expectedTransformation = getTests(test_transformed); List<ObjectNode> transformedTests = transformTests( tests, Collections.singletonList(new ReplaceKeyInLength("key.in_length_to_replace", "key.in_length_replaced", null)) ); AssertObjectNodes.areEqual(transformedTests, expectedTransformation); } }
ReplaceKeyInLengthTests
java
quarkusio__quarkus
extensions/panache/mongodb-panache-common/runtime/src/main/java/io/quarkus/mongodb/panache/common/MongoEntity.java
{ "start": 385, "end": 486 }
interface ____ { /** * The name of the collection (if not set the name of the entity
MongoEntity
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/runtime/AbstractBooleanScriptFieldQuery.java
{ "start": 799, "end": 1796 }
class ____ extends AbstractScriptFieldQuery<BooleanFieldScript> { AbstractBooleanScriptFieldQuery(Script script, BooleanFieldScript.LeafFactory leafFactory, String fieldName) { super(script, fieldName, leafFactory::newInstance); } @Override protected final boolean matches(BooleanFieldScript scriptContext, int docId) { scriptContext.runForDoc(docId); return matches(scriptContext.trues(), scriptContext.falses()); } /** * Does the value match this query? * @param trues the number of true values returned by the script * @param falses the number of false values returned by the script */ protected abstract boolean matches(int trues, int falses); @Override public final void visit(QueryVisitor visitor) { // No subclasses contain any Terms because those have to be strings. if (visitor.acceptField(fieldName())) { visitor.visitLeaf(this); } } }
AbstractBooleanScriptFieldQuery
java
elastic__elasticsearch
x-pack/plugin/spatial/src/test/java/org/elasticsearch/xpack/spatial/search/aggregations/bucket/geogrid/GeoTileTilerTests.java
{ "start": 1927, "end": 13741 }
class ____ extends GeoGridTilerTestCase<GeoTileGridTiler> { @Override protected GeoTileGridTiler getGridTiler(GeoBoundingBox bbox, int precision) { return GeoTileGridTiler.makeGridTiler(precision, bbox); } @Override protected Rectangle getCell(double lon, double lat, int precision) { return GeoTileUtils.toBoundingBox(GeoTileUtils.longEncode(lon, lat, precision)); } @Override protected int maxPrecision() { return GeoTileUtils.MAX_ZOOM; } @Override protected long getCellsForDiffPrecision(int precisionDiff) { return (1L << precisionDiff) * (1L << precisionDiff); } @Override protected void assertSetValuesBruteAndRecursive(Geometry geometry) throws Exception { int precision = randomIntBetween(1, 4); GeoTileGridTiler tiler = getGridTiler(precision); geometry = GeometryNormalizer.apply(Orientation.CCW, geometry); GeoShapeValues.GeoShapeValue value = geoShapeValue(geometry); GeoShapeCellValues recursiveValues = new GeoShapeCellValues(null, tiler, NOOP_BREAKER); int recursiveCount; { recursiveCount = tiler.setValuesByRasterization(0, 0, 0, recursiveValues, 0, value); } GeoShapeCellValues bruteForceValues = new GeoShapeCellValues(null, tiler, NOOP_BREAKER); int bruteForceCount; { final int tiles = 1 << precision; GeoShapeValues.BoundingBox bounds = value.boundingBox(); int minXTile = GeoTileUtils.getXTile(bounds.minX(), tiles); int minYTile = GeoTileUtils.getYTile(bounds.maxY(), tiles); int maxXTile = GeoTileUtils.getXTile(bounds.maxX(), tiles); int maxYTile = GeoTileUtils.getYTile(bounds.minY(), tiles); bruteForceCount = tiler.setValuesByBruteForceScan(bruteForceValues, value, minXTile, minYTile, maxXTile, maxYTile); } assertThat(geometry.toString(), recursiveCount, equalTo(bruteForceCount)); long[] recursive = Arrays.copyOf(recursiveValues.getValues(), recursiveCount); long[] bruteForce = Arrays.copyOf(bruteForceValues.getValues(), bruteForceCount); Arrays.sort(recursive); Arrays.sort(bruteForce); assertArrayEquals(geometry.toString(), recursive, bruteForce); } @Override protected int expectedBuckets(GeoShapeValues.GeoShapeValue geoValue, int precision, GeoBoundingBox bbox) throws Exception { GeoShapeValues.BoundingBox bounds = geoValue.boundingBox(); int count = 0; if (bounds.bottom > GeoTileUtils.NORMALIZED_LATITUDE_MASK || bounds.top < GeoTileUtils.NORMALIZED_NEGATIVE_LATITUDE_MASK) { return 0; } if (bbox != null) { if (bbox.bottom() > GeoTileUtils.NORMALIZED_LATITUDE_MASK || bbox.top() < GeoTileUtils.NORMALIZED_NEGATIVE_LATITUDE_MASK) { return 0; } } if (precision == 0) { return 1; } final int tiles = 1 << precision; int minYTile = GeoTileUtils.getYTile(bounds.maxY(), tiles); int maxYTile = GeoTileUtils.getYTile(bounds.minY(), tiles); if ((bounds.posLeft >= 0 && bounds.posRight >= 0) && (bounds.negLeft < 0 && bounds.negRight < 0)) { // box one int minXTileNeg = GeoTileUtils.getXTile(bounds.negLeft, tiles); int maxXTileNeg = GeoTileUtils.getXTile(bounds.negRight, tiles); for (int x = minXTileNeg; x <= maxXTileNeg; x++) { for (int y = minYTile; y <= maxYTile; y++) { Rectangle r = GeoTileUtils.toBoundingBox(x, y, precision); if (tileIntersectsBounds(x, y, precision, bbox) && intersects(x, y, precision, geoValue)) { count += 1; } } } // box two int minXTilePos = GeoTileUtils.getXTile(bounds.posLeft, tiles); if (minXTilePos > maxXTileNeg + 1) { minXTilePos -= 1; } int maxXTilePos = GeoTileUtils.getXTile(bounds.posRight, tiles); for (int x = minXTilePos; x <= maxXTilePos; x++) { for (int y = minYTile; y <= maxYTile; y++) { if (tileIntersectsBounds(x, y, precision, bbox) && intersects(x, y, precision, geoValue)) { count += 1; } } } return count; } else { int minXTile = GeoTileUtils.getXTile(bounds.minX(), tiles); int maxXTile = GeoTileUtils.getXTile(bounds.maxX(), tiles); if (minXTile == maxXTile && minYTile == maxYTile) { return tileIntersectsBounds(minXTile, minYTile, precision, bbox) ? 1 : 0; } for (int x = minXTile; x <= maxXTile; x++) { for (int y = minYTile; y <= maxYTile; y++) { Rectangle r = GeoTileUtils.toBoundingBox(x, y, precision); if (tileIntersectsBounds(x, y, precision, bbox) && intersects(x, y, precision, geoValue)) { count += 1; } } } return count; } } private boolean intersects(int x, int y, int precision, GeoShapeValues.GeoShapeValue geoValue) throws IOException { Rectangle r = GeoGridQueryBuilder.getQueryTile(stringEncode(longEncodeTiles(precision, x, y))); return geoValue.relate( GeoEncodingUtils.encodeLongitude(r.getMinLon()), GeoEncodingUtils.encodeLongitude(r.getMaxLon()), GeoEncodingUtils.encodeLatitude(r.getMinLat()), GeoEncodingUtils.encodeLatitude(r.getMaxLat()) ) != GeoRelation.QUERY_DISJOINT; } private boolean tileIntersectsBounds(int x, int y, int precision, GeoBoundingBox bbox) { if (bbox == null) { return true; } GeoTileBoundedPredicate predicate = new GeoTileBoundedPredicate(precision, bbox); return predicate.validTile(x, y, precision); } public void testGeoTile() throws Exception { double x = randomDouble(); double y = randomDouble(); int precision = randomIntBetween(0, GeoTileUtils.MAX_ZOOM); assertThat(getGridTiler(precision).encode(x, y), equalTo(GeoTileUtils.longEncode(x, y, precision))); // create rectangle within tile and check bound counts Rectangle tile = GeoTileUtils.toBoundingBox(1309, 3166, 13); Rectangle shapeRectangle = new Rectangle( tile.getMinX() + 0.00001, tile.getMaxX() - 0.00001, tile.getMaxY() - 0.00001, tile.getMinY() + 0.00001 ); GeoShapeValues.GeoShapeValue value = geoShapeValue(shapeRectangle); // test shape within tile bounds { GeoShapeCellValues values = new GeoShapeCellValues(makeGeoShapeValues(value), getGridTiler(13), NOOP_BREAKER); assertTrue(values.advanceExact(0)); assertThat(values.docValueCount(), equalTo(1)); } { GeoShapeCellValues values = new GeoShapeCellValues(makeGeoShapeValues(value), getGridTiler(14), NOOP_BREAKER); assertTrue(values.advanceExact(0)); assertThat(values.docValueCount(), equalTo(4)); } { GeoShapeCellValues values = new GeoShapeCellValues(makeGeoShapeValues(value), getGridTiler(15), NOOP_BREAKER); assertTrue(values.advanceExact(0)); assertThat(values.docValueCount(), equalTo(16)); } } public void testMaxCellsBoundedWithAnotherCell() { double lon = GeoTestUtil.nextLongitude(); double lat = GeoTestUtil.nextLatitude(); for (int i = 0; i < maxPrecision(); i++) { Rectangle tile = getCell(lon, lat, i); GeoBoundingBox boundingBox = new GeoBoundingBox( new GeoPoint(tile.getMaxLat(), tile.getMinLon()), new GeoPoint(tile.getMinLat(), tile.getMaxLon()) ); int otherPrecision = randomIntBetween(i, maxPrecision()); GeoGridTiler tiler = getGridTiler(boundingBox, otherPrecision); assertThat(tiler.getMaxCells(), equalTo(getCellsForDiffPrecision(otherPrecision - i))); } } public void testBoundGridOutOfRange() throws Exception { GeoBoundingBox boundingBox = new GeoBoundingBox(new GeoPoint(90, -180), new GeoPoint(89, 180)); double lon = GeoTestUtil.nextLongitude(); double lat = GeoTestUtil.nextLatitude(); GeoShapeValues.GeoShapeValue value = geoShapeValue(new Point(lon, lat)); for (int i = 0; i < maxPrecision(); i++) { GeoShapeCellValues values = new GeoShapeCellValues(makeGeoShapeValues(value), getGridTiler(boundingBox, i), NOOP_BREAKER); assertTrue(values.advanceExact(0)); int numTiles = values.docValueCount(); assertThat(numTiles, equalTo(0)); } } public void testTilerMatchPoint() throws Exception { int precision = randomIntBetween(0, 4); Point originalPoint = GeometryTestUtils.randomPoint(false); int xTile = GeoTileUtils.getXTile(originalPoint.getX(), 1 << precision); int yTile = GeoTileUtils.getYTile(originalPoint.getY(), 1 << precision); Rectangle bbox = GeoTileUtils.toBoundingBox(xTile, yTile, precision); Point[] pointCorners = new Point[] { // tile corners new Point(bbox.getMinX(), bbox.getMinY()), new Point(bbox.getMinX(), bbox.getMaxY()), new Point(bbox.getMaxX(), bbox.getMinY()), new Point(bbox.getMaxX(), bbox.getMaxY()), // tile edge midpoints new Point(bbox.getMinX(), (bbox.getMinY() + bbox.getMaxY()) / 2), new Point(bbox.getMaxX(), (bbox.getMinY() + bbox.getMaxY()) / 2), new Point((bbox.getMinX() + bbox.getMaxX()) / 2, bbox.getMinY()), new Point((bbox.getMinX() + bbox.getMaxX()) / 2, bbox.getMaxY()), }; for (Point point : pointCorners) { if (point.getX() == GeoUtils.MAX_LON || point.getY() == -LATITUDE_MASK) { continue; } GeoShapeValues.GeoShapeValue value = geoShapeValue(point); GeoShapeCellValues unboundedCellValues = new GeoShapeCellValues( makeGeoShapeValues(value), getGridTiler(precision), NOOP_BREAKER ); assertTrue(unboundedCellValues.advanceExact(0)); int numTiles = unboundedCellValues.docValueCount(); assertThat(numTiles, equalTo(1)); long tilerHash = unboundedCellValues.getValues()[0]; long pointHash = GeoTileUtils.longEncode(encodeDecodeLon(point.getX()), encodeDecodeLat(point.getY()), precision); assertThat(tilerHash, equalTo(pointHash)); } } public void testMultiPointOutOfBounds() throws Exception { final double maxLat = randomDoubleBetween(GeoTileUtils.NORMALIZED_LATITUDE_MASK, 90, false); final double minLat = randomDoubleBetween(-90, Math.nextDown(GeoTileUtils.NORMALIZED_NEGATIVE_LATITUDE_MASK), true); // points are out of bounds, should not generate any bucket MultiPoint points = new MultiPoint(List.of(new Point(0, maxLat), new Point(0, minLat))); final GeoShapeValues.GeoShapeValue value = geoShapeValue(points); final GeoGridTiler tiler = getGridTiler(0); final GeoShapeCellValues values = new GeoShapeCellValues(makeGeoShapeValues(value), tiler, NOOP_BREAKER); assertTrue(values.advanceExact(0)); assertThat(values.docValueCount(), equalTo(0)); } }
GeoTileTilerTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/VarCheckerTest.java
{ "start": 5961, "end": 6302 }
class ____ { public void x(@Var int y) { y++; } } """) .doTest(); } @Test public void varLocal() { compilationHelper .addSourceLines( "Test.java", """ import com.google.errorprone.annotations.Var;
Test
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/AbstractAnnotationLiteral.java
{ "start": 224, "end": 655 }
class ____ checks. There are * two typical use cases: * <ol> * <li>checking against {@code Annotation} can be replaced with checking against * {@code AbstractAnnotationLiteral}, when the caller knows that the annotation instance * is likely to come from ArC;</li> * <li>checking against some concrete annotation type can be replaced with checking * equality to {@code annotationType()}.</li> * </ol> * * <p> * Replacing
type
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/legacy/sources/LookupableTableSource.java
{ "start": 1677, "end": 2594 }
interface ____<T> extends TableSource<T> { /** * Gets the {@link TableFunction} which supports lookup one key at a time. * * @param lookupKeys the chosen field names as lookup keys, it is in the defined order */ TableFunction<T> getLookupFunction(String[] lookupKeys); /** * Gets the {@link AsyncTableFunction} which supports async lookup one key at a time. * * @param lookupKeys the chosen field names as lookup keys, it is in the defined order */ AsyncTableFunction<T> getAsyncLookupFunction(String[] lookupKeys); /** * Returns true if async lookup is enabled. * * <p>The lookup function returned by {@link #getAsyncLookupFunction(String[])} will be used if * returns true. Otherwise, the lookup function returned by {@link #getLookupFunction(String[])} * will be used. */ boolean isAsyncEnabled(); }
LookupableTableSource
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/Daemon.java
{ "start": 1583, "end": 2471 }
class ____ extends Thread { Subject startSubject; @Override public final void start() { if (!SubjectUtil.THREAD_INHERITS_SUBJECT) { startSubject = SubjectUtil.current(); } super.start(); } /** * Override this instead of run() */ public void work() { if (runnable != null) { runnable.run(); } } @Override public final void run() { if (!SubjectUtil.THREAD_INHERITS_SUBJECT) { SubjectUtil.doAs(startSubject, new PrivilegedAction<Void>() { @Override public Void run() { work(); return null; } }); } else { work(); } } { setDaemon(true); // always a daemon } /** * Provide a factory for named daemon threads, for use in ExecutorServices * constructors */ @InterfaceAudience.LimitedPrivate({ "HDFS", "MapReduce" }) public static
Daemon
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/jinaai/request/JinaAIRequest.java
{ "start": 713, "end": 1074 }
class ____ implements Request { public static void decorateWithAuthHeader(HttpPost request, JinaAIAccount account) { request.setHeader(HttpHeaders.CONTENT_TYPE, XContentType.JSON.mediaType()); request.setHeader(createAuthBearerHeader(account.apiKey())); request.setHeader(JinaAIUtils.createRequestSourceHeader()); } }
JinaAIRequest
java
google__guava
android/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java
{ "start": 3491, "end": 5056 }
interface ____ { ExampleFeature[] value() default {}; ExampleFeature[] absent() default {}; } } public void testTestFeatureEnums() { // Haha! Let's test our own test rig! assertGoodFeatureEnum(ExampleFeature.class); } public void testAddImpliedFeatures_returnsSameSetInstance() { Set<Feature<?>> features = newHashSet(FOO); assertThat(addImpliedFeatures(features)).isSameInstanceAs(features); } public void testAddImpliedFeatures_addsImpliedFeatures() { assertThat(addImpliedFeatures(newHashSet(FOO))).containsExactly(FOO); assertThat(addImpliedFeatures(newHashSet(IMPLIES_IMPLIES_FOO))) .containsExactly(IMPLIES_IMPLIES_FOO, IMPLIES_FOO, FOO); assertThat(addImpliedFeatures(newHashSet(IMPLIES_IMPLIES_FOO_AND_IMPLIES_BAR))) .containsExactly(IMPLIES_IMPLIES_FOO_AND_IMPLIES_BAR, IMPLIES_FOO, FOO, IMPLIES_BAR, BAR); } public void testImpliedFeatures_returnsNewSetInstance() { Set<Feature<?>> features = newHashSet(IMPLIES_FOO); assertThat(impliedFeatures(features)).isNotSameInstanceAs(features); } public void testImpliedFeatures_returnsImpliedFeatures() { assertThat(impliedFeatures(newHashSet(FOO))).isEmpty(); assertThat(impliedFeatures(newHashSet(IMPLIES_IMPLIES_FOO))).containsExactly(IMPLIES_FOO, FOO); assertThat(impliedFeatures(newHashSet(IMPLIES_IMPLIES_FOO_AND_IMPLIES_BAR))) .containsExactly(IMPLIES_FOO, FOO, IMPLIES_BAR, BAR); } public void testBuildTesterRequirements_class_notAnnotated() throws Exception {
NotTesterAnnotation
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/hierarchies/MockitoBeanByNameInChildContextHierarchyTests.java
{ "start": 2517, "end": 3334 }
class ____ { @MockitoBean(name = "service", contextName = "child") ExampleService service; @Autowired ExampleServiceCaller serviceCaller1; @Autowired ExampleServiceCaller serviceCaller2; @Test void test(ApplicationContext context) { ExampleService serviceInParent = context.getParent().getBean(ExampleService.class); assertIsNotMock(serviceInParent); when(service.greeting()).thenReturn("Mock 2"); assertThat(service.greeting()).isEqualTo("Mock 2"); assertThat(serviceCaller1.getService()).isSameAs(serviceInParent); assertThat(serviceCaller2.getService()).isSameAs(service); assertThat(serviceCaller1.sayGreeting()).isEqualTo("I say Service 1"); assertThat(serviceCaller2.sayGreeting()).isEqualTo("I say Mock 2"); } @Configuration static
MockitoBeanByNameInChildContextHierarchyTests
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/generated/GeneratedRecordEqualiser.java
{ "start": 1081, "end": 1476 }
class ____ extends GeneratedClass<RecordEqualiser> { private static final long serialVersionUID = 2L; @VisibleForTesting public GeneratedRecordEqualiser(String className, String code, Object[] references) { super(className, code, references, new Configuration()); } /** * Creates a GeneratedRecordEqualiser. * * @param className
GeneratedRecordEqualiser
java
quarkusio__quarkus
extensions/reactive-datasource/deployment/src/test/java/io/quarkus/reactive/datasource/runtime/TestPool.java
{ "start": 544, "end": 1953 }
class ____ implements TestPoolInterface { private final AtomicBoolean isClosed = new AtomicBoolean(false); @Override public void getConnection(Handler<AsyncResult<SqlConnection>> handler) { } @Override public Query<RowSet<Row>> query(String s) { return null; } @Override public PreparedQuery<RowSet<Row>> preparedQuery(String s) { return null; } @Override public PreparedQuery<RowSet<Row>> preparedQuery(String sql, PrepareOptions options) { return null; } @Override public Future<SqlConnection> getConnection() { Promise<SqlConnection> promise = Promise.promise(); getConnection(promise); return promise.future(); } @Override public void close(Handler<AsyncResult<Void>> handler) { isClosed.set(true); handler.handle(Future.succeededFuture()); } @Override public Pool connectHandler(Handler<SqlConnection> handler) { return null; } @Override public Pool connectionProvider(Function<Context, Future<SqlConnection>> provider) { return null; } @Override public int size() { return 0; } @Override public Future<Void> close() { isClosed.set(true); return Future.succeededFuture(); } @Override public boolean isClosed() { return isClosed.get(); } }
TestPool
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2200/issue2224_2/PersonGroupedCollection.java
{ "start": 143, "end": 400 }
class ____ extends StringGroupedCollection<Person> { @Override protected String getKeyForItem(List<Person> list) { if (list == null || list.isEmpty()) return null; return list.get(0).getName(); } }
PersonGroupedCollection
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/NaturalIdInUninitializedAssociationTest.java
{ "start": 4791, "end": 5101 }
class ____ { @Id private int id; @NaturalId(mutable = true) private String name; public EntityMutableNaturalId() { } public EntityMutableNaturalId(int id, String name) { this.id = id; this.name = name; } } @Entity(name = "EntityImmutableNaturalId") public static
EntityMutableNaturalId
java
apache__kafka
metadata/src/test/java/org/apache/kafka/controller/MockAclMutator.java
{ "start": 1648, "end": 1733 }
class ____ attaches * the two directly, for the purpose of unit testing. */ public
just
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/collection/adder/SourceTargetMapperStrategySetterPreferred.java
{ "start": 602, "end": 877 }
interface ____ { SourceTargetMapperStrategySetterPreferred INSTANCE = Mappers.getMapper( SourceTargetMapperStrategySetterPreferred.class ); TargetWithoutSetter toTargetDontUseAdder(Source source) throws DogException; }
SourceTargetMapperStrategySetterPreferred
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/jdk8/ZoneIdTest.java
{ "start": 566, "end": 770 }
class ____ { private ZoneId date; public ZoneId getDate() { return date; } public void setDate(ZoneId date) { this.date = date; } } }
VO
java
google__guice
core/test/com/google/inject/spi/SourcesTest.java
{ "start": 373, "end": 1526 }
class ____ { @Test public void entirelyFilteredSourceShowsAsUnknown() { ElementSource source = (ElementSource) Guice.createInjector( new AbstractModule() { @Override protected void configure() { binder().skipSources(getClass()).bind(String.class).toInstance("Foo"); } }) .getBinding(String.class) .getSource(); assertThat(source.getDeclaringSource()).isEqualTo("[unknown source]"); } @Test public void unfilteredShowsCorrectly() { Module m = new AbstractModule() { @Override protected void configure() { binder().bind(String.class).toInstance("Foo"); } }; ElementSource source = (ElementSource) Guice.createInjector(m).getBinding(String.class).getSource(); StackTraceElement ste = (StackTraceElement) source.getDeclaringSource(); assertThat(ste.getClassName()).isEqualTo(m.getClass().getName()); assertThat(ste.getMethodName()).isEqualTo("configure"); } }
SourcesTest
java
netty__netty
example/src/main/java/io/netty/example/securechat/SecureChatServerHandler.java
{ "start": 1170, "end": 3141 }
class ____ extends SimpleChannelInboundHandler<String> { static final ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE); @Override public void channelActive(final ChannelHandlerContext ctx) { // Once session is secured, send a greeting and register the channel to the global channel // list so the channel received the messages from others. ctx.pipeline().get(SslHandler.class).handshakeFuture().addListener( new GenericFutureListener<Future<Channel>>() { @Override public void operationComplete(Future<Channel> future) throws Exception { ctx.writeAndFlush( "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); ctx.writeAndFlush( "Your session is protected by " + ctx.pipeline().get(SslHandler.class).engine().getSession().getCipherSuite() + " cipher suite.\n"); channels.add(ctx.channel()); } }); } @Override public void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { // Send the received message to all channels but the current one. for (Channel c: channels) { if (c != ctx.channel()) { c.writeAndFlush("[" + ctx.channel().remoteAddress() + "] " + msg + '\n'); } else { c.writeAndFlush("[you] " + msg + '\n'); } } // Close the connection if the client has sent 'bye'. if ("bye".equals(msg.toLowerCase())) { ctx.close(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } }
SecureChatServerHandler
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_3809/Issue3809Mapper.java
{ "start": 1186, "end": 1413 }
class ____ { private String param1; public String getParam1() { return param1; } public void setParam1(String param1) { this.param1 = param1; } } }
NestedTarget
java
redisson__redisson
redisson/src/main/java/org/redisson/client/protocol/convertor/BooleanNotNullReplayConvertor.java
{ "start": 708, "end": 870 }
class ____ implements Convertor<Boolean> { @Override public Boolean convert(Object obj) { return obj != null; } }
BooleanNotNullReplayConvertor
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/timeline/security/TimelineAuthenticationFilterInitializer.java
{ "start": 2422, "end": 4533 }
class ____ extends FilterInitializer { @VisibleForTesting Map<String, String> filterConfig; protected void setAuthFilterConfig(Configuration conf) { filterConfig = new HashMap<String, String>(); for (Map.Entry<String, String> entry : conf .getPropsWithPrefix(ProxyUsers.CONF_HADOOP_PROXYUSER).entrySet()) { filterConfig.put("proxyuser" + entry.getKey(), entry.getValue()); } // yarn.timeline-service.http-authentication.proxyuser will override // hadoop.proxyuser Map<String, String> timelineAuthProps = AuthenticationFilterInitializer.getFilterConfigMap(conf, TIMELINE_HTTP_AUTH_PREFIX); filterConfig.putAll(timelineAuthProps); } protected Map<String, String> getFilterConfig() { return filterConfig; } /** * Initializes {@link TimelineAuthenticationFilter}. * <p> * Propagates to {@link TimelineAuthenticationFilter} configuration all YARN * configuration properties prefixed with * {@value org.apache.hadoop.yarn.conf.YarnConfiguration#TIMELINE_HTTP_AUTH_PREFIX}. * * @param container * The filter container. * @param conf * Configuration for run-time parameters. */ @Override public void initFilter(FilterContainer container, Configuration conf) { setAuthFilterConfig(conf); String authType = filterConfig.get(AuthenticationFilter.AUTH_TYPE); if (authType.equals(PseudoAuthenticationHandler.TYPE)) { filterConfig.put(AuthenticationFilter.AUTH_TYPE, PseudoDelegationTokenAuthenticationHandler.class.getName()); } else if (authType.equals(KerberosAuthenticationHandler.TYPE)) { filterConfig.put(AuthenticationFilter.AUTH_TYPE, KerberosDelegationTokenAuthenticationHandler.class.getName()); } filterConfig.put(DelegationTokenAuthenticationHandler.TOKEN_KIND, TimelineDelegationTokenIdentifier.KIND_NAME.toString()); container.addGlobalFilter("Timeline Authentication Filter", TimelineAuthenticationFilter.class.getName(), filterConfig); } }
TimelineAuthenticationFilterInitializer
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/ir/InvokeCallDefNode.java
{ "start": 616, "end": 1213 }
class ____ extends ArgumentsNode { /* ---- begin visitor ---- */ @Override public <Scope> void visit(IRTreeVisitor<Scope> irTreeVisitor, Scope scope) { irTreeVisitor.visitInvokeCallDef(this, scope); } @Override public <Scope> void visitChildren(IRTreeVisitor<Scope> irTreeVisitor, Scope scope) { for (ExpressionNode argumentNode : getArgumentNodes()) { argumentNode.visit(irTreeVisitor, scope); } } /* ---- end visitor ---- */ public InvokeCallDefNode(Location location) { super(location); } }
InvokeCallDefNode
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/ResolvableTypeTests.java
{ "start": 78270, "end": 78329 }
class ____ extends Wildcard<String> { } public
WildcardFixed
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/FileProducerToDMoveExistingTest.java
{ "start": 1061, "end": 2172 }
class ____ extends ContextTestSupport { @Test public void testMoveExisting() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(2); Map<String, Object> headers = new HashMap<>(); headers.put("myDir", "out"); headers.put(Exchange.FILE_NAME, "hello.txt"); template.sendBodyAndHeaders("direct:start", "Hello World", headers); template.sendBodyAndHeaders("direct:start", "Bye World", headers); assertMockEndpointsSatisfied(); assertFileExists(testFile("out/old-hello.txt")); assertFileExists(testFile("out/hello.txt")); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .toD(fileUri("${header.myDir}?fileExist=Move&moveExisting=" + testDirectory("out").toString() + "/old-${file:onlyname}")) .to("mock:result"); } }; } }
FileProducerToDMoveExistingTest
java
apache__logging-log4j2
log4j-1.2-api/src/main/java/org/apache/log4j/jmx/Agent.java
{ "start": 1347, "end": 1502 }
class ____ provided to maintain compatibility with earlier * versions of log4j and use in new code is discouraged. * * @deprecated */ @Deprecated public
is
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/lib/InputSampler.java
{ "start": 7917, "end": 9800 }
class ____<K,V> extends org.apache.hadoop.mapreduce.lib.partition.InputSampler.IntervalSampler<K, V> implements Sampler<K,V> { /** * Create a new IntervalSampler sampling <em>all</em> splits. * @param freq The frequency with which records will be emitted. */ public IntervalSampler(double freq) { this(freq, Integer.MAX_VALUE); } /** * Create a new IntervalSampler. * @param freq The frequency with which records will be emitted. * @param maxSplitsSampled The maximum number of splits to examine. * @see #getSample */ public IntervalSampler(double freq, int maxSplitsSampled) { super(freq, maxSplitsSampled); } /** * For each split sampled, emit when the ratio of the number of records * retained to the total record count is less than the specified * frequency. */ @SuppressWarnings("unchecked") // ArrayList::toArray doesn't preserve type public K[] getSample(InputFormat<K,V> inf, JobConf job) throws IOException { InputSplit[] splits = inf.getSplits(job, job.getNumMapTasks()); ArrayList<K> samples = new ArrayList<K>(); int splitsToSample = Math.min(maxSplitsSampled, splits.length); int splitStep = splits.length / splitsToSample; long records = 0; long kept = 0; for (int i = 0; i < splitsToSample; ++i) { RecordReader<K,V> reader = inf.getRecordReader(splits[i * splitStep], job, Reporter.NULL); K key = reader.createKey(); V value = reader.createValue(); while (reader.next(key, value)) { ++records; if ((double) kept / records < freq) { ++kept; samples.add(key); key = reader.createKey(); } } reader.close(); } return (K[])samples.toArray(); } } }
IntervalSampler
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/ITestOutOfBandAzureBlobOperationsLive.java
{ "start": 1174, "end": 7181 }
class ____ extends AbstractWasbTestBase { @Override protected AzureBlobStorageTestAccount createTestAccount() throws Exception { return AzureBlobStorageTestAccount.create(); } // scenario for this particular test described at MONARCH-HADOOP-764 // creating a file out-of-band would confuse mkdirs("<oobfilesUncleFolder>") // eg oob creation of "user/<name>/testFolder/a/input/file" // Then wasb creation of "user/<name>/testFolder/a/output" fails @Test public void outOfBandFolder_uncleMkdirs() throws Exception { // NOTE: manual use of CloubBlockBlob targets working directory explicitly. // WASB driver methods prepend working directory implicitly. String workingDir = "user/" + UserGroupInformation.getCurrentUser().getShortUserName() + "/"; CloudBlockBlob blob = testAccount.getBlobReference(workingDir + "testFolder1/a/input/file"); BlobOutputStream s = blob.openOutputStream(); s.close(); assertTrue(fs.exists(new Path("testFolder1/a/input/file"))); Path targetFolder = new Path("testFolder1/a/output"); assertTrue(fs.mkdirs(targetFolder)); } // scenario for this particular test described at MONARCH-HADOOP-764 @Test public void outOfBandFolder_parentDelete() throws Exception { // NOTE: manual use of CloubBlockBlob targets working directory explicitly. // WASB driver methods prepend working directory implicitly. String workingDir = "user/" + UserGroupInformation.getCurrentUser().getShortUserName() + "/"; CloudBlockBlob blob = testAccount.getBlobReference(workingDir + "testFolder2/a/input/file"); BlobOutputStream s = blob.openOutputStream(); s.close(); assertTrue(fs.exists(new Path("testFolder2/a/input/file"))); Path targetFolder = new Path("testFolder2/a/input"); assertTrue(fs.delete(targetFolder, true)); } @Test public void outOfBandFolder_rootFileDelete() throws Exception { CloudBlockBlob blob = testAccount.getBlobReference("fileY"); BlobOutputStream s = blob.openOutputStream(); s.close(); assertTrue(fs.exists(new Path("/fileY"))); assertTrue(fs.delete(new Path("/fileY"), true)); } @Test public void outOfBandFolder_firstLevelFolderDelete() throws Exception { CloudBlockBlob blob = testAccount.getBlobReference("folderW/file"); BlobOutputStream s = blob.openOutputStream(); s.close(); assertTrue(fs.exists(new Path("/folderW"))); assertTrue(fs.exists(new Path("/folderW/file"))); assertTrue(fs.delete(new Path("/folderW"), true)); } // scenario for this particular test described at MONARCH-HADOOP-764 @Test public void outOfBandFolder_siblingCreate() throws Exception { // NOTE: manual use of CloubBlockBlob targets working directory explicitly. // WASB driver methods prepend working directory implicitly. String workingDir = "user/" + UserGroupInformation.getCurrentUser().getShortUserName() + "/"; CloudBlockBlob blob = testAccount.getBlobReference(workingDir + "testFolder3/a/input/file"); BlobOutputStream s = blob.openOutputStream(); s.close(); assertTrue(fs.exists(new Path("testFolder3/a/input/file"))); Path targetFile = new Path("testFolder3/a/input/file2"); FSDataOutputStream s2 = fs.create(targetFile); s2.close(); } // scenario for this particular test described at MONARCH-HADOOP-764 // creating a new file in the root folder @Test public void outOfBandFolder_create_rootDir() throws Exception { Path targetFile = new Path("/newInRoot"); FSDataOutputStream s2 = fs.create(targetFile); s2.close(); } // scenario for this particular test described at MONARCH-HADOOP-764 @Test public void outOfBandFolder_rename() throws Exception { // NOTE: manual use of CloubBlockBlob targets working directory explicitly. // WASB driver methods prepend working directory implicitly. String workingDir = "user/" + UserGroupInformation.getCurrentUser().getShortUserName() + "/"; CloudBlockBlob blob = testAccount.getBlobReference(workingDir + "testFolder4/a/input/file"); BlobOutputStream s = blob.openOutputStream(); s.close(); Path srcFilePath = new Path("testFolder4/a/input/file"); assertTrue(fs.exists(srcFilePath)); Path destFilePath = new Path("testFolder4/a/input/file2"); fs.rename(srcFilePath, destFilePath); } // Verify that you can rename a file which is the only file in an implicit folder in the // WASB file system. // scenario for this particular test described at MONARCH-HADOOP-892 @Test public void outOfBandSingleFile_rename() throws Exception { //NOTE: manual use of CloubBlockBlob targets working directory explicitly. // WASB driver methods prepend working directory implicitly. String workingDir = "user/" + UserGroupInformation.getCurrentUser().getShortUserName() + "/"; CloudBlockBlob blob = testAccount.getBlobReference(workingDir + "testFolder5/a/input/file"); BlobOutputStream s = blob.openOutputStream(); s.close(); Path srcFilePath = new Path("testFolder5/a/input/file"); assertTrue(fs.exists(srcFilePath)); Path destFilePath = new Path("testFolder5/file2"); fs.rename(srcFilePath, destFilePath); } // WASB must force explicit parent directories in create, delete, mkdirs, rename. // scenario for this particular test described at MONARCH-HADOOP-764 @Test public void outOfBandFolder_rename_rootLevelFiles() throws Exception { // NOTE: manual use of CloubBlockBlob targets working directory explicitly. // WASB driver methods prepend working directory implicitly. CloudBlockBlob blob = testAccount.getBlobReference("fileX"); BlobOutputStream s = blob.openOutputStream(); s.close(); Path srcFilePath = new Path("/fileX"); assertTrue(fs.exists(srcFilePath)); Path destFilePath = new Path("/fileXrename"); fs.rename(srcFilePath, destFilePath); } }
ITestOutOfBandAzureBlobOperationsLive
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/producer/internals/BuiltInPartitioner.java
{ "start": 16613, "end": 17173 }
class ____ { public final int[] cumulativeFrequencyTable; public final int[] partitionIds; public final int length; public PartitionLoadStats(int[] cumulativeFrequencyTable, int[] partitionIds, int length) { assert cumulativeFrequencyTable.length == partitionIds.length; assert length <= cumulativeFrequencyTable.length; this.cumulativeFrequencyTable = cumulativeFrequencyTable; this.partitionIds = partitionIds; this.length = length; } } }
PartitionLoadStats
java
spring-projects__spring-framework
spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/reactive/PayloadMethodArgumentResolver.java
{ "start": 3235, "end": 11635 }
class ____ implements HandlerMethodArgumentResolver { protected final Log logger = LogFactory.getLog(getClass()); private final List<Decoder<?>> decoders; private final @Nullable Validator validator; private final ReactiveAdapterRegistry adapterRegistry; private final boolean useDefaultResolution; public PayloadMethodArgumentResolver(List<? extends Decoder<?>> decoders, @Nullable Validator validator, @Nullable ReactiveAdapterRegistry registry, boolean useDefaultResolution) { Assert.isTrue(!CollectionUtils.isEmpty(decoders), "At least one Decoder is required"); this.decoders = List.copyOf(decoders); this.validator = validator; this.adapterRegistry = registry != null ? registry : ReactiveAdapterRegistry.getSharedInstance(); this.useDefaultResolution = useDefaultResolution; } /** * Return a read-only list of the configured decoders. */ public List<Decoder<?>> getDecoders() { return this.decoders; } /** * Return the configured validator, if any. */ public @Nullable Validator getValidator() { return this.validator; } /** * Return the configured {@link ReactiveAdapterRegistry}. */ public ReactiveAdapterRegistry getAdapterRegistry() { return this.adapterRegistry; } /** * Whether this resolver is configured to use default resolution, i.e. * works for any argument type regardless of whether {@code @Payload} is * present or not. */ public boolean isUseDefaultResolution() { return this.useDefaultResolution; } @Override public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(Payload.class) || this.useDefaultResolution; } /** * Decode the content of the given message payload through a compatible * {@link Decoder}. * * <p>Validation is applied if the method argument is annotated with * {@code @jakarta.validation.Valid} or * {@link org.springframework.validation.annotation.Validated}. Validation * failure results in an {@link MethodArgumentNotValidException}. * @param parameter the target method argument that we are decoding to * @param message the message from which the content was extracted * @return a Mono with the result of argument resolution * @see #extractContent(MethodParameter, Message) * @see #getMimeType(Message) */ @Override public final Mono<Object> resolveArgument(MethodParameter parameter, Message<?> message) { Payload ann = parameter.getParameterAnnotation(Payload.class); if (ann != null && StringUtils.hasText(ann.expression())) { throw new IllegalStateException("@Payload SpEL expressions not supported by this resolver"); } MimeType mimeType = getMimeType(message); mimeType = mimeType != null ? mimeType : MimeTypeUtils.APPLICATION_OCTET_STREAM; Flux<DataBuffer> content = extractContent(parameter, message); return decodeContent(parameter, message, ann == null || ann.required(), content, mimeType); } @SuppressWarnings("unchecked") private Flux<DataBuffer> extractContent(MethodParameter parameter, Message<?> message) { Object payload = message.getPayload(); if (payload instanceof DataBuffer dataBuffer) { return Flux.just(dataBuffer); } if (payload instanceof Publisher<?> publisher) { return Flux.from(publisher).map(value -> { if (value instanceof DataBuffer dataBuffer) { return dataBuffer; } String className = value.getClass().getName(); throw getUnexpectedPayloadError(message, parameter, "Publisher<" + className + ">"); }); } return Flux.error(getUnexpectedPayloadError(message, parameter, payload.getClass().getName())); } private MethodArgumentResolutionException getUnexpectedPayloadError( Message<?> message, MethodParameter parameter, String actualType) { return new MethodArgumentResolutionException(message, parameter, "Expected DataBuffer or Publisher<DataBuffer> for the Message payload, actual: " + actualType); } /** * Return the mime type for the content. By default this method checks the * {@link MessageHeaders#CONTENT_TYPE} header expecting to find a * {@link MimeType} value or a String to parse to a {@link MimeType}. * @param message the input message */ protected @Nullable MimeType getMimeType(Message<?> message) { Object headerValue = message.getHeaders().get(MessageHeaders.CONTENT_TYPE); if (headerValue == null) { return null; } else if (headerValue instanceof String stringHeader) { return MimeTypeUtils.parseMimeType(stringHeader); } else if (headerValue instanceof MimeType mimeTypeHeader) { return mimeTypeHeader; } else { throw new IllegalArgumentException("Unexpected MimeType value: " + headerValue); } } private Mono<Object> decodeContent(MethodParameter parameter, Message<?> message, boolean isContentRequired, Flux<DataBuffer> content, MimeType mimeType) { ResolvableType targetType = ResolvableType.forMethodParameter(parameter); Class<?> resolvedType = targetType.resolve(); ReactiveAdapter adapter = (resolvedType != null ? getAdapterRegistry().getAdapter(resolvedType) : null); ResolvableType elementType = (adapter != null ? targetType.getGeneric() : targetType); isContentRequired = isContentRequired || (adapter != null && !adapter.supportsEmpty()); Consumer<Object> validator = getValidator(message, parameter); Map<String, Object> hints = Collections.emptyMap(); for (Decoder<?> decoder : this.decoders) { if (decoder.canDecode(elementType, mimeType)) { if (adapter != null && adapter.isMultiValue()) { Flux<?> flux = content .filter(this::nonEmptyDataBuffer) .map(buffer -> Objects.requireNonNull(decoder.decode(buffer, elementType, mimeType, hints))) .onErrorMap(ex -> handleReadError(parameter, message, ex)); if (isContentRequired) { flux = flux.switchIfEmpty(Flux.error(() -> handleMissingBody(parameter, message))); } if (validator != null) { flux = flux.doOnNext(validator); } return Mono.just(adapter.fromPublisher(flux)); } else { // Single-value (with or without reactive type wrapper) Mono<?> mono = content.next() .filter(this::nonEmptyDataBuffer) .map(buffer -> Objects.requireNonNull(decoder.decode(buffer, elementType, mimeType, hints))) .onErrorMap(ex -> handleReadError(parameter, message, ex)); if (isContentRequired) { mono = mono.switchIfEmpty(Mono.error(() -> handleMissingBody(parameter, message))); } if (validator != null) { mono = mono.doOnNext(validator); } return (adapter != null ? Mono.just(adapter.fromPublisher(mono)) : Mono.from(mono)); } } } return Mono.error(new MethodArgumentResolutionException( message, parameter, "Cannot decode to [" + targetType + "]" + message)); } private boolean nonEmptyDataBuffer(DataBuffer buffer) { if (buffer.readableByteCount() > 0) { return true; } DataBufferUtils.release(buffer); return false; } private Throwable handleReadError(MethodParameter parameter, Message<?> message, Throwable ex) { return ex instanceof DecodingException ? new MethodArgumentResolutionException(message, parameter, "Failed to read HTTP message", ex) : ex; } private MethodArgumentResolutionException handleMissingBody(MethodParameter param, Message<?> message) { return new MethodArgumentResolutionException(message, param, "Payload content is missing: " + param.getExecutable().toGenericString()); } private @Nullable Consumer<Object> getValidator(Message<?> message, MethodParameter parameter) { if (this.validator == null) { return null; } for (Annotation ann : parameter.getParameterAnnotations()) { Object[] validationHints = ValidationAnnotationUtils.determineValidationHints(ann); if (validationHints != null) { String name = Conventions.getVariableNameForParameter(parameter); return target -> { BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(target, name); if (!ObjectUtils.isEmpty(validationHints) && this.validator instanceof SmartValidator sv) { sv.validate(target, bindingResult, validationHints); } else { this.validator.validate(target, bindingResult); } if (bindingResult.hasErrors()) { throw new MethodArgumentNotValidException(message, parameter, bindingResult); } }; } } return null; } }
PayloadMethodArgumentResolver
java
apache__spark
sql/catalyst/src/main/java/org/apache/spark/sql/catalyst/expressions/codegen/UnsafeRowWriter.java
{ "start": 1076, "end": 1834 }
class ____ write data into global row buffer using `UnsafeRow` format. * * It will remember the offset of row buffer which it starts to write, and move the cursor of row * buffer while writing. If new data(can be the input record if this is the outermost writer, or * nested struct if this is an inner writer) comes, the starting cursor of row buffer may be * changed, so we need to call `UnsafeRowWriter.resetRowWriter` before writing, to update the * `startingOffset` and clear out null bits. * * Note that if this is the outermost writer, which means we will always write from the very * beginning of the global row buffer, we don't need to update `startingOffset` and can just call * `zeroOutNullBytes` before writing new data. */ public final
to
java
spring-projects__spring-framework
spring-aop/src/main/java/org/springframework/aop/config/ConfigBeanDefinitionParser.java
{ "start": 17274, "end": 20699 }
class ____ to the supplied {@link Element}. */ private Class<?> getAdviceClass(Element adviceElement, ParserContext parserContext) { String elementName = parserContext.getDelegate().getLocalName(adviceElement); return switch (elementName) { case BEFORE -> AspectJMethodBeforeAdvice.class; case AFTER -> AspectJAfterAdvice.class; case AFTER_RETURNING_ELEMENT -> AspectJAfterReturningAdvice.class; case AFTER_THROWING_ELEMENT -> AspectJAfterThrowingAdvice.class; case AROUND -> AspectJAroundAdvice.class; default -> throw new IllegalArgumentException("Unknown advice kind [" + elementName + "]."); }; } /** * Parses the supplied {@code <pointcut>} and registers the resulting * Pointcut with the BeanDefinitionRegistry. */ private AbstractBeanDefinition parsePointcut(Element pointcutElement, ParserContext parserContext) { String id = pointcutElement.getAttribute(ID); String expression = pointcutElement.getAttribute(EXPRESSION); AbstractBeanDefinition pointcutDefinition = null; try { this.parseState.push(new PointcutEntry(id)); pointcutDefinition = createPointcutDefinition(expression); pointcutDefinition.setSource(parserContext.extractSource(pointcutElement)); String pointcutBeanName = id; if (StringUtils.hasText(pointcutBeanName)) { parserContext.getRegistry().registerBeanDefinition(pointcutBeanName, pointcutDefinition); } else { pointcutBeanName = parserContext.getReaderContext().registerWithGeneratedName(pointcutDefinition); } parserContext.registerComponent( new PointcutComponentDefinition(pointcutBeanName, pointcutDefinition, expression)); } finally { this.parseState.pop(); } return pointcutDefinition; } /** * Parses the {@code pointcut} or {@code pointcut-ref} attributes of the supplied * {@link Element} and add a {@code pointcut} property as appropriate. Generates a * {@link org.springframework.beans.factory.config.BeanDefinition} for the pointcut if necessary * and returns its bean name, otherwise returns the bean name of the referred pointcut. */ private @Nullable Object parsePointcutProperty(Element element, ParserContext parserContext) { if (element.hasAttribute(POINTCUT) && element.hasAttribute(POINTCUT_REF)) { parserContext.getReaderContext().error( "Cannot define both 'pointcut' and 'pointcut-ref' on <advisor> tag.", element, this.parseState.snapshot()); return null; } else if (element.hasAttribute(POINTCUT)) { // Create a pointcut for the anonymous pc and register it. String expression = element.getAttribute(POINTCUT); AbstractBeanDefinition pointcutDefinition = createPointcutDefinition(expression); pointcutDefinition.setSource(parserContext.extractSource(element)); return pointcutDefinition; } else if (element.hasAttribute(POINTCUT_REF)) { String pointcutRef = element.getAttribute(POINTCUT_REF); if (!StringUtils.hasText(pointcutRef)) { parserContext.getReaderContext().error( "'pointcut-ref' attribute contains empty value.", element, this.parseState.snapshot()); return null; } return pointcutRef; } else { parserContext.getReaderContext().error( "Must define one of 'pointcut' or 'pointcut-ref' on <advisor> tag.", element, this.parseState.snapshot()); return null; } } /** * Creates a {@link BeanDefinition} for the {@link AspectJExpressionPointcut}
corresponding
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/isolation/spring/annotation/consumer/dubbo/HelloServiceV2.java
{ "start": 1093, "end": 1383 }
class ____ implements HelloService { @DubboReference(version = "2.0.0", group = "Group2", scope = "remote", protocol = "dubbo") private HelloService helloService; @Override public String sayHello(String name) { return helloService.sayHello(name); } }
HelloServiceV2
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/ensemble/ExponentTests.java
{ "start": 705, "end": 2756 }
class ____ extends WeightedAggregatorTests<Exponent> { @Override Exponent createTestInstance(int numberOfWeights) { double[] weights = Stream.generate(ESTestCase::randomDouble).limit(numberOfWeights).mapToDouble(Double::valueOf).toArray(); return new Exponent(weights); } @Override protected Exponent doParseInstance(XContentParser parser) throws IOException { return lenient ? Exponent.fromXContentLenient(parser) : Exponent.fromXContentStrict(parser); } @Override protected Exponent createTestInstance() { return randomBoolean() ? new Exponent() : createTestInstance(randomIntBetween(1, 100)); } @Override protected Exponent mutateInstance(Exponent instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Writeable.Reader<Exponent> instanceReader() { return Exponent::new; } public void testAggregate() { double[] ones = new double[] { 1.0, 1.0, 1.0, 1.0, 1.0 }; double[][] values = new double[][] { new double[] { .01 }, new double[] { .2 }, new double[] { .002 }, new double[] { -.01 }, new double[] { .1 } }; Exponent exponent = new Exponent(ones); assertThat(exponent.aggregate(exponent.processValues(values)), closeTo(1.35256, 0.00001)); double[] variedWeights = new double[] { .01, -1.0, .1, 0.0, 0.0 }; exponent = new Exponent(variedWeights); assertThat(exponent.aggregate(exponent.processValues(values)), closeTo(0.81897, 0.00001)); exponent = new Exponent(); assertThat(exponent.aggregate(exponent.processValues(values)), closeTo(1.35256, 0.00001)); } public void testCompatibleWith() { Exponent exponent = createTestInstance(); assertThat(exponent.compatibleWith(TargetType.CLASSIFICATION), is(false)); assertThat(exponent.compatibleWith(TargetType.REGRESSION), is(true)); } }
ExponentTests
java
google__guava
android/guava/src/com/google/common/collect/CompactHashMap.java
{ "start": 3469, "end": 3647 }
class ____ there is a specific reason * to prioritize memory over CPU. * * @author Louis Wasserman * @author Jon Noack */ @GwtIncompatible // not worth using in GWT for now
when
java
spring-projects__spring-boot
integration-test/spring-boot-actuator-integration-tests/src/test/java/org/springframework/boot/actuate/autoconfigure/endpoint/web/WebEndpointsAutoConfigurationIntegrationTests.java
{ "start": 1440, "end": 2547 }
class ____ { @Test void healthEndpointWebExtensionIsAutoConfigured() { servletWebRunner().run((context) -> context.getBean(WebEndpointTestApplication.class)); servletWebRunner().run((context) -> assertThat(context).hasSingleBean(HealthEndpointWebExtension.class)); } @Test void healthEndpointReactiveWebExtensionIsAutoConfigured() { reactiveWebRunner() .run((context) -> assertThat(context).hasSingleBean(ReactiveHealthEndpointWebExtension.class)); } private WebApplicationContextRunner servletWebRunner() { return new WebApplicationContextRunner() .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)) .withPropertyValues("management.defaults.metrics.export.enabled=false"); } private ReactiveWebApplicationContextRunner reactiveWebRunner() { return new ReactiveWebApplicationContextRunner() .withConfiguration(UserConfigurations.of(WebEndpointTestApplication.class)) .withPropertyValues("management.defaults.metrics.export.enabled=false"); } @EnableAutoConfiguration @SpringBootConfiguration static
WebEndpointsAutoConfigurationIntegrationTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/PreferredInterfaceTypeTest.java
{ "start": 29336, "end": 29741 }
class ____ { // BUG: Diagnostic contains: String private final CharSequence a = "foo"; } """) .doTest(); } @Test public void obeysKeep() { refactoringHelper .addInputLines( "Test.java", """ import com.google.errorprone.annotations.Keep; import java.util.ArrayList;
Test
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringLoopTest.java
{ "start": 1029, "end": 1251 }
class ____ extends LoopTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/loop.xml"); } }
SpringLoopTest
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/method/RequestMappingInfo.java
{ "start": 15274, "end": 16367 }
interface ____ { /** * Set the path patterns. */ Builder paths(String... paths); /** * Set the request method conditions. */ Builder methods(RequestMethod... methods); /** * Set the request param conditions. */ Builder params(String... params); /** * Set the header conditions. * <p>By default this is not set. */ Builder headers(String... headers); /** * Set the consumes conditions. */ Builder consumes(String... consumes); /** * Set the produces conditions. */ Builder produces(String... produces); /** * Set the API version condition. * @since 7.0 */ Builder version(String version); /** * Set the mapping name. */ Builder mappingName(String name); /** * Set a custom condition to use. */ Builder customCondition(RequestCondition<?> condition); /** * Provide additional configuration needed for request mapping purposes. */ Builder options(BuilderConfiguration options); /** * Build the RequestMappingInfo. */ RequestMappingInfo build(); } private static
Builder
java
quarkusio__quarkus
extensions/spring-data-jpa/deployment/src/test/java/io/quarkus/spring/data/deployment/CustomerRepositoryDerivedMethodsTest.java
{ "start": 522, "end": 6252 }
class ____ { @RegisterExtension static final QuarkusUnitTest TEST = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addAsResource("import_customers.sql", "import.sql") .addClasses(Customer.class, CustomerRepository.class)) .withConfigurationResource("application.properties"); private static final ZonedDateTime BIRTHDATE = ZonedDateTime.now(); @Autowired private CustomerRepository customerRepository; @Test @Transactional void whenFindByNameThenReturnsCorrectResult() { assertEquals(2, customerRepository.findByName("Adam") .size()); assertEquals(2, customerRepository.findByNameIs("Adam") .size()); assertEquals(2, customerRepository.findByNameEquals("Adam") .size()); assertEquals(1, customerRepository.findByNameIsNull() .size()); assertEquals(5, customerRepository.findByNameIsNotNull() .size()); } @Test @Transactional void whenFindingByNameNotAdamThenReturnsCorrectResult() { assertEquals(3, customerRepository.findByNameNot("Adam") .size()); assertEquals(3, customerRepository.findByNameIsNot("Adam") .size()); } @Test @Transactional void whenFindByNameStartingWith_thenReturnsCorrectResult() { assertEquals(2, customerRepository.findByNameStartingWith("A") .size()); } @Test @Transactional void whenFindByNameLikePatternThenReturnsCorrectResult() { assertEquals(2, customerRepository.findByNameLike("%im%") .size()); } @Test @Transactional void whenFindByNameEndingWith_thenReturnsCorrectResult() { assertEquals(2, customerRepository.findByNameEndingWith("e") .size()); } @Test @Transactional void whenByNameContaining_thenReturnsCorrectResult() { assertEquals(1, customerRepository.findByNameContaining("v") .size()); } @Test @Transactional void whenFindingByNameEndingWithMThenReturnsThree() { assertEquals(3, customerRepository.findByNameEndingWith("m") .size()); } @Test @Transactional void whenByAgeLessThanThenReturnsCorrectResult() { assertEquals(3, customerRepository.findByAgeLessThan(25) .size()); } @Test @Transactional void whenByAgeLessThanEqualThenReturnsCorrectResult() { assertEquals(4, customerRepository.findByAgeLessThanEqual(25) .size()); } @Test @Transactional void whenByAgeGreaterThan25ThenReturnsTwo() { assertEquals(2, customerRepository.findByAgeGreaterThan(25) .size()); } @Test @Transactional void whenFindingByAgeGreaterThanEqual25ThenReturnsThree() { assertEquals(3, customerRepository.findByAgeGreaterThanEqual(25) .size()); } @Test @Transactional void whenFindingByAgeBetween20And30ThenReturnsFour() { assertEquals(4, customerRepository.findByAgeBetween(20, 30) .size()); } @Test @Transactional void whenFindingByBirthDateAfterYesterdayThenReturnsCorrectResult() { final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); assertEquals(6, customerRepository.findByBirthDateAfter(yesterday) .size()); } @Test @Transactional void whenByBirthDateBeforeThenReturnsCorrectResult() { final ZonedDateTime yesterday = BIRTHDATE.minusDays(1); assertEquals(0, customerRepository.findByBirthDateBefore(yesterday) .size()); } @Test @Transactional void whenByActiveTrueThenReturnsCorrectResult() { assertEquals(2, customerRepository.findByActiveTrue() .size()); } @Test @Transactional void whenByActiveFalseThenReturnsCorrectResult() { assertEquals(4, customerRepository.findByActiveFalse() .size()); } @Test @Transactional void whenByAgeInThenReturnsCorrectResult() { final List<Integer> ages = Arrays.asList(20, 25); assertEquals(3, customerRepository.findByAgeIn(ages) .size()); } @Test @Transactional void whenByNameOrAge() { assertEquals(3, customerRepository.findByNameOrAge("Adam", 20) .size()); } @Test @Transactional void whenByNameOrAgeAndActive() { assertEquals(2, customerRepository.findByNameOrAgeAndActive("Adam", 20, false) .size()); } @Test @Transactional void whenByNameAndAgeAndActive() { assertEquals(1, customerRepository.findAllByNameAndAgeAndActive("Adam", 20, false) .size()); } @Test @Transactional void whenByNameOrAgeOrActive() { assertEquals(3, customerRepository.findAllByNameOrAgeOrActive("Adam", 20, true) .size()); } @Test @Transactional void whenByNameAndAgeOrActive() { assertEquals(3, customerRepository.findAllByNameAndAgeOrActive("Adam", 20, true) .size()); } @Test @Transactional void whenByNameOrderByName() { assertEquals(2, customerRepository.findByNameOrderByName("Adam") .size()); assertEquals(2, customerRepository.findByNameOrderByNameDesc("Adam") .size()); assertEquals(2, customerRepository.findByNameOrderByNameAsc("Adam") .size()); } }
CustomerRepositoryDerivedMethodsTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/connections/AggressiveReleaseTest.java
{ "start": 2108, "end": 2191 }
class ____ extends ConnectionManagementTestCase { public static
AggressiveReleaseTest
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/DefaultLoginPageConfigurerTests.java
{ "start": 17110, "end": 17593 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((requests) -> requests .anyRequest().hasRole("USER")) .formLogin(withDefaults()); // @formatter:on return http.build(); } @Bean UserDetailsService userDetailsService() { return new InMemoryUserDetailsManager(PasswordEncodedUser.user()); } } @Configuration @EnableWebSecurity static
DefaultLoginPageConfig
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/type/TypeAliasesTest.java
{ "start": 657, "end": 1255 }
class ____ extends BaseData<List<String>> { } } /* /******************************************************* /* Unit tests /******************************************************* */ // Reproducing [databind#743] @Test public void testAliasResolutionIssue743() throws Exception { String s3 = "{\"dataObj\" : [ \"one\", \"two\", \"three\" ] }"; ObjectMapper m = new ObjectMapper(); Child.ChildData d = m.readValue(s3, Child.ChildData.class); assertNotNull(d.dataObj); assertEquals(3, d.dataObj.size()); } }
ChildData
java
apache__kafka
storage/api/src/main/java/org/apache/kafka/server/log/remote/storage/RemoteLogSegmentMetadata.java
{ "start": 16963, "end": 17774 }
class ____ { private final byte[] value; public CustomMetadata(byte[] value) { this.value = value; } public byte[] value() { return value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CustomMetadata that = (CustomMetadata) o; return Arrays.equals(value, that.value); } @Override public int hashCode() { return Arrays.hashCode(value); } @Override public String toString() { return "CustomMetadata{" + value.length + " bytes}"; } } }
CustomMetadata
java
google__auto
common/src/main/java/com/google/auto/common/Visibility.java
{ "start": 1197, "end": 1288 }
enum ____ ordered according by increasing visibility. * * @author Gregory Kick */ public
are
java
apache__maven
impl/maven-logging/src/main/java/org/apache/maven/slf4j/MavenFailOnSeverityLogger.java
{ "start": 1102, "end": 4199 }
class ____ extends MavenSimpleLogger { private final DefaultLogLevelRecorder logLevelRecorder; MavenFailOnSeverityLogger(String name, DefaultLogLevelRecorder logLevelRecorder) { super(name); this.logLevelRecorder = logLevelRecorder; } /** * A simple implementation which always logs messages of level WARN * according to the format outlined above. */ @Override public void warn(String msg) { super.warn(msg); logLevelRecorder.record(Level.WARN); } /** * Perform single parameter substitution before logging the message of level * WARN according to the format outlined above. */ @Override public void warn(String format, Object arg) { super.warn(format, arg); logLevelRecorder.record(Level.WARN); } /** * Perform double parameter substitution before logging the message of level * WARN according to the format outlined above. */ @Override public void warn(String format, Object arg1, Object arg2) { super.warn(format, arg1, arg2); logLevelRecorder.record(Level.WARN); } /** * Perform double parameter substitution before logging the message of level * WARN according to the format outlined above. */ @Override public void warn(String format, Object... argArray) { super.warn(format, argArray); logLevelRecorder.record(Level.WARN); } /** Log a message of level WARN, including an exception. */ @Override public void warn(String msg, Throwable t) { super.warn(msg, t); logLevelRecorder.record(Level.WARN); } /** * A simple implementation which always logs messages of level ERROR * according to the format outlined above. */ @Override public void error(String msg) { super.error(msg); logLevelRecorder.record(Level.ERROR); } /** * Perform single parameter substitution before logging the message of level * ERROR according to the format outlined above. */ @Override public void error(String format, Object arg) { super.error(format, arg); logLevelRecorder.record(Level.ERROR); } /** * Perform double parameter substitution before logging the message of level * ERROR according to the format outlined above. */ @Override public void error(String format, Object arg1, Object arg2) { super.error(format, arg1, arg2); logLevelRecorder.record(Level.ERROR); } /** * Perform double parameter substitution before logging the message of level * ERROR according to the format outlined above. */ @Override public void error(String format, Object... argArray) { super.error(format, argArray); logLevelRecorder.record(Level.ERROR); } /** Log a message of level ERROR, including an exception. */ @Override public void error(String msg, Throwable t) { super.error(msg, t); logLevelRecorder.record(Level.ERROR); } }
MavenFailOnSeverityLogger
java
spring-projects__spring-boot
module/spring-boot-jdbc/src/test/java/org/springframework/boot/jdbc/DatabaseDriverClassNameTests.java
{ "start": 1399, "end": 3694 }
class ____ { private static final Set<DatabaseDriver> EXCLUDED_DRIVERS = Collections .unmodifiableSet(EnumSet.of(DatabaseDriver.UNKNOWN, DatabaseDriver.DB2_AS400, DatabaseDriver.INFORMIX, DatabaseDriver.HANA, DatabaseDriver.PHOENIX, DatabaseDriver.TERADATA, DatabaseDriver.REDSHIFT)); @ParameterizedTest(name = "{0} {2}") @MethodSource void databaseClassIsOfRequiredType(DatabaseDriver driver, String className, Class<?> requiredType) throws Exception { assertThat(getInterfaceNames(className.replace('.', '/'))).contains(requiredType.getName().replace('.', '/')); } private List<String> getInterfaceNames(String className) throws IOException { // Use ASM to avoid unwanted side effects of loading JDBC drivers ClassReader classReader = new ClassReader(getClass().getResourceAsStream("/" + className + ".class")); List<String> interfaceNames = new ArrayList<>(); for (String name : classReader.getInterfaces()) { interfaceNames.add(name); interfaceNames.addAll(getInterfaceNames(name)); } String superName = classReader.getSuperName(); if (superName != null) { interfaceNames.addAll(getInterfaceNames(superName)); } return interfaceNames; } static Stream<? extends Arguments> databaseClassIsOfRequiredType() { Function<DatabaseDriver, @Nullable String> getDriverClassName = DatabaseDriver::getDriverClassName; return Stream.concat(argumentsForType(Driver.class, getDriverClassName), argumentsForType(XADataSource.class, (databaseDriver) -> databaseDriver.getXaDataSourceClassName() != null, DatabaseDriver::getXaDataSourceClassName)); } private static Stream<? extends Arguments> argumentsForType(Class<?> type, Function<DatabaseDriver, @Nullable String> classNameExtractor) { return argumentsForType(type, (databaseDriver) -> true, classNameExtractor); } private static Stream<? extends Arguments> argumentsForType(Class<?> type, Predicate<DatabaseDriver> predicate, Function<DatabaseDriver, @Nullable String> classNameExtractor) { return Stream.of(DatabaseDriver.values()) .filter((databaseDriver) -> !EXCLUDED_DRIVERS.contains(databaseDriver)) .filter(predicate) .map((databaseDriver) -> Arguments.of(databaseDriver, classNameExtractor.apply(databaseDriver), type)); } }
DatabaseDriverClassNameTests
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/support/discovery/SelectorResolver.java
{ "start": 18693, "end": 23070 }
class ____ { private static final Resolution UNRESOLVED = new Resolution(emptySet(), emptySet()); private final Set<Match> matches; private final Set<? extends DiscoverySelector> selectors; /** * Factory for creating <em>unresolved</em> resolutions. * * @return an <em>unresolved</em> resolution; never {@code null} */ public static Resolution unresolved() { return UNRESOLVED; } /** * Factory for creating a resolution that contains the supplied * {@link Match Match}. * * @param match the resolved {@code Match}; never {@code null} * @return a resolution that contains the supplied {@code Match}; never * {@code null} */ public static Resolution match(Match match) { Preconditions.notNull(match, "match must not be null"); return new Resolution(Set.of(match), emptySet()); } /** * Factory for creating a resolution that contains the supplied * {@link Match Matches}. * * @param matches the resolved {@code Matches}; never {@code null} or * empty * @return a resolution that contains the supplied {@code Matches}; * never {@code null} */ public static Resolution matches(Set<Match> matches) { Preconditions.notNull(matches, "matches must not be null"); Preconditions.notEmpty(matches, "matches must not be empty"); Preconditions.containsNoNullElements(matches, "matches must not contain null elements"); return new Resolution(matches, emptySet()); } /** * Factory for creating a resolution that contains the supplied * {@link DiscoverySelector DiscoverySelectors}. * * @param selectors the resolved {@code DiscoverySelectors}; never * {@code null} or empty * @return a resolution that contains the supplied * {@code DiscoverySelectors}; never {@code null} */ public static Resolution selectors(Set<? extends DiscoverySelector> selectors) { Preconditions.notNull(selectors, "selectors must not be null"); Preconditions.notEmpty(selectors, "selectors must not be empty"); Preconditions.containsNoNullElements(selectors, "selectors must not contain null elements"); return new Resolution(emptySet(), selectors); } private Resolution(Set<Match> matches, Set<? extends DiscoverySelector> selectors) { this.matches = matches; this.selectors = selectors; } /** * Whether this resolution contains matches or selectors. * * @return {@code true} if this resolution contains matches or selectors */ public boolean isResolved() { return this != UNRESOLVED; } /** * Returns the matches contained by this resolution. * * @return the set of matches; never {@code null} but potentially empty */ public Set<Match> getMatches() { return matches; } /** * Returns the selectors contained by this resolution. * * @return the set of selectors; never {@code null} but potentially empty */ public Set<? extends DiscoverySelector> getSelectors() { return selectors; } } /** * An exact or partial match for resolving a {@link DiscoverySelector} into * a {@link TestDescriptor}. * * <p>A match is <em>exact</em> if the {@link DiscoverySelector} directly * represents the resulting {@link TestDescriptor}, e.g. if a * {@link ClassSelector} was resolved into the {@link TestDescriptor} that * represents the test class. It is <em>partial</em> if the matching * {@link TestDescriptor} does not directly correspond to the resolved * {@link DiscoverySelector}, e.g. when resolving a {@link UniqueIdSelector} * that represents a dynamic child of the resolved {@link TestDescriptor}. * * <p>In addition to the {@link TestDescriptor}, a match may contain a * {@code Supplier} of {@link DiscoverySelector DiscoverySelectors} that may * be used to discover the children of the {@link TestDescriptor}. The * algorithm implemented by {@link EngineDiscoveryRequestResolver} * {@linkplain #expand() expands} all exact matches immediately, i.e. it * resolves all of their children. Partial matches will only be expanded in * case a subsequent resolution finds an exact match that contains a {@link * TestDescriptor} with the same {@linkplain TestDescriptor#getUniqueId() * unique ID}. * * @since 1.5 * @see SelectorResolver * @see Resolution#match(Match) * @see Resolution#matches(Set) */ @API(status = STABLE, since = "1.10")
Resolution
java
redisson__redisson
redisson/src/main/java/org/redisson/RedissonReference.java
{ "start": 2718, "end": 3285 }
class ____ be located */ public Class<?> getType() throws ClassNotFoundException { return Class.forName(type); } public Class<?> getRxJavaType() throws ClassNotFoundException { String rxName = type + "Rx"; if (isAvailable(rxName)) { return Class.forName(rxName); //live object is not supported in reactive client } throw new ClassNotFoundException("There is no RxJava compatible type for " + type); } /** * @return the type * @throws java.lang.ClassNotFoundException - if the
cannot
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/objects/Objects_assertHasSameHashCodeAs_Test.java
{ "start": 1736, "end": 2831 }
class ____ is computed with the Jedi's name only Jedi redYoda = new Jedi("Yoda", "Red"); objects.assertHasSameHashCodeAs(someInfo(), greenYoda, redYoda); objects.assertHasSameHashCodeAs(someInfo(), redYoda, greenYoda); objects.assertHasSameHashCodeAs(someInfo(), greenYoda, new Jedi("Yoda", "green")); objects.assertHasSameHashCodeAs(someInfo(), greenYoda, greenYoda); } @Test void should_throw_error_if_other_is_null() { assertThatNullPointerException().isThrownBy(() -> objects.assertHasSameHashCodeAs(someInfo(), greenYoda, null)) .withMessage("The object used to compare actual's hash code with should not be null"); } @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> objects.assertHasSameHashCodeAs(someInfo(), null, greenYoda)) .withMessage(actualIsNull()); } @Test void should_fail_if_actual_does_not_have_the_same_hash_code_as_other() { AssertionInfo info = someInfo(); // Jedi
hashCode
java
apache__camel
components/camel-avro/src/main/java/org/apache/camel/dataformat/avro/AvroDataFormat.java
{ "start": 2379, "end": 4221 }
class ____ extends ServiceSupport implements DataFormat, DataFormatName, CamelContextAware { private static final String GENERIC_CONTAINER_CLASSNAME = GenericContainer.class.getName(); private CamelContext camelContext; private Object schema; private transient Schema actualSchema; private String instanceClassName; public AvroDataFormat() { } public AvroDataFormat(Schema schema) { this.schema = schema; } @Override public String getDataFormatName() { return "avro"; } @Override public CamelContext getCamelContext() { return camelContext; } @Override public void setCamelContext(CamelContext camelContext) { this.camelContext = camelContext; } @Override protected void doInit() throws Exception { super.doInit(); if (schema != null) { if (schema instanceof Schema) { actualSchema = (Schema) schema; } else { actualSchema = loadSchema(schema.getClass().getName()); } } else if (instanceClassName != null) { actualSchema = loadSchema(instanceClassName); } } @Override protected void doStop() throws Exception { // noop } // the getter/setter for Schema is Object type in the API public Object getSchema() { return actualSchema != null ? actualSchema : schema; } public void setSchema(Object schema) { this.schema = schema; } public String getInstanceClassName() { return instanceClassName; } public void setInstanceClassName(String className) { instanceClassName = className; } protected Schema loadSchema(String className) throws CamelException, ClassNotFoundException { // must use same
AvroDataFormat
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CheckReturnValueWellKnownLibrariesTest.java
{ "start": 12673, "end": 13887 }
class ____ {", " @Test(expected = IllegalArgumentException.class) ", " public void foo() {", " new Foo();", // OK when it's the only statement " }", " @Test(expected = IllegalArgumentException.class) ", " public void fooWith2Statements() {", " Foo f = new Foo();", " // BUG: Diagnostic contains: CheckReturnValue", " new Foo();", // Not OK if there is more than one statement in the block. " }", " @Test(expected = Test.None.class) ", // This is a weird way to spell the default " public void fooWithNone() {", " // BUG: Diagnostic contains: CheckReturnValue", " new Foo();", " }", "}") .doTest(); } @Test public void autoValueBuilderSetterMethods() { compilationHelper .addSourceLines( "Animal.java", """ package com.google.frobber; import com.google.auto.value.AutoValue; import com.google.errorprone.annotations.CheckReturnValue; @AutoValue @CheckReturnValue abstract
Foo
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/cdi/RepositoryConsumer.java
{ "start": 778, "end": 1534 }
class ____ { @Inject PersonRepository unqualifiedRepo; @Inject @PersonDB PersonRepository qualifiedRepo; @Inject SamplePersonRepository samplePersonRepository; @Inject @UserDB QualifiedCustomizedUserRepository qualifiedCustomizedUserRepository; public void findAll() { unqualifiedRepo.findAll(); qualifiedRepo.findAll(); } public void save(Person person) { unqualifiedRepo.save(person); } public void saveUserDb(Person person) { qualifiedRepo.save(person); } public int returnOne() { return samplePersonRepository.returnOne(); } public void doSomethingOnUserDB() { qualifiedCustomizedUserRepository.doSomething(); } public int returnOneUserDB() { return qualifiedCustomizedUserRepository.returnOne(); } }
RepositoryConsumer
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/type/JavaTypeTest.java
{ "start": 1668, "end": 13549 }
interface ____ extends Iterator<String> { } /* /********************************************************** /* Test methods /********************************************************** */ @Test public void testLocalType728() throws Exception { TypeFactory tf = defaultTypeFactory(); Method m = Issue728.class.getMethod("method", CharSequence.class); assertNotNull(m); // Start with return type // first type-erased JavaType t = tf.constructType(m.getReturnType()); assertEquals(CharSequence.class, t.getRawClass()); // then generic t = tf.constructType(m.getGenericReturnType()); assertEquals(CharSequence.class, t.getRawClass()); // then parameter type t = tf.constructType(m.getParameterTypes()[0]); assertEquals(CharSequence.class, t.getRawClass()); t = tf.constructType(m.getGenericParameterTypes()[0]); assertEquals(CharSequence.class, t.getRawClass()); } @Test public void testSimpleClass() { TypeFactory tf = defaultTypeFactory(); JavaType baseType = tf.constructType(BaseType.class); assertSame(BaseType.class, baseType.getRawClass()); assertTrue(baseType.hasRawClass(BaseType.class)); assertFalse(baseType.isTypeOrSubTypeOf(SubType.class)); assertFalse(baseType.isArrayType()); assertFalse(baseType.isContainerType()); assertFalse(baseType.isEnumType()); assertFalse(baseType.isInterface()); assertFalse(baseType.isIterationType()); assertFalse(baseType.isPrimitive()); assertFalse(baseType.isReferenceType()); assertFalse(baseType.hasContentType()); assertNull(baseType.getContentType()); assertNull(baseType.getKeyType()); assertNull(baseType.getValueHandler()); assertEquals("Ltools/jackson/databind/type/JavaTypeTest$BaseType;", baseType.getGenericSignature()); assertEquals("Ltools/jackson/databind/type/JavaTypeTest$BaseType;", baseType.getErasedSignature()); } @Test public void testArrayType() { TypeFactory tf = defaultTypeFactory(); JavaType arrayT = ArrayType.construct(tf.constructType(String.class), null); assertNotNull(arrayT); assertTrue(arrayT.isContainerType()); assertFalse(arrayT.isIterationType()); assertFalse(arrayT.isReferenceType()); assertTrue(arrayT.hasContentType()); assertNotNull(arrayT.toString()); assertNotNull(arrayT.getContentType()); assertNull(arrayT.getKeyType()); assertTrue(arrayT.equals(arrayT)); assertFalse(arrayT.equals(null)); final Object bogus = "xyz"; assertFalse(arrayT.equals(bogus)); assertTrue(arrayT.equals(ArrayType.construct(tf.constructType(String.class), null))); assertFalse(arrayT.equals(ArrayType.construct(tf.constructType(Integer.class), null))); } @Test public void testMapType() { TypeFactory tf = defaultTypeFactory(); JavaType mapT = tf.constructType(HashMap.class); assertTrue(mapT.isContainerType()); assertFalse(mapT.isIterationType()); assertFalse(mapT.isReferenceType()); assertTrue(mapT.hasContentType()); assertNotNull(mapT.toString()); assertNotNull(mapT.getContentType()); assertNotNull(mapT.getKeyType()); assertEquals("Ljava/util/HashMap<Ljava/lang/Object;Ljava/lang/Object;>;", mapT.getGenericSignature()); assertEquals("Ljava/util/HashMap;", mapT.getErasedSignature()); assertTrue(mapT.equals(mapT)); assertFalse(mapT.equals(null)); Object bogus = "xyz"; assertFalse(mapT.equals(bogus)); } @Test public void testEnumType() { TypeFactory tf = defaultTypeFactory(); JavaType enumT = tf.constructType(MyEnum.class); // JDK actually works fine with "basic" Enum types... assertTrue(enumT.getRawClass().isEnum()); assertTrue(enumT.isEnumType()); assertTrue(enumT.isEnumImplType()); assertFalse(enumT.isIterationType()); assertFalse(enumT.hasHandlers()); assertTrue(enumT.isTypeOrSubTypeOf(MyEnum.class)); assertTrue(enumT.isTypeOrSubTypeOf(Object.class)); assertNull(enumT.containedType(3)); assertTrue(enumT.containedTypeOrUnknown(3).isJavaLangObject()); assertEquals("Ltools/jackson/databind/type/JavaTypeTest$MyEnum;", enumT.getGenericSignature()); assertEquals("Ltools/jackson/databind/type/JavaTypeTest$MyEnum;", enumT.getErasedSignature()); assertTrue(tf.constructType(MyEnum2.class).isEnumType()); assertTrue(tf.constructType(MyEnum.A.getClass()).isEnumType()); assertTrue(tf.constructType(MyEnum2.A.getClass()).isEnumType()); // [databind#2480] assertFalse(tf.constructType(Enum.class).isEnumImplType()); JavaType enumSubT = tf.constructType(MyEnumSub.B.getClass()); assertTrue(enumSubT.isEnumType()); assertTrue(enumSubT.isEnumImplType()); // and this is kind of odd twist by JDK: one might except this to return true, // but no, sub-classes (when Enum values have overrides, and require sub-class) // are NOT considered enums for whatever reason assertFalse(enumSubT.getRawClass().isEnum()); } @Test public void testClassKey() { ClassKey key = new ClassKey(String.class); ClassKey keyToo = key; int selfComparisonResult = key.compareTo(keyToo); assertEquals(0, selfComparisonResult); assertTrue(key.equals(key)); assertFalse(key.equals(null)); Object bogus = "foo"; assertFalse(key.equals(bogus)); assertFalse(key.equals(new ClassKey(Integer.class))); assertEquals(String.class.getName(), key.toString()); } // [databind#116] @Test public void testJavaTypeAsJLRType() { TypeFactory tf = defaultTypeFactory(); JavaType t1 = tf.constructType(getClass()); // should just get it back as-is: JavaType t2 = tf.constructType(t1); assertSame(t1, t2); } // [databind#1194] @Test public void testGenericSignature1194() throws Exception { TypeFactory tf = defaultTypeFactory(); Method m; JavaType t; m = Generic1194.class.getMethod("getList"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/List<Ljava/lang/String;>;", t.getGenericSignature()); assertEquals("Ljava/util/List;", t.getErasedSignature()); m = Generic1194.class.getMethod("getMap"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/Map<Ljava/lang/String;Ljava/lang/String;>;", t.getGenericSignature()); m = Generic1194.class.getMethod("getGeneric"); t = tf.constructType(m.getGenericReturnType()); assertEquals("Ljava/util/concurrent/atomic/AtomicReference<Ljava/lang/String;>;", t.getGenericSignature()); } @Deprecated @Test public void testAnchorTypeForRefTypes() throws Exception { TypeFactory tf = defaultTypeFactory(); JavaType t = tf.constructType(AtomicStringReference.class); assertTrue(t.isReferenceType()); assertTrue(t.hasContentType()); JavaType ct = t.getContentType(); assertEquals(String.class, ct.getRawClass()); assertSame(ct, t.containedType(0)); ReferenceType rt = (ReferenceType) t; assertFalse(rt.isAnchorType()); assertEquals(AtomicReference.class, rt.getAnchorType().getRawClass()); } // for [databind#1290] @Test public void testObjectToReferenceSpecialization() throws Exception { TypeFactory tf = defaultTypeFactory(); JavaType base = tf.constructType(Object.class); assertTrue(base.isJavaLangObject()); JavaType sub = tf.constructSpecializedType(base, AtomicReference.class); assertEquals(AtomicReference.class, sub.getRawClass()); assertTrue(sub.isReferenceType()); } // for [databind#2091] @Test public void testConstructReferenceType() throws Exception { TypeFactory tf = defaultTypeFactory(); // do AtomicReference<Long> final JavaType refdType = tf.constructType(Long.class); JavaType t = tf.constructReferenceType(AtomicReference.class, refdType); assertTrue(t.isReferenceType()); assertTrue(t.hasContentType()); assertEquals(Long.class, t.getContentType().getRawClass()); // 26-Mar-2020, tatu: [databind#2019] made this work assertEquals(1, t.containedTypeCount()); TypeBindings bindings = t.getBindings(); assertEquals(1, bindings.size()); assertEquals(refdType, bindings.getBoundType(0)); // Should we even verify this or not? assertEquals("V", bindings.getBoundName(0)); } // for [databind#3950]: resolve `Iterator`, `Stream` @Test public void testIterationTypesDirect() throws Exception { TypeFactory tf = defaultTypeFactory(); // First, type-erased types _verifyIteratorType(tf.constructType(Iterator.class), Iterator.class, Object.class); _verifyIteratorType(tf.constructType(Stream.class), Stream.class, Object.class); // Then generic but direct JavaType t = _verifyIteratorType(tf.constructType(new TypeReference<Iterator<String>>() { }), Iterator.class, String.class); assertEquals("java.util.Iterator<java.lang.String>", t.toCanonical()); assertEquals("Ljava/util/Iterator;", t.getErasedSignature()); assertEquals("Ljava/util/Iterator<Ljava/lang/String;>;", t.getGenericSignature()); _verifyIteratorType(tf.constructType(new TypeReference<Stream<Long>>() { }), Stream.class, Long.class); // Then primitive stream: _verifyIteratorType(tf.constructType(DoubleStream.class), DoubleStream.class, Double.TYPE); _verifyIteratorType(tf.constructType(IntStream.class), IntStream.class, Integer.TYPE); _verifyIteratorType(tf.constructType(LongStream.class), LongStream.class, Long.TYPE); } // for [databind#3950]: resolve `Iterator`, `Stream` @Test public void testIterationTypesFromValues() throws Exception { TypeFactory tf = defaultTypeFactory(); List<String> strings = Arrays.asList("foo", "bar"); // We will get type-erased, alas, so: Iterator<String> stringIT = strings.iterator(); _verifyIteratorType(tf.constructType(stringIT.getClass()), stringIT.getClass(), Object.class); Stream<String> stringStream = strings.stream(); _verifyIteratorType(tf.constructType(stringStream.getClass()), stringStream.getClass(), Object.class); } // for [databind#3950]: resolve `Iterator`, `Stream` @Test public void testIterationSubTypes() throws Exception { TypeFactory tf = defaultTypeFactory(); _verifyIteratorType(tf.constructType(StringIterator.class), StringIterator.class, String.class); _verifyIteratorType(tf.constructType(StringStream.class), StringStream.class, String.class); } private JavaType _verifyIteratorType(JavaType type, Class<?> expType, Class<?> expContentType) { assertTrue(type.isIterationType()); assertEquals(IterationType.class, type.getClass()); assertEquals(expType, type.getRawClass()); assertEquals(expContentType, type.getContentType().getRawClass()); return type; } }
StringIterator
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/subresource/ParameterizedParentInterfaceTest.java
{ "start": 3216, "end": 3414 }
interface ____ extends ClientLocatorBase<String, Long> { @Path("greetings/translations/english/shorts/hello") @GET List<String> testListOnRoot(); } public
ClientLocator
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/SampleIntAggregatorFunction.java
{ "start": 1039, "end": 6049 }
class ____ implements AggregatorFunction { private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of( new IntermediateStateDesc("sample", ElementType.BYTES_REF) ); private final DriverContext driverContext; private final SampleIntAggregator.SingleState state; private final List<Integer> channels; private final int limit; public SampleIntAggregatorFunction(DriverContext driverContext, List<Integer> channels, SampleIntAggregator.SingleState state, int limit) { this.driverContext = driverContext; this.channels = channels; this.state = state; this.limit = limit; } public static SampleIntAggregatorFunction create(DriverContext driverContext, List<Integer> channels, int limit) { return new SampleIntAggregatorFunction(driverContext, channels, SampleIntAggregator.initSingle(driverContext.bigArrays(), limit), limit); } public static List<IntermediateStateDesc> intermediateStateDesc() { return INTERMEDIATE_STATE_DESC; } @Override public int intermediateBlockCount() { return INTERMEDIATE_STATE_DESC.size(); } @Override public void addRawInput(Page page, BooleanVector mask) { if (mask.allFalse()) { // Entire page masked away } else if (mask.allTrue()) { addRawInputNotMasked(page); } else { addRawInputMasked(page, mask); } } private void addRawInputMasked(Page page, BooleanVector mask) { IntBlock valueBlock = page.getBlock(channels.get(0)); IntVector valueVector = valueBlock.asVector(); if (valueVector == null) { addRawBlock(valueBlock, mask); return; } addRawVector(valueVector, mask); } private void addRawInputNotMasked(Page page) { IntBlock valueBlock = page.getBlock(channels.get(0)); IntVector valueVector = valueBlock.asVector(); if (valueVector == null) { addRawBlock(valueBlock); return; } addRawVector(valueVector); } private void addRawVector(IntVector valueVector) { for (int valuesPosition = 0; valuesPosition < valueVector.getPositionCount(); valuesPosition++) { int valueValue = valueVector.getInt(valuesPosition); SampleIntAggregator.combine(state, valueValue); } } private void addRawVector(IntVector valueVector, BooleanVector mask) { for (int valuesPosition = 0; valuesPosition < valueVector.getPositionCount(); valuesPosition++) { if (mask.getBoolean(valuesPosition) == false) { continue; } int valueValue = valueVector.getInt(valuesPosition); SampleIntAggregator.combine(state, valueValue); } } private void addRawBlock(IntBlock valueBlock) { for (int p = 0; p < valueBlock.getPositionCount(); p++) { int valueValueCount = valueBlock.getValueCount(p); if (valueValueCount == 0) { continue; } int valueStart = valueBlock.getFirstValueIndex(p); int valueEnd = valueStart + valueValueCount; for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) { int valueValue = valueBlock.getInt(valueOffset); SampleIntAggregator.combine(state, valueValue); } } } private void addRawBlock(IntBlock valueBlock, BooleanVector mask) { for (int p = 0; p < valueBlock.getPositionCount(); p++) { if (mask.getBoolean(p) == false) { continue; } int valueValueCount = valueBlock.getValueCount(p); if (valueValueCount == 0) { continue; } int valueStart = valueBlock.getFirstValueIndex(p); int valueEnd = valueStart + valueValueCount; for (int valueOffset = valueStart; valueOffset < valueEnd; valueOffset++) { int valueValue = valueBlock.getInt(valueOffset); SampleIntAggregator.combine(state, valueValue); } } } @Override public void addIntermediateInput(Page page) { assert channels.size() == intermediateBlockCount(); assert page.getBlockCount() >= channels.get(0) + intermediateStateDesc().size(); Block sampleUncast = page.getBlock(channels.get(0)); if (sampleUncast.areAllValuesNull()) { return; } BytesRefBlock sample = (BytesRefBlock) sampleUncast; assert sample.getPositionCount() == 1; BytesRef sampleScratch = new BytesRef(); SampleIntAggregator.combineIntermediate(state, sample); } @Override public void evaluateIntermediate(Block[] blocks, int offset, DriverContext driverContext) { state.toIntermediate(blocks, offset, driverContext); } @Override public void evaluateFinal(Block[] blocks, int offset, DriverContext driverContext) { blocks[offset] = SampleIntAggregator.evaluateFinal(state, driverContext); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("["); sb.append("channels=").append(channels); sb.append("]"); return sb.toString(); } @Override public void close() { state.close(); } }
SampleIntAggregatorFunction
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/localizer/event/ResourceLocalizedEvent.java
{ "start": 1016, "end": 1431 }
class ____ extends ResourceEvent { private final long size; private final Path location; public ResourceLocalizedEvent(LocalResourceRequest rsrc, Path location, long size) { super(rsrc, ResourceEventType.LOCALIZED); this.size = size; this.location = location; } public Path getLocation() { return location; } public long getSize() { return size; } }
ResourceLocalizedEvent
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/defaultmethod/DefaultMethodBean.java
{ "start": 147, "end": 356 }
class ____ implements DefaultMethodInterface { @NextBinding public String hello() { return "hello"; } @Override public String ping() { return "pong"; } }
DefaultMethodBean
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/test/TestGenericTestUtils.java
{ "start": 4039, "end": 5149 }
interface ____ { waitFor(null, 0, 0); } catch (NullPointerException e) { assertExceptionContains(GenericTestUtils.ERROR_MISSING_ARGUMENT, e); } Supplier<Boolean> simpleSupplier = new Supplier<Boolean>() { @Override public Boolean get() { return true; } }; // test waitFor method with waitForMillis greater than checkEveryMillis waitFor(simpleSupplier, 5, 10); try { // test waitFor method with waitForMillis smaller than checkEveryMillis waitFor(simpleSupplier, 10, 5); fail( "Excepted a failure when the param value of" + " waitForMillis is smaller than checkEveryMillis."); } catch (IllegalArgumentException e) { assertExceptionContains(GenericTestUtils.ERROR_INVALID_ARGUMENT, e); } } @Test public void testToLevel() throws Throwable { assertEquals(Level.INFO, toLevel("INFO")); assertEquals(Level.DEBUG, toLevel("NonExistLevel")); assertEquals(Level.INFO, toLevel("INFO", Level.TRACE)); assertEquals(Level.TRACE, toLevel("NonExistLevel", Level.TRACE)); } }
try
java
apache__hadoop
hadoop-common-project/hadoop-registry/src/main/java/org/apache/hadoop/registry/server/dns/BaseServiceRecordProcessor.java
{ "start": 7740, "end": 9884 }
class ____<T> extends RecordDescriptor<T> { public ContainerRecordDescriptor(String path, ServiceRecord record) throws Exception { super(record); init(record); } /** * Returns the DNS name constructed from the YARN container ID. * * @return the container ID name. * @throws TextParseException */ protected Name getContainerIDName() throws TextParseException { String containerID = RegistryPathUtils.lastPathEntry(getPath()); return Name.fromString(String.format("%s.%s", containerID, domain)); } /** * Returns the DNS name constructed from the container role/component name. * * @return the DNS naem. * @throws PathNotFoundException * @throws TextParseException */ protected Name getContainerName() throws PathNotFoundException, TextParseException { String service = RegistryPathUtils.lastPathEntry( RegistryPathUtils.parentOf(RegistryPathUtils.parentOf(getPath()))); String description = getRecord().description.toLowerCase(); String user = RegistryPathUtils.getUsername(getPath()); return Name.fromString(MessageFormat.format("{0}.{1}.{2}.{3}", description, service, user, domain)); } /** * Return the DNS name constructed from the component name. * * @return the DNS naem. * @throws PathNotFoundException * @throws TextParseException */ protected Name getComponentName() throws PathNotFoundException, TextParseException { String service = RegistryPathUtils.lastPathEntry( RegistryPathUtils.parentOf(RegistryPathUtils.parentOf(getPath()))); String component = getRecord().get("yarn:component").toLowerCase(); String user = RegistryPathUtils.getUsername(getPath()); return Name.fromString(MessageFormat.format("{0}.{1}.{2}.{3}", component, service, user, domain)); } } /** * An application-based DNS record descriptor. * * @param <T> the DNS record type/class. */ abstract
ContainerRecordDescriptor
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/bug/Bug_for_kongmu.java
{ "start": 1937, "end": 2258 }
class ____ { private String type; public Toy() { this.type = "toyType"; } public String getType() { return type; } public void setType(String type) { this.type = type; } } } }
Toy
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/api/serialization/PagedViewsTest.java
{ "start": 8678, "end": 9562 }
class ____ extends AbstractPagedOutputView { private final List<SegmentWithPosition> segments = new ArrayList<>(); private final int segmentSize; private TestOutputView(int segmentSize) { super(MemorySegmentFactory.allocateUnpooledSegment(segmentSize), segmentSize, 0); this.segmentSize = segmentSize; } @Override protected MemorySegment nextSegment(MemorySegment current, int positionInCurrent) throws IOException { segments.add(new SegmentWithPosition(current, positionInCurrent)); return MemorySegmentFactory.allocateUnpooledSegment(segmentSize); } public void close() { segments.add( new SegmentWithPosition(getCurrentSegment(), getCurrentPositionInSegment())); } } private static final
TestOutputView
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/generated/delegate/MutationDelegateIdentityTest.java
{ "start": 9540, "end": 9847 }
class ____ { @Id @GeneratedValue( strategy = GenerationType.IDENTITY ) private Long id; private String name; public Long getId() { return id; } public String getName() { return name; } } @Entity( name = "IdentityAndValues" ) @SuppressWarnings( "unused" ) public static
IdentityOnly