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
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnicodeEscapeTest.java
{ "start": 4326, "end": 4416 }
class ____ {} """) .expectUnchanged() .doTest(TEXT_MATCH); } }
A
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/time/JavaDurationWithNanosTest.java
{ "start": 877, "end": 1226 }
class ____ { private final CompilationTestHelper helper = CompilationTestHelper.newInstance(JavaDurationWithNanos.class, getClass()); @Test public void durationWithNanos() { helper .addSourceLines( "TestClass.java", """ import java.time.Duration; public
JavaDurationWithNanosTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/aggregations/bucket/terms/LongTermsTests.java
{ "start": 932, "end": 6210 }
class ____ extends InternalTermsTestCase { @Override protected InternalTerms<?, ?> createTestInstance( String name, Map<String, Object> metadata, InternalAggregations aggregations, boolean showTermDocCountError, long docCountError ) { BucketOrder order = BucketOrder.count(false); long minDocCount = 1; int requiredSize = 3; int shardSize = requiredSize + 2; DocValueFormat format = randomNumericDocValueFormat(); long otherDocCount = 0; List<LongTerms.Bucket> buckets = new ArrayList<>(); final int numBuckets = randomNumberOfBuckets(); Set<Long> terms = new HashSet<>(); for (int i = 0; i < numBuckets; ++i) { long term = randomValueOtherThanMany(l -> terms.add(l) == false, random()::nextLong); int docCount = randomIntBetween(1, 100); buckets.add(new LongTerms.Bucket(term, docCount, aggregations, showTermDocCountError, docCountError, format)); } BucketOrder reduceOrder = rarely() ? order : BucketOrder.key(true); Collections.sort(buckets, reduceOrder.comparator()); return new LongTerms( name, reduceOrder, order, requiredSize, minDocCount, metadata, format, shardSize, showTermDocCountError, otherDocCount, buckets, docCountError ); } @Override protected InternalTerms<?, ?> mutateInstance(InternalTerms<?, ?> instance) { if (instance instanceof LongTerms longTerms) { String name = longTerms.getName(); BucketOrder order = longTerms.order; int requiredSize = longTerms.requiredSize; long minDocCount = longTerms.minDocCount; DocValueFormat format = longTerms.format; int shardSize = longTerms.getShardSize(); boolean showTermDocCountError = longTerms.showTermDocCountError; long otherDocCount = longTerms.getSumOfOtherDocCounts(); List<LongTerms.Bucket> buckets = longTerms.getBuckets(); long docCountError = longTerms.getDocCountError(); Map<String, Object> metadata = longTerms.getMetadata(); switch (between(0, 8)) { case 0 -> name += randomAlphaOfLength(5); case 1 -> requiredSize += between(1, 100); case 2 -> minDocCount += between(1, 100); case 3 -> shardSize += between(1, 100); case 4 -> showTermDocCountError = showTermDocCountError == false; case 5 -> otherDocCount += between(1, 100); case 6 -> docCountError += between(1, 100); case 7 -> { buckets = new ArrayList<>(buckets); buckets.add( new LongTerms.Bucket( randomLong(), randomNonNegativeLong(), InternalAggregations.EMPTY, showTermDocCountError, docCountError, format ) ); } case 8 -> { if (metadata == null) { metadata = Maps.newMapWithExpectedSize(1); } else { metadata = new HashMap<>(instance.getMetadata()); } metadata.put(randomAlphaOfLength(15), randomInt()); } default -> throw new AssertionError("Illegal randomisation branch"); } Collections.sort(buckets, longTerms.reduceOrder.comparator()); return new LongTerms( name, longTerms.reduceOrder, order, requiredSize, minDocCount, metadata, format, shardSize, showTermDocCountError, otherDocCount, buckets, docCountError ); } else { String name = instance.getName(); BucketOrder order = instance.order; int requiredSize = instance.requiredSize; long minDocCount = instance.minDocCount; Map<String, Object> metadata = instance.getMetadata(); switch (between(0, 3)) { case 0 -> name += randomAlphaOfLength(5); case 1 -> requiredSize += between(1, 100); case 2 -> minDocCount += between(1, 100); case 3 -> { if (metadata == null) { metadata = Maps.newMapWithExpectedSize(1); } else { metadata = new HashMap<>(instance.getMetadata()); } metadata.put(randomAlphaOfLength(15), randomInt()); } default -> throw new AssertionError("Illegal randomisation branch"); } return new UnmappedTerms(name, order, requiredSize, minDocCount, metadata); } } }
LongTermsTests
java
processing__processing4
app/ant/processing/app/Schema.java
{ "start": 135, "end": 240 }
class ____ not used in the Gradle build system // The actual implementation is in src/.../Schema.kt public
is
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/test/java/org/apache/hadoop/yarn/client/api/impl/TestYarnClient.java
{ "start": 6181, "end": 12424 }
class ____ extends ParameterizedSchedulerTestBase { public void initTestYarnClient(SchedulerType type) throws IOException { initParameterizedSchedulerTestBase(type); setup(); } protected void configureFairScheduler(YarnConfiguration conf) {} public void setup() { QueueMetrics.clearQueueMetrics(); DefaultMetricsSystem.setMiniClusterMode(true); } @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testClientStop(SchedulerType type) throws IOException { initTestYarnClient(type); Configuration conf = getConf(); ResourceManager rm = new ResourceManager(); rm.init(conf); rm.start(); YarnClient client = YarnClient.createYarnClient(); client.init(conf); client.start(); client.stop(); rm.stop(); } @ParameterizedTest(name = "{0}") @MethodSource("getParameters") public void testStartTimelineClientWithErrors(SchedulerType type) throws Exception { initTestYarnClient(type); // If timeline client failed to init with a NoClassDefFoundError // it should be wrapped with an informative error message testCreateTimelineClientWithError( 1.5f, true, false, new NoClassDefFoundError("Mock a NoClassDefFoundError"), new CreateTimelineClientErrorVerifier(1) { @Override public void verifyError(Throwable e) { assertTrue(e instanceof NoClassDefFoundError); assertTrue(e.getMessage() != null && e.getMessage().contains(YarnConfiguration.TIMELINE_SERVICE_ENABLED)); } }); // Disable timeline service for this client, // yarn client will not fail when such error happens testCreateTimelineClientWithError( 1.5f, false, false, new NoClassDefFoundError("Mock a NoClassDefFoundError"), new CreateTimelineClientErrorVerifier(0) { @Override public void verifyError(Throwable e) { fail("NoClassDefFoundError while creating timeline client" + "should be tolerated when timeline service is disabled."); } } ); // Set best-effort to true, verify an error is still fatal testCreateTimelineClientWithError( 1.5f, true, true, new NoClassDefFoundError("Mock a NoClassDefFoundError"), new CreateTimelineClientErrorVerifier(1) { @Override public void verifyError(Throwable e) { assertTrue(e instanceof NoClassDefFoundError); assertTrue(e.getMessage() != null && e.getMessage().contains(YarnConfiguration.TIMELINE_SERVICE_ENABLED)); } } ); // Set best-effort to false, verify that an exception // causes the client to fail testCreateTimelineClientWithError( 1.5f, true, false, new IOException("ATS v1.5 client initialization failed."), new CreateTimelineClientErrorVerifier(1) { @Override public void verifyError(Throwable e) { assertTrue(e instanceof IOException); } } ); // Set best-effort to true, verify that an normal exception // won't fail the entire client testCreateTimelineClientWithError( 1.5f, true, true, new IOException("ATS v1.5 client initialization failed."), new CreateTimelineClientErrorVerifier(0) { @Override public void verifyError(Throwable e) { fail("IOException while creating timeline client" + "should be tolerated when best effort is true"); } } ); } @SuppressWarnings("deprecation") @ParameterizedTest(name = "{0}") @MethodSource("getParameters") @Timeout(value = 30) public void testSubmitApplication(SchedulerType type) throws Exception { initTestYarnClient(type); Configuration conf = getConf(); conf.setLong(YarnConfiguration.YARN_CLIENT_APP_SUBMISSION_POLL_INTERVAL_MS, 100); // speed up tests final YarnClient client = new MockYarnClient(); client.init(conf); client.start(); YarnApplicationState[] exitStates = new YarnApplicationState[] { YarnApplicationState.ACCEPTED, YarnApplicationState.RUNNING, YarnApplicationState.FINISHED }; // Submit an application without ApplicationId provided // Should get ApplicationIdNotProvidedException ApplicationSubmissionContext contextWithoutApplicationId = mock(ApplicationSubmissionContext.class); try { client.submitApplication(contextWithoutApplicationId); fail("Should throw the ApplicationIdNotProvidedException"); } catch (YarnException e) { assertTrue(e instanceof ApplicationIdNotProvidedException); assertTrue(e.getMessage().contains( "ApplicationId is not provided in ApplicationSubmissionContext")); } // Submit the application with applicationId provided // Should be successful for (int i = 0; i < exitStates.length; ++i) { ApplicationSubmissionContext context = mock(ApplicationSubmissionContext.class); ApplicationId applicationId = ApplicationId.newInstance( System.currentTimeMillis(), i); when(context.getApplicationId()).thenReturn(applicationId); ((MockYarnClient) client).setYarnApplicationState(exitStates[i]); client.submitApplication(context); verify(((MockYarnClient) client).mockReport,times(4 * i + 4)) .getYarnApplicationState(); } client.stop(); } @SuppressWarnings("deprecation") @ParameterizedTest(name = "{0}") @MethodSource("getParameters") @Timeout(value = 20) public void testSubmitApplicationInterrupted(SchedulerType type) throws IOException { initTestYarnClient(type); Configuration conf = getConf(); int pollIntervalMs = 1000; conf.setLong(YarnConfiguration.YARN_CLIENT_APP_SUBMISSION_POLL_INTERVAL_MS, pollIntervalMs); try (YarnClient client = new MockYarnClient()) { client.init(conf); client.start(); // Submit the application and then interrupt it while its waiting // for submission to be successful. final
TestYarnClient
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/main/java/io/quarkus/vertx/http/deployment/webjar/WebJarResourcesTargetVisitor.java
{ "start": 114, "end": 407 }
interface ____ { default void visitDirectory(String path) throws IOException { } default void visitFile(String path, InputStream stream) throws IOException { } default boolean supportsOnlyCopyingNonArtifactFiles() { return false; } }
WebJarResourcesTargetVisitor
java
quarkusio__quarkus
extensions/oidc-client/deployment/src/main/java/io/quarkus/oidc/client/deployment/OidcClientBuildStep.java
{ "start": 6379, "end": 8586 }
class ____ extends AbstractTokensProducer { * &#64;Produces * &#64;NamedOidcClient("oidcClientName") * &#64;RequestScoped * public Tokens produceTokens() { * return awaitTokens(); * } * * &#64;Override * protected Optional<String> clientId() { * return Optional.of("oidcClientName"); * } * } * </pre> */ private String createNamedTokensProducerFor(ClassOutput classOutput, String targetPackage, String oidcClientName) { String generatedName = targetPackage + "TokensProducer_" + sanitize(oidcClientName); try (ClassCreator tokensProducer = ClassCreator.builder().classOutput(classOutput).className(generatedName) .superClass(AbstractTokensProducer.class) .build()) { tokensProducer.addAnnotation(DotNames.SINGLETON.toString()); try (MethodCreator produceMethod = tokensProducer.getMethodCreator("produceTokens", Tokens.class)) { produceMethod.setModifiers(Modifier.PUBLIC); produceMethod.addAnnotation(DotNames.PRODUCES.toString()); produceMethod.addAnnotation(NamedOidcClient.class.getName()).addValue("value", oidcClientName); produceMethod.addAnnotation(RequestScoped.class.getName()); ResultHandle tokensResult = produceMethod.invokeVirtualMethod( MethodDescriptor.ofMethod(AbstractTokensProducer.class, "awaitTokens", Tokens.class), produceMethod.getThis()); produceMethod.returnValue(tokensResult); } try (MethodCreator clientIdMethod = tokensProducer.getMethodCreator("clientId", Optional.class)) { clientIdMethod.setModifiers(Modifier.PROTECTED); clientIdMethod.returnValue(clientIdMethod.invokeStaticMethod( MethodDescriptor.ofMethod(Optional.class, "of", Optional.class, Object.class), clientIdMethod.load(oidcClientName))); } } return generatedName.replace('/', '.'); } public static
TokensProducer_oidcClientName
java
apache__hadoop
hadoop-tools/hadoop-compat-bench/src/test/java/org/apache/hadoop/fs/compat/common/TestHdfsCompatFsCommand.java
{ "start": 1435, "end": 3506 }
class ____ { @Test public void testDfsCompatibility() throws Exception { final String suite = "ALL"; HdfsCompatMiniCluster cluster = null; try { cluster = new HdfsCompatMiniCluster(); cluster.start(); final String uri = cluster.getUri() + "/tmp"; final Configuration conf = cluster.getConf(); HdfsCompatCommand cmd = new TestCommand(uri, suite, conf); cmd.initialize(); HdfsCompatReport report = cmd.apply(); assertEquals(7, report.getPassedCase().size()); assertEquals(0, report.getFailedCase().size()); show(conf, report); } finally { if (cluster != null) { cluster.shutdown(); } } } @Test public void testLocalFsCompatibility() throws Exception { final String uri = "file:///tmp/"; final String suite = "ALL"; final Configuration conf = new Configuration(); HdfsCompatCommand cmd = new TestCommand(uri, suite, conf); cmd.initialize(); HdfsCompatReport report = cmd.apply(); assertEquals(1, report.getPassedCase().size()); assertEquals(6, report.getFailedCase().size()); show(conf, report); cleanup(cmd, conf); } @Test public void testFsCompatibilityWithSuite() throws Exception { final String uri = "file:///tmp/"; final String suite = "acl"; final Configuration conf = new Configuration(); HdfsCompatCommand cmd = new TestCommand(uri, suite, conf); cmd.initialize(); HdfsCompatReport report = cmd.apply(); assertEquals(0, report.getPassedCase().size()); assertEquals(6, report.getFailedCase().size()); show(conf, report); cleanup(cmd, conf); } private void show(Configuration conf, HdfsCompatReport report) throws IOException { new HdfsCompatTool(conf).printReport(report, System.out); } private void cleanup(HdfsCompatCommand cmd, Configuration conf) throws Exception { Path basePath = ((TestCommand) cmd).getBasePath(); FileSystem fs = basePath.getFileSystem(conf); fs.delete(basePath, true); } private static final
TestHdfsCompatFsCommand
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/TaskExecutorLocalStateStoresManagerTest.java
{ "start": 2477, "end": 18759 }
class ____ { @TempDir public static File temporaryFolder; @RegisterExtension public static final AllCallbackWrapper<WorkingDirectoryExtension> WORKING_DIRECTORY_EXTENSION_WRAPPER = new AllCallbackWrapper<>(new WorkingDirectoryExtension(() -> temporaryFolder)); /** * This tests that the creation of {@link TaskManagerServices} correctly creates the local state * root directory for the {@link TaskExecutorLocalStateStoresManager} with the configured root * directory. */ @Test void testCreationFromConfig() throws Exception { final Configuration config = new Configuration(); File newFolder = TempDirUtils.newFolder(temporaryFolder.toPath()); String tmpDir = newFolder.getAbsolutePath() + File.separator; final String rootDirString = "__localStateRoot1,__localStateRoot2,__localStateRoot3".replaceAll("__", tmpDir); // test configuration of the local state directories config.set(CheckpointingOptions.LOCAL_RECOVERY_TASK_MANAGER_STATE_ROOT_DIRS, rootDirString); // test configuration of the local state mode config.set(StateRecoveryOptions.LOCAL_RECOVERY, true); final WorkingDirectory workingDirectory = WORKING_DIRECTORY_EXTENSION_WRAPPER .getCustomExtension() .createNewWorkingDirectory(); TaskManagerServices taskManagerServices = createTaskManagerServices( createTaskManagerServiceConfiguration(config, workingDirectory), workingDirectory); try { TaskExecutorLocalStateStoresManager taskStateManager = taskManagerServices.getTaskManagerStateStore(); // verify configured directories for local state String[] split = rootDirString.split(","); File[] rootDirectories = taskStateManager.getLocalStateRootDirectories(); for (int i = 0; i < split.length; ++i) { assertThat(rootDirectories[i].toPath()).startsWith(Paths.get(split[i])); } // verify local recovery mode assertThat(taskStateManager.isLocalRecoveryEnabled()).isTrue(); for (File rootDirectory : rootDirectories) { FileUtils.deleteFileOrDirectory(rootDirectory); } } finally { taskManagerServices.shutDown(); } } /** * This tests that the creation of {@link TaskManagerServices} correctly falls back to the first * tmp directory of the IOManager as default for the local state root directory. */ @Test void testCreationFromConfigDefault() throws Exception { final Configuration config = new Configuration(); final WorkingDirectory workingDirectory = WORKING_DIRECTORY_EXTENSION_WRAPPER .getCustomExtension() .createNewWorkingDirectory(); TaskManagerServicesConfiguration taskManagerServicesConfiguration = createTaskManagerServiceConfiguration(config, workingDirectory); TaskManagerServices taskManagerServices = createTaskManagerServices(taskManagerServicesConfiguration, workingDirectory); try { TaskExecutorLocalStateStoresManager taskStateManager = taskManagerServices.getTaskManagerStateStore(); File[] localStateRootDirectories = taskStateManager.getLocalStateRootDirectories(); for (int i = 0; i < localStateRootDirectories.length; ++i) { assertThat(localStateRootDirectories[i]) .isEqualTo(workingDirectory.getLocalStateDirectory()); } assertThat(taskStateManager.isLocalRecoveryEnabled()).isFalse(); } finally { taskManagerServices.shutDown(); } } @Test void testLocalStateNoCreateDirWhenDisabledLocalBackupAndRecovery() throws Exception { JobID jobID = new JobID(); JobVertexID jobVertexID = new JobVertexID(); AllocationID allocationID = new AllocationID(); int subtaskIdx = 23; File[] rootDirs = { TempDirUtils.newFolder(temporaryFolder.toPath()), TempDirUtils.newFolder(temporaryFolder.toPath()), TempDirUtils.newFolder(temporaryFolder.toPath()) }; boolean localRecoveryEnabled = false; boolean localBackupEnabled = false; TaskExecutorLocalStateStoresManager storesManager = new TaskExecutorLocalStateStoresManager( localRecoveryEnabled, localBackupEnabled, Reference.owned(rootDirs), Executors.directExecutor()); TaskLocalStateStore taskLocalStateStore = storesManager.localStateStoreForSubtask( jobID, allocationID, jobVertexID, subtaskIdx, new Configuration(), new Configuration()); assertThat(taskLocalStateStore.getLocalRecoveryConfig().isLocalRecoveryEnabled()).isFalse(); assertThat(taskLocalStateStore.getLocalRecoveryConfig().getLocalStateDirectoryProvider()) .isNotPresent(); for (File recoveryDir : rootDirs) { assertThat(recoveryDir).isEmptyDirectory(); } } /** * This tests that the {@link TaskExecutorLocalStateStoresManager} creates {@link * TaskLocalStateStoreImpl} that have a properly initialized local state base directory. It also * checks that subdirectories are correctly deleted on shutdown. */ @Test void testSubtaskStateStoreDirectoryCreateAndDelete() throws Exception { testSubtaskStateStoreDirectoryCreateAndDelete(true, true); } @Test void testStateStoreDirectoryCreateAndDeleteWithLocalRecoveryEnabled() throws Exception { testSubtaskStateStoreDirectoryCreateAndDelete(true, false); } @Test void testStateStoreDirectoryCreateAndDeleteWithLocalBackupEnabled() throws Exception { testSubtaskStateStoreDirectoryCreateAndDelete(false, true); } private void testSubtaskStateStoreDirectoryCreateAndDelete( boolean localRecoveryEnabled, boolean localBackupEnabled) throws Exception { JobID jobID = new JobID(); JobVertexID jobVertexID = new JobVertexID(); AllocationID allocationID = new AllocationID(); int subtaskIdx = 23; File[] rootDirs = { TempDirUtils.newFolder(temporaryFolder.toPath()), TempDirUtils.newFolder(temporaryFolder.toPath()), TempDirUtils.newFolder(temporaryFolder.toPath()) }; TaskExecutorLocalStateStoresManager storesManager = new TaskExecutorLocalStateStoresManager( localRecoveryEnabled, localBackupEnabled, Reference.owned(rootDirs), Executors.directExecutor()); TaskLocalStateStore taskLocalStateStore = storesManager.localStateStoreForSubtask( jobID, allocationID, jobVertexID, subtaskIdx, new Configuration(), new Configuration()); LocalSnapshotDirectoryProvider directoryProvider = taskLocalStateStore .getLocalRecoveryConfig() .getLocalStateDirectoryProvider() .orElseThrow(LocalRecoveryConfig.localRecoveryNotEnabled()); for (int i = 0; i < 10; ++i) { assertThat( new File( rootDirs[(i & Integer.MAX_VALUE) % rootDirs.length], storesManager.allocationSubDirString(allocationID))) .isEqualTo(directoryProvider.allocationBaseDirectory(i)); } long chkId = 42L; File allocBaseDirChk42 = directoryProvider.allocationBaseDirectory(chkId); File subtaskSpecificCheckpointDirectory = directoryProvider.subtaskSpecificCheckpointDirectory(chkId); assertThat( new File( allocBaseDirChk42, "jid_" + jobID + File.separator + "vtx_" + jobVertexID + "_" + "sti_" + subtaskIdx + File.separator + "chk_" + chkId)) .isEqualTo(subtaskSpecificCheckpointDirectory); assertThat(subtaskSpecificCheckpointDirectory.mkdirs()).isTrue(); File testFile = new File(subtaskSpecificCheckpointDirectory, "test"); assertThat(testFile.createNewFile()).isTrue(); // test that local recovery mode is forwarded to the created store assertThat(taskLocalStateStore.getLocalRecoveryConfig().isLocalRecoveryEnabled()) .isEqualTo(storesManager.isLocalRecoveryEnabled()); assertThat(testFile).exists(); // check cleanup after releasing allocation id storesManager.releaseLocalStateForAllocationId(allocationID); checkRootDirsClean(rootDirs); AllocationID otherAllocationID = new AllocationID(); taskLocalStateStore = storesManager.localStateStoreForSubtask( jobID, otherAllocationID, jobVertexID, subtaskIdx, new Configuration(), new Configuration()); directoryProvider = taskLocalStateStore .getLocalRecoveryConfig() .getLocalStateDirectoryProvider() .orElseThrow(LocalRecoveryConfig.localRecoveryNotEnabled()); File chkDir = directoryProvider.subtaskSpecificCheckpointDirectory(23L); assertThat(chkDir.mkdirs()).isTrue(); testFile = new File(chkDir, "test"); assertThat(testFile.createNewFile()).isTrue(); // check cleanup after shutdown storesManager.shutdown(); checkRootDirsClean(rootDirs); } @Test void testOwnedLocalStateDirectoriesAreDeletedOnShutdown() throws IOException { final File localStateStoreA = TempDirUtils.newFolder(temporaryFolder.toPath()); final File localStateStoreB = TempDirUtils.newFolder(temporaryFolder.toPath()); final File[] localStateDirectories = {localStateStoreA, localStateStoreB}; final TaskExecutorLocalStateStoresManager taskExecutorLocalStateStoresManager = new TaskExecutorLocalStateStoresManager( true, true, Reference.owned(localStateDirectories), Executors.directExecutor()); for (File localStateDirectory : localStateDirectories) { assertThat(localStateDirectory).exists(); } taskExecutorLocalStateStoresManager.shutdown(); for (File localStateDirectory : localStateDirectories) { assertThat(localStateDirectory).doesNotExist(); } } @Test void testBorrowedLocalStateDirectoriesAreNotDeletedOnShutdown() throws IOException { final File localStateStoreA = TempDirUtils.newFolder(temporaryFolder.toPath()); final File localStateStoreB = TempDirUtils.newFolder(temporaryFolder.toPath()); final File[] localStateDirectories = {localStateStoreA, localStateStoreB}; final TaskExecutorLocalStateStoresManager taskExecutorLocalStateStoresManager = new TaskExecutorLocalStateStoresManager( true, true, Reference.borrowed(localStateDirectories), Executors.directExecutor()); for (File localStateDirectory : localStateDirectories) { assertThat(localStateDirectory).exists(); } taskExecutorLocalStateStoresManager.shutdown(); for (File localStateDirectory : localStateDirectories) { assertThat(localStateDirectory).exists(); } } @Test void testRetainLocalStateForAllocationsDeletesUnretainedAllocationDirectories() throws IOException { final File localStateStore = TempDirUtils.newFolder(temporaryFolder.toPath()); final TaskExecutorLocalStateStoresManager taskExecutorLocalStateStoresManager = new TaskExecutorLocalStateStoresManager( true, true, Reference.owned(new File[] {localStateStore}), Executors.directExecutor()); final JobID jobId = new JobID(); final AllocationID retainedAllocationId = new AllocationID(); final AllocationID otherAllocationId = new AllocationID(); final JobVertexID jobVertexId = new JobVertexID(); // register local state stores taskExecutorLocalStateStoresManager.localStateStoreForSubtask( jobId, retainedAllocationId, jobVertexId, 0, new Configuration(), new Configuration()); taskExecutorLocalStateStoresManager.localStateStoreForSubtask( jobId, otherAllocationId, jobVertexId, 1, new Configuration(), new Configuration()); final Collection<Path> allocationDirectories = TaskExecutorLocalStateStoresManager.listAllocationDirectoriesIn(localStateStore); assertThat(allocationDirectories).hasSize(2); taskExecutorLocalStateStoresManager.retainLocalStateForAllocations( Sets.newHashSet(retainedAllocationId)); final Collection<Path> allocationDirectoriesAfterCleanup = TaskExecutorLocalStateStoresManager.listAllocationDirectoriesIn(localStateStore); assertThat(allocationDirectoriesAfterCleanup).hasSize(1); assertThat( new File( localStateStore, taskExecutorLocalStateStoresManager.allocationSubDirString( otherAllocationId))) .doesNotExist(); } private void checkRootDirsClean(File[] rootDirs) { for (File rootDir : rootDirs) { File[] files = rootDir.listFiles(); if (files != null) { assertThat(files).isEmpty(); } } } private TaskManagerServicesConfiguration createTaskManagerServiceConfiguration( Configuration config, WorkingDirectory workingDirectory) throws Exception { return TaskManagerServicesConfiguration.fromConfiguration( config, ResourceID.generate(), InetAddress.getLocalHost().getHostName(), true, TaskExecutorResourceUtils.resourceSpecFromConfigForLocalExecution(config), workingDirectory); } private TaskManagerServices createTaskManagerServices( TaskManagerServicesConfiguration config, WorkingDirectory workingDirectory) throws Exception { return TaskManagerServices.fromConfiguration( config, VoidPermanentBlobService.INSTANCE, UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup(), Executors.newDirectExecutorService(), null, throwable -> {}, workingDirectory); } }
TaskExecutorLocalStateStoresManagerTest
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/function/BodyInserters.java
{ "start": 22458, "end": 23181 }
interface ____<T> extends BodyInserter<MultiValueMap<String, T>, ClientHttpRequest> { // FormInserter is parameterized to ClientHttpRequest (for client-side use only) /** * Adds the specified key-value pair to the form. * @param key the key to be added * @param value the value to be added * @return this inserter for adding more parts */ FormInserter<T> with(String key, T value); /** * Adds the specified values to the form. * @param values the values to be added * @return this inserter for adding more parts */ FormInserter<T> with(MultiValueMap<String, T> values); } /** * Extension of {@link FormInserter} that allows for adding asynchronous parts. */ public
FormInserter
java
apache__dubbo
dubbo-config/dubbo-config-spring/src/test/java/org/apache/dubbo/config/spring/reference/localcall/LocalCallTest2.java
{ "start": 1916, "end": 2640 }
class ____ { @BeforeAll public static void setUp() { DubboBootstrap.reset(); } @AfterAll public static void tearDown() { DubboBootstrap.reset(); } @DubboReference private HelloService helloService; @Autowired private ApplicationContext applicationContext; @Test public void testLocalCall() { // see also: org.apache.dubbo.rpc.protocol.injvm.InjvmInvoker.doInvoke // InjvmInvoker set remote address to 127.0.0.1:0 String result = helloService.sayHello("world"); Assertions.assertEquals( "Hello world, response from provider: " + InetSocketAddress.createUnresolved("127.0.0.1", 0), result); } }
LocalCallTest2
java
netty__netty
handler/src/main/java/io/netty/handler/ssl/util/LazyJavaxX509Certificate.java
{ "start": 1230, "end": 4169 }
class ____ extends X509Certificate { private final byte[] bytes; private X509Certificate wrapped; /** * Creates a new instance which will lazy parse the given bytes. Be aware that the bytes will not be cloned. */ public LazyJavaxX509Certificate(byte[] bytes) { this.bytes = ObjectUtil.checkNotNull(bytes, "bytes"); } @Override public void checkValidity() throws CertificateExpiredException, CertificateNotYetValidException { unwrap().checkValidity(); } @Override public void checkValidity(Date date) throws CertificateExpiredException, CertificateNotYetValidException { unwrap().checkValidity(date); } @Override public int getVersion() { return unwrap().getVersion(); } @Override public BigInteger getSerialNumber() { return unwrap().getSerialNumber(); } @Override public Principal getIssuerDN() { return unwrap().getIssuerDN(); } @Override public Principal getSubjectDN() { return unwrap().getSubjectDN(); } @Override public Date getNotBefore() { return unwrap().getNotBefore(); } @Override public Date getNotAfter() { return unwrap().getNotAfter(); } @Override public String getSigAlgName() { return unwrap().getSigAlgName(); } @Override public String getSigAlgOID() { return unwrap().getSigAlgOID(); } @Override public byte[] getSigAlgParams() { return unwrap().getSigAlgParams(); } @Override public byte[] getEncoded() { return bytes.clone(); } /** * Return the underyling {@code byte[]} without cloning it first. This {@code byte[]} <strong>must</strong> never * be mutated. */ byte[] getBytes() { return bytes; } @Override public void verify(PublicKey key) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { unwrap().verify(key); } @Override public void verify(PublicKey key, String sigProvider) throws CertificateException, NoSuchAlgorithmException, InvalidKeyException, NoSuchProviderException, SignatureException { unwrap().verify(key, sigProvider); } @Override public String toString() { return unwrap().toString(); } @Override public PublicKey getPublicKey() { return unwrap().getPublicKey(); } private X509Certificate unwrap() { X509Certificate wrapped = this.wrapped; if (wrapped == null) { try { wrapped = this.wrapped = X509Certificate.getInstance(bytes); } catch (CertificateException e) { throw new IllegalStateException(e); } } return wrapped; } }
LazyJavaxX509Certificate
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/UserMetricsInfo.java
{ "start": 1382, "end": 4427 }
class ____ { protected int appsSubmitted; protected int appsCompleted; protected int appsPending; protected int appsRunning; protected int appsFailed; protected int appsKilled; protected int runningContainers; protected int pendingContainers; protected int reservedContainers; protected long reservedMB; protected long pendingMB; protected long allocatedMB; protected long reservedVirtualCores; protected long pendingVirtualCores; protected long allocatedVirtualCores; @XmlTransient protected boolean userMetricsAvailable; public UserMetricsInfo() { } // JAXB needs this public UserMetricsInfo(final ResourceManager rm, final String user) { ResourceScheduler rs = rm.getResourceScheduler(); QueueMetrics metrics = rs.getRootQueueMetrics(); QueueMetrics userMetrics = metrics.getUserMetrics(user); this.userMetricsAvailable = false; if (userMetrics != null) { this.userMetricsAvailable = true; this.appsSubmitted = userMetrics.getAppsSubmitted(); this.appsCompleted = userMetrics.getAppsCompleted(); this.appsPending = userMetrics.getAppsPending(); this.appsRunning = userMetrics.getAppsRunning(); this.appsFailed = userMetrics.getAppsFailed(); this.appsKilled = userMetrics.getAppsKilled(); this.runningContainers = userMetrics.getAllocatedContainers(); this.pendingContainers = userMetrics.getPendingContainers(); this.reservedContainers = userMetrics.getReservedContainers(); this.reservedMB = userMetrics.getReservedMB(); this.pendingMB = userMetrics.getPendingMB(); this.allocatedMB = userMetrics.getAllocatedMB(); this.reservedVirtualCores = userMetrics.getReservedVirtualCores(); this.pendingVirtualCores = userMetrics.getPendingVirtualCores(); this.allocatedVirtualCores = userMetrics.getAllocatedVirtualCores(); } } public boolean metricsAvailable() { return userMetricsAvailable; } public int getAppsSubmitted() { return this.appsSubmitted; } public int getAppsCompleted() { return appsCompleted; } public int getAppsPending() { return appsPending; } public int getAppsRunning() { return appsRunning; } public int getAppsFailed() { return appsFailed; } public int getAppsKilled() { return appsKilled; } public long getReservedMB() { return this.reservedMB; } public long getAllocatedMB() { return this.allocatedMB; } public long getPendingMB() { return this.pendingMB; } public long getReservedVirtualCores() { return this.reservedVirtualCores; } public long getAllocatedVirtualCores() { return this.allocatedVirtualCores; } public long getPendingVirtualCores() { return this.pendingVirtualCores; } public int getReservedContainers() { return this.reservedContainers; } public int getRunningContainers() { return this.runningContainers; } public int getPendingContainers() { return this.pendingContainers; } }
UserMetricsInfo
java
spring-projects__spring-boot
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/messaging/jms/sending/MyBean.java
{ "start": 803, "end": 1051 }
class ____ { private final JmsClient jmsClient; public MyBean(JmsClient jmsClient) { this.jmsClient = jmsClient; } // @fold:on // ... public void someMethod() { this.jmsClient.destination("myQueue").send("hello"); } // @fold:off }
MyBean
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/DeleteDataFrameAnalyticsAction.java
{ "start": 920, "end": 1384 }
class ____ extends ActionType<AcknowledgedResponse> { public static final DeleteDataFrameAnalyticsAction INSTANCE = new DeleteDataFrameAnalyticsAction(); public static final String NAME = "cluster:admin/xpack/ml/data_frame/analytics/delete"; public static final String DELETION_TASK_DESCRIPTION_PREFIX = "delete-analytics-"; private DeleteDataFrameAnalyticsAction() { super(NAME); } public static final
DeleteDataFrameAnalyticsAction
java
quarkusio__quarkus
test-framework/hibernate-reactive-panache/src/main/java/io/quarkus/test/hibernate/reactive/panache/TransactionalUniAsserter.java
{ "start": 446, "end": 767 }
class ____ extends UniAsserterInterceptor { TransactionalUniAsserter(UniAsserter asserter) { super(asserter); } @Override protected <T> Supplier<Uni<T>> transformUni(Supplier<Uni<T>> uniSupplier) { return () -> SessionOperations.withTransaction(uniSupplier); } }
TransactionalUniAsserter
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DoNotMockCheckerTest.java
{ "start": 13608, "end": 13821 }
class ____ {", " @Mock AnnotatedClass x;", "}") .withClasspath( AnnotatedClass.class, DoNotMockCheckerTest.class, DoNotMock.class, Mock.class) .doTest(); } }
Test
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/watcher/watch/ClockMock.java
{ "start": 516, "end": 2878 }
class ____ extends Clock { private volatile Clock wrappedClock; public ClockMock() { this(Clock.systemUTC()); } /** * a utility method to create a new {@link ClockMock} and immediately call its {@link #freeze()} method */ public static ClockMock frozen() { return new ClockMock().freeze(); } private ClockMock(Clock wrappedClock) { this.wrappedClock = wrappedClock; } @Override public ZoneId getZone() { return wrappedClock.getZone(); } @Override public synchronized Clock withZone(ZoneId zoneId) { if (zoneId.equals(wrappedClock.getZone())) { return this; } return new ClockMock(wrappedClock.withZone(zoneId)); } @Override public long millis() { return wrappedClock.millis(); } @Override public Instant instant() { return wrappedClock.instant(); } public synchronized void setTime(ZonedDateTime now) { setTime(now.toInstant()); } private void setTime(Instant now) { assert Thread.holdsLock(this); this.wrappedClock = Clock.fixed(now, getZone()); } /** freeze the time for this clock, preventing it from advancing */ public synchronized ClockMock freeze() { setTime(instant()); return this; } /** the clock will be reset to current time and will advance from now */ public synchronized ClockMock unfreeze() { wrappedClock = Clock.system(getZone()); return this; } /** freeze the clock if not frozen and advance it by the given time */ public synchronized void fastForward(TimeValue timeValue) { setTime(instant().plusMillis(timeValue.getMillis())); } /** freeze the clock if not frozen and advance it by the given amount of seconds */ public void fastForwardSeconds(int seconds) { fastForward(TimeValue.timeValueSeconds(seconds)); } /** freeze the clock if not frozen and rewind it by the given time */ public synchronized void rewind(TimeValue timeValue) { setTime(instant().minusMillis((int) timeValue.millis())); } /** freeze the clock if not frozen and rewind it by the given number of seconds */ public void rewindSeconds(int seconds) { rewind(TimeValue.timeValueSeconds(seconds)); } }
ClockMock
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/suggest/completion/context/CategoryQueryContext.java
{ "start": 1291, "end": 4540 }
class ____ implements ToXContentObject { public static final String NAME = "category"; private final String category; private final boolean isPrefix; private final int boost; private CategoryQueryContext(String category, int boost, boolean isPrefix) { this.category = category; this.boost = boost; this.isPrefix = isPrefix; } /** * Returns the category of the context */ public String getCategory() { return category; } /** * Returns if the context should be treated as a prefix */ public boolean isPrefix() { return isPrefix; } /** * Returns the query-time boost of the context */ public int getBoost() { return boost; } public static Builder builder() { return new Builder(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CategoryQueryContext that = (CategoryQueryContext) o; if (isPrefix != that.isPrefix) return false; if (boost != that.boost) return false; return Objects.equals(category, that.category); } @Override public int hashCode() { int result = category != null ? category.hashCode() : 0; result = 31 * result + (isPrefix ? 1 : 0); result = 31 * result + boost; return result; } private static final ObjectParser<Builder, Void> CATEGORY_PARSER = new ObjectParser<>(NAME); static { CATEGORY_PARSER.declareField( Builder::setCategory, XContentParser::text, new ParseField(CONTEXT_VALUE), ObjectParser.ValueType.VALUE ); CATEGORY_PARSER.declareInt(Builder::setBoost, new ParseField(CONTEXT_BOOST)); CATEGORY_PARSER.declareBoolean(Builder::setPrefix, new ParseField(CONTEXT_PREFIX)); } public static CategoryQueryContext fromXContent(XContentParser parser) throws IOException { XContentParser.Token token = parser.currentToken(); Builder builder = builder(); if (token == XContentParser.Token.START_OBJECT) { try { CATEGORY_PARSER.parse(parser, builder, null); } catch (XContentParseException e) { throw new XContentParseException("category context must be a string, number or boolean"); } } else if (token == XContentParser.Token.VALUE_STRING || token == XContentParser.Token.VALUE_BOOLEAN || token == XContentParser.Token.VALUE_NUMBER) { builder.setCategory(parser.text()); } else { throw new XContentParseException("category context must be an object, string, number or boolean"); } return builder.build(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(CONTEXT_VALUE, category); builder.field(CONTEXT_BOOST, boost); builder.field(CONTEXT_PREFIX, isPrefix); builder.endObject(); return builder; } public static
CategoryQueryContext
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/TruthIncompatibleTypeTest.java
{ "start": 13081, "end": 13624 }
class ____ { public void f(Map<String, Long> xs, Map<Long, Long> ys) { // BUG: Diagnostic contains: assertThat(xs).containsExactlyEntriesIn(ys); } } """) .doTest(); } @Test public void mapContainsExactlyEntriesIn_valueTypesDiffer() { compilationHelper .addSourceLines( "Test.java", """ import static com.google.common.truth.Truth.assertThat; import java.util.Map; public
Test
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/support/UserRoleMapper.java
{ "start": 1522, "end": 2253 }
interface ____ { /** * Determines the set of roles that should be applied to <code>user</code>. */ void resolveRoles(UserData user, ActionListener<Set<String>> listener); /** * Informs the mapper that the provided <code>realm</code> should be refreshed when * the set of role-mappings change. The realm may be updated for the local node only, or across * the whole cluster depending on whether this role-mapper has node-local data or cluster-wide * data. */ void clearRealmCacheOnChange(CachingRealm realm); /** * A representation of a user for whom roles should be mapped. * The user has been authenticated, but does not yet have any roles. */
UserRoleMapper
java
quarkusio__quarkus
extensions/keycloak-authorization/runtime/src/main/java/io/quarkus/keycloak/pep/runtime/KeycloakPolicyEnforcerRecorder.java
{ "start": 329, "end": 2205 }
class ____ { private final RuntimeValue<KeycloakPolicyEnforcerConfig> runtimeConfig; public KeycloakPolicyEnforcerRecorder(final RuntimeValue<KeycloakPolicyEnforcerConfig> runtimeConfig) { this.runtimeConfig = runtimeConfig; } public BooleanSupplier createBodyHandlerRequiredEvaluator() { return new BooleanSupplier() { @Override public boolean getAsBoolean() { if (isBodyHandlerRequired(runtimeConfig.getValue().defaultTenant())) { return true; } for (KeycloakPolicyEnforcerTenantConfig tenantConfig : runtimeConfig.getValue().namedTenants().values()) { if (isBodyHandlerRequired(tenantConfig)) { return true; } } return false; } }; } private static boolean isBodyHandlerRequired(KeycloakPolicyEnforcerTenantConfig config) { if (isBodyClaimInformationPointDefined(config.policyEnforcer().claimInformationPoint().simpleConfig())) { return true; } for (PathConfig path : config.policyEnforcer().paths().values()) { if (isBodyClaimInformationPointDefined(path.claimInformationPoint().simpleConfig())) { return true; } } return false; } private static boolean isBodyClaimInformationPointDefined(Map<String, Map<String, String>> claims) { for (Map.Entry<String, Map<String, String>> entry : claims.entrySet()) { Map<String, String> value = entry.getValue(); for (String nestedValue : value.values()) { if (nestedValue.contains("request.body")) { return true; } } } return false; } }
KeycloakPolicyEnforcerRecorder
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/hotreload/SomeProcessor.java
{ "start": 261, "end": 425 }
class ____ { @Incoming("my-source") @Outgoing("my-sink") public String process(int input) { return Long.toString(input * -1); } }
SomeProcessor
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/cluster/stats/ClusterStatsNodes.java
{ "start": 30924, "end": 36083 }
class ____ implements ToXContentFragment { private final IndexingPressureStats indexingPressureStats; IndexPressureStats(final List<NodeStats> nodeStats) { long totalCombinedCoordinatingAndPrimaryBytes = 0; long totalCoordinatingBytes = 0; long totalPrimaryBytes = 0; long totalReplicaBytes = 0; long currentCombinedCoordinatingAndPrimaryBytes = 0; long currentCoordinatingBytes = 0; long currentPrimaryBytes = 0; long currentReplicaBytes = 0; long coordinatingRejections = 0; long primaryRejections = 0; long replicaRejections = 0; long primaryDocumentRejections = 0; long memoryLimit = 0; long totalCoordinatingOps = 0; long totalCoordinatingRequests = 0; long totalPrimaryOps = 0; long totalReplicaOps = 0; long currentCoordinatingOps = 0; long currentPrimaryOps = 0; long currentReplicaOps = 0; long lowWaterMarkSplits = 0; long highWaterMarkSplits = 0; long largeOpsRejections = 0; long totalLargeRejectedOpsBytes = 0; for (NodeStats nodeStat : nodeStats) { IndexingPressureStats nodeStatIndexingPressureStats = nodeStat.getIndexingPressureStats(); if (nodeStatIndexingPressureStats != null) { totalCombinedCoordinatingAndPrimaryBytes += nodeStatIndexingPressureStats.getTotalCombinedCoordinatingAndPrimaryBytes(); totalCoordinatingBytes += nodeStatIndexingPressureStats.getTotalCoordinatingBytes(); totalPrimaryBytes += nodeStatIndexingPressureStats.getTotalPrimaryBytes(); totalReplicaBytes += nodeStatIndexingPressureStats.getTotalReplicaBytes(); currentCombinedCoordinatingAndPrimaryBytes += nodeStatIndexingPressureStats .getCurrentCombinedCoordinatingAndPrimaryBytes(); currentCoordinatingBytes += nodeStatIndexingPressureStats.getCurrentCoordinatingBytes(); currentPrimaryBytes += nodeStatIndexingPressureStats.getCurrentPrimaryBytes(); currentReplicaBytes += nodeStatIndexingPressureStats.getCurrentReplicaBytes(); coordinatingRejections += nodeStatIndexingPressureStats.getCoordinatingRejections(); primaryRejections += nodeStatIndexingPressureStats.getPrimaryRejections(); replicaRejections += nodeStatIndexingPressureStats.getReplicaRejections(); memoryLimit += nodeStatIndexingPressureStats.getMemoryLimit(); totalCoordinatingOps += nodeStatIndexingPressureStats.getTotalCoordinatingOps(); totalReplicaOps += nodeStatIndexingPressureStats.getTotalReplicaOps(); currentCoordinatingOps += nodeStatIndexingPressureStats.getCurrentCoordinatingOps(); currentPrimaryOps += nodeStatIndexingPressureStats.getCurrentPrimaryOps(); currentReplicaOps += nodeStatIndexingPressureStats.getCurrentReplicaOps(); primaryDocumentRejections += nodeStatIndexingPressureStats.getPrimaryDocumentRejections(); totalCoordinatingRequests += nodeStatIndexingPressureStats.getTotalCoordinatingRequests(); lowWaterMarkSplits += nodeStatIndexingPressureStats.getLowWaterMarkSplits(); highWaterMarkSplits += nodeStatIndexingPressureStats.getHighWaterMarkSplits(); largeOpsRejections += nodeStatIndexingPressureStats.getLargeOpsRejections(); totalLargeRejectedOpsBytes += nodeStatIndexingPressureStats.getTotalLargeRejectedOpsBytes(); } } indexingPressureStats = new IndexingPressureStats( totalCombinedCoordinatingAndPrimaryBytes, totalCoordinatingBytes, totalPrimaryBytes, totalReplicaBytes, currentCombinedCoordinatingAndPrimaryBytes, currentCoordinatingBytes, currentPrimaryBytes, currentReplicaBytes, coordinatingRejections, primaryRejections, replicaRejections, memoryLimit, totalCoordinatingOps, totalPrimaryOps, totalReplicaOps, currentCoordinatingOps, currentPrimaryOps, currentReplicaOps, primaryDocumentRejections, totalCoordinatingRequests, lowWaterMarkSplits, highWaterMarkSplits, largeOpsRejections, totalLargeRejectedOpsBytes ); } @Override public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { return indexingPressureStats.toXContent(builder, params); } } static
IndexPressureStats
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/AbstractReadOnlyDecorator.java
{ "start": 5639, "end": 5976 }
class ____<K, V> extends KeyValueStoreReadOnlyDecorator<K, ValueAndTimestamp<V>> implements TimestampedKeyValueStore<K, V> { private TimestampedKeyValueStoreReadOnlyDecorator(final TimestampedKeyValueStore<K, V> inner) { super(inner); } } static
TimestampedKeyValueStoreReadOnlyDecorator
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/test/java/org/apache/hadoop/hdfs/TestDFSOpsCountStatistics.java
{ "start": 3561, "end": 6956 }
enum ____ are iterated via iter assertEquals(OpType.values().length, iterations); } @Test public void testGetLong() { assertNull(statistics.getLong(null)); assertNull(statistics.getLong(NO_SUCH_OP)); verifyStatistics(); } @Test public void testIsTracked() { assertFalse(statistics.isTracked(null)); assertFalse(statistics.isTracked(NO_SUCH_OP)); final Iterator<LongStatistic> iter = statistics.getLongStatistics(); while (iter.hasNext()) { final LongStatistic longStatistic = iter.next(); assertTrue(statistics.isTracked(longStatistic.getName())); } } @Test public void testReset() { statistics.reset(); for (OpType opType : OpType.values()) { expectedOpsCountMap.get(opType).set(0); } final Iterator<LongStatistic> iter = statistics.getLongStatistics(); while (iter.hasNext()) { final LongStatistic longStat = iter.next(); assertEquals(0, longStat.getValue()); } incrementOpsCountByRandomNumbers(); verifyStatistics(); } @Test public void testCurrentAccess() throws InterruptedException { final int numThreads = 10; final ExecutorService threadPool = newFixedThreadPool(numThreads); try { final CountDownLatch allReady = new CountDownLatch(numThreads); final CountDownLatch startBlocker = new CountDownLatch(1); final CountDownLatch allDone = new CountDownLatch(numThreads); final AtomicReference<Throwable> childError = new AtomicReference<>(); for (int i = 0; i < numThreads; i++) { threadPool.submit(new Runnable() { @Override public void run() { allReady.countDown(); try { startBlocker.await(); incrementOpsCountByRandomNumbers(); } catch (Throwable t) { LOG.error("Child failed when calling mkdir", t); childError.compareAndSet(null, t); } finally { allDone.countDown(); } } }); } allReady.await(); // wait until all threads are ready startBlocker.countDown(); // all threads start making directories allDone.await(); // wait until all threads are done assertNull(childError.get(), "Child failed with exception."); verifyStatistics(); } finally { threadPool.shutdownNow(); } } /** * This is helper method to increment the statistics by random data. */ private void incrementOpsCountByRandomNumbers() { for (OpType opType : OpType.values()) { final Long randomCount = RandomUtils.nextLong(0, 100); expectedOpsCountMap.get(opType).addAndGet(randomCount); for (long i = 0; i < randomCount; i++) { statistics.incrementOpCounter(opType); } } } /** * We have the expected ops count in {@link #expectedOpsCountMap}, and this * method is to verify that its ops count is the same as the one in * {@link #statistics}. */ private void verifyStatistics() { for (OpType opType : OpType.values()) { assertNotNull(expectedOpsCountMap.get(opType)); assertNotNull(statistics.getLong(opType.getSymbol())); assertEquals(expectedOpsCountMap.get(opType).longValue(), statistics.getLong(opType.getSymbol()).longValue(), "Not expected count for operation " + opType.getSymbol()); } } }
entries
java
spring-projects__spring-security
oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/access/BearerTokenAccessDeniedHandlerTests.java
{ "start": 3783, "end": 4251 }
class ____ extends AbstractOAuth2TokenAuthenticationToken<TestingOAuth2TokenAuthenticationToken.TestingOAuth2Token> { private Map<String, Object> attributes; protected TestingOAuth2TokenAuthenticationToken(Map<String, Object> attributes) { super(new TestingOAuth2Token("token")); this.attributes = attributes; } @Override public Map<String, Object> getTokenAttributes() { return this.attributes; } static
TestingOAuth2TokenAuthenticationToken
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/SlotPoolServiceSchedulerFactory.java
{ "start": 2186, "end": 4165 }
interface ____ { /** * Creates a {@link SlotPoolService}. * * @param jid jid is the JobID to pass to the service * @param declarativeSlotPoolFactory the declarative slot pool factory * @param componentMainThreadExecutor component main thread executor. * @return created SlotPoolService */ SlotPoolService createSlotPoolService( JobID jid, DeclarativeSlotPoolFactory declarativeSlotPoolFactory, @Nonnull ComponentMainThreadExecutor componentMainThreadExecutor); /** * Returns the scheduler type this factory is creating. * * @return the scheduler type this factory is creating. */ JobManagerOptions.SchedulerType getSchedulerType(); /** * Creates a {@link SchedulerNG}. * * @return created SchedulerNG * @throws Exception if the scheduler creation fails */ SchedulerNG createScheduler( Logger log, ExecutionPlan executionPlan, Executor ioExecutor, Configuration configuration, SlotPoolService slotPoolService, ScheduledExecutorService futureExecutor, ClassLoader userCodeLoader, CheckpointRecoveryFactory checkpointRecoveryFactory, Duration rpcTimeout, BlobWriter blobWriter, JobManagerJobMetricGroup jobManagerJobMetricGroup, Duration slotRequestTimeout, ShuffleMaster<?> shuffleMaster, JobMasterPartitionTracker partitionTracker, ExecutionDeploymentTracker executionDeploymentTracker, long initializationTimestamp, ComponentMainThreadExecutor mainThreadExecutor, FatalErrorHandler fatalErrorHandler, JobStatusListener jobStatusListener, Collection<FailureEnricher> failureEnrichers, BlocklistOperations blocklistOperations) throws Exception; }
SlotPoolServiceSchedulerFactory
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 31630, "end": 31803 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return definesFunction( dialect, "xmlforest" ); } } public static
SupportsXmlforest
java
apache__kafka
shell/src/main/java/org/apache/kafka/shell/glob/GlobVisitor.java
{ "start": 1232, "end": 1578 }
class ____ implements Consumer<MetadataShellState> { private final String glob; private final Consumer<Optional<MetadataNodeInfo>> handler; public GlobVisitor(String glob, Consumer<Optional<MetadataNodeInfo>> handler) { this.glob = glob; this.handler = handler; } public static
GlobVisitor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/fetching/ProfileFetchingTest.java
{ "start": 1349, "end": 2761 }
class ____ { @AfterEach void tearDown(SessionFactoryScope factoryScope) { factoryScope.dropData(); } @Test public void test(SessionFactoryScope factoryScope) { factoryScope.inTransaction( entityManager -> { Department department = new Department(); department.id = 1L; entityManager.persist(department); Employee employee1 = new Employee(); employee1.id = 1L; employee1.username = "user1"; employee1.password = "3fabb4de8f1ee2e97d7793bab2db1116"; employee1.accessLevel = 0; employee1.department = department; entityManager.persist(employee1); Employee employee2 = new Employee(); employee2.id = 2L; employee2.username = "user2"; employee2.password = "3fabb4de8f1ee2e97d7793bab2db1116"; employee2.accessLevel = 1; employee2.department = department; entityManager.persist(employee2); }); factoryScope.inTransaction( entityManager -> { String username = "user1"; String password = "3fabb4de8f1ee2e97d7793bab2db1116"; Session session = entityManager.unwrap(Session.class); //tag::fetching-strategies-dynamic-fetching-profile-example[] session.enableFetchProfile("employee.projects"); Employee employee = session.bySimpleNaturalId(Employee.class).load(username); //end::fetching-strategies-dynamic-fetching-profile-example[] assertNotNull( employee ); }); } @Entity(name = "Department") public static
ProfileFetchingTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/client/internal/node/NodeClientHeadersTests.java
{ "start": 1446, "end": 2320 }
class ____ extends AbstractClientHeadersTestCase { private static final ActionFilters EMPTY_FILTERS = new ActionFilters(Collections.emptySet()); @Override protected Client buildClient(Settings headersSettings, ActionType<?>[] testedActions) { Settings settings = HEADER_SETTINGS; TaskManager taskManager = new TaskManager(settings, threadPool, Collections.emptySet()); Map<ActionType<?>, TransportAction<?, ?>> actions = Stream.of(testedActions) .collect(Collectors.toMap(Function.identity(), a -> new InternalTransportAction(a.name(), taskManager))); NodeClient client = new NodeClient(settings, threadPool, TestProjectResolvers.alwaysThrow()); client.initialize(actions, taskManager, () -> "test", mock(Transport.Connection.class), null); return client; } private static
NodeClientHeadersTests
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/http/converter/ByteArrayHttpMessageConverter.java
{ "start": 1375, "end": 2437 }
class ____ extends AbstractHttpMessageConverter<byte[]> { /** * Create a new instance of the {@code ByteArrayHttpMessageConverter}. */ public ByteArrayHttpMessageConverter() { super(MediaType.APPLICATION_OCTET_STREAM, MediaType.ALL); } @Override public boolean supports(Class<?> clazz) { return byte[].class == clazz; } @Override public byte[] readInternal(Class<? extends byte[]> clazz, HttpInputMessage message) throws IOException { long length = message.getHeaders().getContentLength(); return (length >= 0 && length < Integer.MAX_VALUE ? message.getBody().readNBytes((int) length) : message.getBody().readAllBytes()); } @Override protected Long getContentLength(byte[] bytes, @Nullable MediaType contentType) { return (long) bytes.length; } @Override protected void writeInternal(byte[] bytes, HttpOutputMessage outputMessage) throws IOException { StreamUtils.copy(bytes, outputMessage.getBody()); } @Override protected boolean supportsRepeatableWrites(byte[] bytes) { return true; } }
ByteArrayHttpMessageConverter
java
spring-projects__spring-boot
integration-test/spring-boot-actuator-integration-tests/src/test/java/org/springframework/boot/actuate/endpoint/web/annotation/AbstractWebEndpointIntegrationTests.java
{ "start": 25132, "end": 25387 }
class ____ { @Bean FluxResponseEndpoint testEndpoint(EndpointDelegate endpointDelegate) { return new FluxResponseEndpoint(); } } @Configuration(proxyBeanMethods = false) @Import(BaseConfiguration.class) static
FluxResponseEndpointConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/basic/CollectionAsBasicTest.java
{ "start": 1522, "end": 1669 }
class ____ extends UserTypeSupport<Set> { public DelimitedStringsJavaType() { super( Set.class, Types.VARCHAR ); } } }
DelimitedStringsJavaType
java
netty__netty
microbench/src/main/java/io/netty/microbenchmark/common/IntObjectHashMapBenchmark.java
{ "start": 2525, "end": 3710 }
class ____ { final int[] keys; Environment() { keys = new int[size]; switch(keyDistribution) { case HTTP2: for (int index = 0, key = 3; index < size; ++index, key += 2) { keys[index] = key; } break; case RANDOM: { // Create a 'size' # of random integers. Random r = new Random(); Set<Integer> keySet = new HashSet<Integer>(); while (keySet.size() < size) { keySet.add(r.nextInt()); } int index = 0; for (Integer key : keySet) { keys[index++] = key; } break; } default: { throw new IllegalStateException("Unknown keyDistribution: " + keyDistribution); } } } abstract void put(Blackhole bh); abstract void lookup(Blackhole bh); abstract void remove(Blackhole bh); } private
Environment
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/NarrowingCompoundAssignmentTest.java
{ "start": 13503, "end": 16013 }
class ____ { void f(short s, byte b, char c, int i, long l, float f, double d) { s += s; s += b; // BUG: Diagnostic contains: s += c; // BUG: Diagnostic contains: s += i; // BUG: Diagnostic contains: s += l; // BUG: Diagnostic contains: s += f; // BUG: Diagnostic contains: s += d; // BUG: Diagnostic contains: b += s; b += b; // BUG: Diagnostic contains: b += c; // BUG: Diagnostic contains: b += i; // BUG: Diagnostic contains: b += l; // BUG: Diagnostic contains: b += f; // BUG: Diagnostic contains: b += d; // BUG: Diagnostic contains: c += s; // BUG: Diagnostic contains: c += b; c += c; // BUG: Diagnostic contains: c += i; // BUG: Diagnostic contains: c += l; // BUG: Diagnostic contains: c += f; // BUG: Diagnostic contains: c += d; i += s; i += b; i += c; i += i; // BUG: Diagnostic contains: i += l; // BUG: Diagnostic contains: i += f; // BUG: Diagnostic contains: i += d; l += s; l += b; l += c; l += i; l += l; // BUG: Diagnostic contains: l += f; // BUG: Diagnostic contains: l += d; f += s; f += b; f += c; f += i; f += l; f += f; // BUG: Diagnostic contains: f += d; d += s; d += b; d += c; d += i; d += l; d += f; d += d; } } """) .doTest(); } @Test public void boxing() { compilationHelper .addSourceLines( "Test.java", """
Test
java
quarkusio__quarkus
extensions/oidc-client-filter/deployment/src/test/java/io/quarkus/oidc/client/filter/ExtendedOidcClientRequestFilterDevModeTest.java
{ "start": 459, "end": 2288 }
class ____ { private static final Class<?>[] testClasses = { ProtectedResource.class, ProtectedResourceServiceNamedOidcClient.class, ProtectedResourceServiceConfigPropertyOidcClient.class, ProtectedResourceServiceExtendedOidcClientRequestFilter.class, NamedOidcClientResource.class, ExtendedOidcClientRequestFilter.class, ExtendedOidcClientRequestFilterResource.class }; @RegisterExtension static final QuarkusDevModeTest test = new QuarkusDevModeTest() .withApplicationRoot((jar) -> jar .addClasses(testClasses) .addAsResource("application-extended-oidc-client-request-filter.properties", "application.properties")); @Test public void testGerUserConfigPropertyAndAnnotation() { // OidcClient selected via @OidcClient("clientName") RestAssured.when().get("/named-oidc-client/user-name") .then() .statusCode(200) .body(equalTo("jdoe")); // @OidcClientFilter: OidcClient selected via `quarkus.oidc-client-filter.client-name=config-property` RestAssured.when().get("/config-property-oidc-client/annotation/user-name") .then() .statusCode(200) .body(equalTo("alice")); // @RegisterProvider(ExtendedOidcClientRequestFilter.class) // OidcClient selected via `quarkus.oidc-client-filter.client-name=config-property` // ExtendedOidcClientRequestFilter extends OidcClientRequestFilter RestAssured.when().get("/config-property-oidc-client/extended-provider/user-name") .then() .statusCode(200) .body(equalTo("alice")); } }
ExtendedOidcClientRequestFilterDevModeTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SchematronEndpointBuilderFactory.java
{ "start": 1573, "end": 3830 }
interface ____ extends EndpointProducerBuilder { default AdvancedSchematronEndpointBuilder advanced() { return (AdvancedSchematronEndpointBuilder) this; } /** * Flag to abort the route and throw a schematron validation exception. * * The option is a: <code>boolean</code> type. * * Default: false * Group: producer * * @param abort the value to set * @return the dsl builder */ default SchematronEndpointBuilder abort(boolean abort) { doSetProperty("abort", abort); return this; } /** * Flag to abort the route and throw a schematron validation exception. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: producer * * @param abort the value to set * @return the dsl builder */ default SchematronEndpointBuilder abort(String abort) { doSetProperty("abort", abort); return this; } /** * To use the given schematron rules instead of loading from the path. * * The option is a: <code>javax.xml.transform.Templates</code> type. * * Group: producer * * @param rules the value to set * @return the dsl builder */ default SchematronEndpointBuilder rules(javax.xml.transform.Templates rules) { doSetProperty("rules", rules); return this; } /** * To use the given schematron rules instead of loading from the path. * * The option will be converted to a * <code>javax.xml.transform.Templates</code> type. * * Group: producer * * @param rules the value to set * @return the dsl builder */ default SchematronEndpointBuilder rules(String rules) { doSetProperty("rules", rules); return this; } } /** * Advanced builder for endpoint for the Schematron component. */ public
SchematronEndpointBuilder
java
spring-projects__spring-boot
module/spring-boot-actuator-autoconfigure/src/test/java/org/springframework/boot/actuate/autoconfigure/web/server/ManagementContextConfigurationImportSelectorTests.java
{ "start": 3746, "end": 3780 }
class ____ { } @Order(2) static
A
java
micronaut-projects__micronaut-core
inject-java/src/main/java/io/micronaut/annotation/processing/visitor/JavaConstructorElement.java
{ "start": 1063, "end": 2158 }
class ____ extends JavaMethodElement implements ConstructorElement { /** * @param owningClass The declaring class * @param nativeElement The native element * @param annotationMetadataFactory The annotation metadata factory * @param visitorContext The visitor context */ JavaConstructorElement(JavaClassElement owningClass, JavaNativeElement.Method nativeElement, ElementAnnotationMetadataFactory annotationMetadataFactory, JavaVisitorContext visitorContext) { super(owningClass, nativeElement, annotationMetadataFactory, visitorContext); } @Override protected AbstractJavaElement copyThis() { return new JavaConstructorElement(getDeclaringType(), getNativeType(), elementAnnotationMetadataFactory, visitorContext); } @Override public boolean overrides(@NonNull MethodElement overridden) { return false; } @Override public boolean hides(@NonNull MemberElement hidden) { return false; } }
JavaConstructorElement
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/stubbing/defaultanswers/ForwardsInvocationsTest.java
{ "start": 339, "end": 432 }
interface ____ { int bar(String baz, Object... args); } private static final
Foo
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java
{ "start": 7123, "end": 25885 }
class ____ known to have no such annotations at any level; * {@code true} otherwise. Callers will usually perform full method/field introspection * if {@code true} is being returned here. * @since 5.2 * @see #isCandidateClass(Class, Class) */ public static boolean isCandidateClass(Class<?> clazz, String annotationName) { if (annotationName.startsWith("java.")) { return true; } if (AnnotationsScanner.hasPlainJavaAnnotationsOnly(clazz)) { return false; } return true; } /** * Get a single {@link Annotation} of {@code annotationType} from the supplied * annotation: either the given annotation itself or a direct meta-annotation * thereof. * <p>Note that this method supports only a single level of meta-annotations. * For support for arbitrary levels of meta-annotations, use one of the * {@code find*()} methods instead. * @param annotation the Annotation to check * @param annotationType the annotation type to look for, both locally and as a meta-annotation * @return the first matching annotation, or {@code null} if not found * @since 4.0 */ @SuppressWarnings("unchecked") public static <A extends Annotation> @Nullable A getAnnotation(Annotation annotation, Class<A> annotationType) { // Shortcut: directly present on the element, with no merging needed? if (annotationType.isInstance(annotation)) { return synthesizeAnnotation((A) annotation, annotationType); } // Shortcut: no searchable annotations to be found on plain Java classes and core Spring types... if (AnnotationsScanner.hasPlainJavaAnnotationsOnly(annotation)) { return null; } // Exhaustive retrieval of merged annotations... return MergedAnnotations.from(annotation, new Annotation[] {annotation}, RepeatableContainers.none()) .get(annotationType).withNonMergedAttributes() .synthesize(AnnotationUtils::isSingleLevelPresent).orElse(null); } /** * Get a single {@link Annotation} of {@code annotationType} from the supplied * {@link AnnotatedElement}, where the annotation is either <em>present</em> or * <em>meta-present</em> on the {@code AnnotatedElement}. * <p>Note that this method supports only a single level of meta-annotations. * For support for arbitrary levels of meta-annotations, use * {@link #findAnnotation(AnnotatedElement, Class)} instead. * @param annotatedElement the {@code AnnotatedElement} from which to get the annotation * @param annotationType the annotation type to look for, both locally and as a meta-annotation * @return the first matching annotation, or {@code null} if not found * @since 3.1 */ public static <A extends Annotation> @Nullable A getAnnotation(AnnotatedElement annotatedElement, Class<A> annotationType) { // Shortcut: directly present on the element, with no merging needed? if (AnnotationFilter.PLAIN.matches(annotationType) || AnnotationsScanner.hasPlainJavaAnnotationsOnly(annotatedElement)) { return annotatedElement.getAnnotation(annotationType); } // Exhaustive retrieval of merged annotations... return MergedAnnotations.from(annotatedElement, SearchStrategy.INHERITED_ANNOTATIONS, RepeatableContainers.none()) .get(annotationType).withNonMergedAttributes() .synthesize(AnnotationUtils::isSingleLevelPresent).orElse(null); } private static <A extends Annotation> boolean isSingleLevelPresent(MergedAnnotation<A> mergedAnnotation) { int distance = mergedAnnotation.getDistance(); return (distance == 0 || distance == 1); } /** * Get a single {@link Annotation} of {@code annotationType} from the * supplied {@link Method}, where the annotation is either <em>present</em> * or <em>meta-present</em> on the method. * <p>Correctly handles bridge {@link Method Methods} generated by the compiler. * <p>Note that this method supports only a single level of meta-annotations. * For support for arbitrary levels of meta-annotations, use * {@link #findAnnotation(Method, Class)} instead. * @param method the method to look for annotations on * @param annotationType the annotation type to look for * @return the first matching annotation, or {@code null} if not found * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method) * @see #getAnnotation(AnnotatedElement, Class) */ public static <A extends Annotation> @Nullable A getAnnotation(Method method, Class<A> annotationType) { Method resolvedMethod = BridgeMethodResolver.findBridgedMethod(method); return getAnnotation((AnnotatedElement) resolvedMethod, annotationType); } /** * Get all {@link Annotation Annotations} that are <em>present</em> on the * supplied {@link AnnotatedElement}. * <p>Meta-annotations will <em>not</em> be searched. * @param annotatedElement the Method, Constructor or Field to retrieve annotations from * @return the annotations found, an empty array, or {@code null} if not * resolvable (for example, because nested Class values in annotation attributes * failed to resolve at runtime) * @since 4.0.8 * @see AnnotatedElement#getAnnotations() * @deprecated since it is superseded by the {@link MergedAnnotations} API */ @Deprecated(since = "5.2") public static Annotation @Nullable [] getAnnotations(AnnotatedElement annotatedElement) { try { return synthesizeAnnotationArray(annotatedElement.getAnnotations(), annotatedElement); } catch (Throwable ex) { handleIntrospectionFailure(annotatedElement, ex); return null; } } /** * Get all {@link Annotation Annotations} that are <em>present</em> on the * supplied {@link Method}. * <p>Correctly handles bridge {@link Method Methods} generated by the compiler. * <p>Meta-annotations will <em>not</em> be searched. * @param method the Method to retrieve annotations from * @return the annotations found, an empty array, or {@code null} if not * resolvable (for example, because nested Class values in annotation attributes * failed to resolve at runtime) * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod(Method) * @see AnnotatedElement#getAnnotations() * @deprecated since it is superseded by the {@link MergedAnnotations} API */ @Deprecated(since = "5.2") public static Annotation @Nullable [] getAnnotations(Method method) { try { return synthesizeAnnotationArray(BridgeMethodResolver.findBridgedMethod(method).getAnnotations(), method); } catch (Throwable ex) { handleIntrospectionFailure(method, ex); return null; } } /** * Get the <em>repeatable</em> {@linkplain Annotation annotations} of * {@code annotationType} from the supplied {@link AnnotatedElement}, where * such annotations are either <em>present</em>, <em>indirectly present</em>, * or <em>meta-present</em> on the element. * <p>This method mimics the functionality of * {@link java.lang.reflect.AnnotatedElement#getAnnotationsByType(Class)} * with support for automatic detection of a <em>container annotation</em> * declared via {@link java.lang.annotation.Repeatable @Repeatable} and with * additional support for meta-annotations. * <p>Handles both single annotations and annotations nested within a * <em>container annotation</em>. * <p>Correctly handles <em>bridge methods</em> generated by the * compiler if the supplied element is a {@link Method}. * <p>Meta-annotations will be searched if the annotation is not * <em>present</em> on the supplied element. * @param annotatedElement the element to look for annotations on * @param annotationType the annotation type to look for * @return the annotations found or an empty set (never {@code null}) * @since 4.2 * @see #getRepeatableAnnotations(AnnotatedElement, Class, Class) * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class, Class) * @see AnnotatedElementUtils#getMergedRepeatableAnnotations(AnnotatedElement, Class) * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod * @see java.lang.annotation.Repeatable * @see java.lang.reflect.AnnotatedElement#getAnnotationsByType * @deprecated since it is superseded by the {@link MergedAnnotations} API */ @Deprecated(since = "5.2") public static <A extends Annotation> Set<A> getRepeatableAnnotations(AnnotatedElement annotatedElement, Class<A> annotationType) { return getRepeatableAnnotations(annotatedElement, annotationType, null); } /** * Get the <em>repeatable</em> {@linkplain Annotation annotations} of * {@code annotationType} from the supplied {@link AnnotatedElement}, where * such annotations are either <em>present</em>, <em>indirectly present</em>, * or <em>meta-present</em> on the element. * <p>This method mimics the functionality * {@link java.lang.reflect.AnnotatedElement#getAnnotationsByType(Class)} * with additional support for meta-annotations. * <p>Handles both single annotations and annotations nested within a * <em>container annotation</em>. * <p>Correctly handles <em>bridge methods</em> generated by the * compiler if the supplied element is a {@link Method}. * <p>Meta-annotations will be searched if the annotation is not * <em>present</em> on the supplied element. * @param annotatedElement the element to look for annotations on * @param annotationType the annotation type to look for * @param containerAnnotationType the type of the container that holds the * annotations; may be {@code null} if a container is not supported or if it * should be looked up via {@link java.lang.annotation.Repeatable @Repeatable} * @return the annotations found or an empty set (never {@code null}) * @since 4.2 * @see #getRepeatableAnnotations(AnnotatedElement, Class) * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class) * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class, Class) * @see AnnotatedElementUtils#getMergedRepeatableAnnotations(AnnotatedElement, Class, Class) * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod * @see java.lang.annotation.Repeatable * @see java.lang.reflect.AnnotatedElement#getAnnotationsByType * @deprecated since it is superseded by the {@link MergedAnnotations} API */ @Deprecated(since = "5.2") public static <A extends Annotation> Set<A> getRepeatableAnnotations(AnnotatedElement annotatedElement, Class<A> annotationType, @Nullable Class<? extends Annotation> containerAnnotationType) { RepeatableContainers repeatableContainers = (containerAnnotationType != null ? RepeatableContainers.explicitRepeatable(annotationType, containerAnnotationType) : RepeatableContainers.standardRepeatables()); return MergedAnnotations.from(annotatedElement, SearchStrategy.SUPERCLASS, repeatableContainers) .stream(annotationType) .filter(MergedAnnotationPredicates.firstRunOf(MergedAnnotation::getAggregateIndex)) .map(MergedAnnotation::withNonMergedAttributes) .collect(MergedAnnotationCollectors.toAnnotationSet()); } /** * Get the declared <em>repeatable</em> {@linkplain Annotation annotations} * of {@code annotationType} from the supplied {@link AnnotatedElement}, * where such annotations are either <em>directly present</em>, * <em>indirectly present</em>, or <em>meta-present</em> on the element. * <p>This method mimics the functionality of * {@link java.lang.reflect.AnnotatedElement#getDeclaredAnnotationsByType(Class)} * with support for automatic detection of a <em>container annotation</em> * declared via {@link java.lang.annotation.Repeatable @Repeatable} and with * additional support for meta-annotations. * <p>Handles both single annotations and annotations nested within a * <em>container annotation</em>. * <p>Correctly handles <em>bridge methods</em> generated by the * compiler if the supplied element is a {@link Method}. * <p>Meta-annotations will be searched if the annotation is not * <em>present</em> on the supplied element. * @param annotatedElement the element to look for annotations on * @param annotationType the annotation type to look for * @return the annotations found or an empty set (never {@code null}) * @since 4.2 * @see #getRepeatableAnnotations(AnnotatedElement, Class) * @see #getRepeatableAnnotations(AnnotatedElement, Class, Class) * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class, Class) * @see AnnotatedElementUtils#getMergedRepeatableAnnotations(AnnotatedElement, Class) * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod * @see java.lang.annotation.Repeatable * @see java.lang.reflect.AnnotatedElement#getDeclaredAnnotationsByType * @deprecated since it is superseded by the {@link MergedAnnotations} API */ @Deprecated(since = "5.2") public static <A extends Annotation> Set<A> getDeclaredRepeatableAnnotations(AnnotatedElement annotatedElement, Class<A> annotationType) { return getDeclaredRepeatableAnnotations(annotatedElement, annotationType, null); } /** * Get the declared <em>repeatable</em> {@linkplain Annotation annotations} * of {@code annotationType} from the supplied {@link AnnotatedElement}, * where such annotations are either <em>directly present</em>, * <em>indirectly present</em>, or <em>meta-present</em> on the element. * <p>This method mimics the functionality of * {@link java.lang.reflect.AnnotatedElement#getDeclaredAnnotationsByType(Class)} * with additional support for meta-annotations. * <p>Handles both single annotations and annotations nested within a * <em>container annotation</em>. * <p>Correctly handles <em>bridge methods</em> generated by the * compiler if the supplied element is a {@link Method}. * <p>Meta-annotations will be searched if the annotation is not * <em>present</em> on the supplied element. * @param annotatedElement the element to look for annotations on * @param annotationType the annotation type to look for * @param containerAnnotationType the type of the container that holds the * annotations; may be {@code null} if a container is not supported or if it * should be looked up via {@link java.lang.annotation.Repeatable @Repeatable} * @return the annotations found or an empty set (never {@code null}) * @since 4.2 * @see #getRepeatableAnnotations(AnnotatedElement, Class) * @see #getRepeatableAnnotations(AnnotatedElement, Class, Class) * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class) * @see AnnotatedElementUtils#getMergedRepeatableAnnotations(AnnotatedElement, Class, Class) * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod * @see java.lang.annotation.Repeatable * @see java.lang.reflect.AnnotatedElement#getDeclaredAnnotationsByType * @deprecated since it is superseded by the {@link MergedAnnotations} API */ @Deprecated(since = "5.2") public static <A extends Annotation> Set<A> getDeclaredRepeatableAnnotations(AnnotatedElement annotatedElement, Class<A> annotationType, @Nullable Class<? extends Annotation> containerAnnotationType) { RepeatableContainers repeatableContainers = containerAnnotationType != null ? RepeatableContainers.explicitRepeatable(annotationType, containerAnnotationType) : RepeatableContainers.standardRepeatables(); return MergedAnnotations.from(annotatedElement, SearchStrategy.DIRECT, repeatableContainers) .stream(annotationType) .map(MergedAnnotation::withNonMergedAttributes) .collect(MergedAnnotationCollectors.toAnnotationSet()); } /** * Find a single {@link Annotation} of {@code annotationType} on the * supplied {@link AnnotatedElement}. * <p>Meta-annotations will be searched if the annotation is not * <em>directly present</em> on the supplied element. * <p><strong>Warning</strong>: this method operates generically on * annotated elements. In other words, this method does not execute * specialized search algorithms for classes or methods. If you require * the more specific semantics of {@link #findAnnotation(Class, Class)} * or {@link #findAnnotation(Method, Class)}, invoke one of those methods * instead. * @param annotatedElement the {@code AnnotatedElement} on which to find the annotation * @param annotationType the annotation type to look for, both locally and as a meta-annotation * @return the first matching annotation, or {@code null} if not found * @since 4.2 */ public static <A extends Annotation> @Nullable A findAnnotation( AnnotatedElement annotatedElement, @Nullable Class<A> annotationType) { if (annotationType == null) { return null; } // Shortcut: directly present on the element, with no merging needed? if (AnnotationFilter.PLAIN.matches(annotationType) || AnnotationsScanner.hasPlainJavaAnnotationsOnly(annotatedElement)) { return annotatedElement.getDeclaredAnnotation(annotationType); } // Exhaustive retrieval of merged annotations... return MergedAnnotations.from(annotatedElement, SearchStrategy.INHERITED_ANNOTATIONS, RepeatableContainers.none()) .get(annotationType).withNonMergedAttributes() .synthesize(MergedAnnotation::isPresent).orElse(null); } /** * Find a single {@link Annotation} of {@code annotationType} on the supplied * {@link Method}, traversing its super methods (i.e. from superclasses and * interfaces) if the annotation is not <em>directly present</em> on the given * method itself. * <p>Correctly handles bridge {@link Method Methods} generated by the compiler. * <p>Meta-annotations will be searched if the annotation is not * <em>directly present</em> on the method. * <p>Annotations on methods are not inherited by default, so we need to handle * this explicitly. * @param method the method to look for annotations on * @param annotationType the annotation type to look for * @return the first matching annotation, or {@code null} if not found * @see #getAnnotation(Method, Class) */ public static <A extends Annotation> @Nullable A findAnnotation(Method method, @Nullable Class<A> annotationType) { if (annotationType == null) { return null; } // Shortcut: directly present on the element, with no merging needed? if (AnnotationFilter.PLAIN.matches(annotationType) || AnnotationsScanner.hasPlainJavaAnnotationsOnly(method)) { return method.getDeclaredAnnotation(annotationType); } // Exhaustive retrieval of merged annotations... return MergedAnnotations.from(method, SearchStrategy.TYPE_HIERARCHY, RepeatableContainers.none()) .get(annotationType).withNonMergedAttributes() .synthesize(MergedAnnotation::isPresent).orElse(null); } /** * Find a single {@link Annotation} of {@code annotationType} on the * supplied {@link Class}, traversing its interfaces, annotations, and * superclasses if the annotation is not <em>directly present</em> on * the given
is
java
apache__dubbo
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/buffer/ChannelBufferInputStream.java
{ "start": 909, "end": 3070 }
class ____ extends InputStream { private final ChannelBuffer buffer; private final int startIndex; private final int endIndex; public ChannelBufferInputStream(ChannelBuffer buffer) { this(buffer, buffer.readableBytes()); } public ChannelBufferInputStream(ChannelBuffer buffer, int length) { if (buffer == null) { throw new NullPointerException("buffer"); } if (length < 0) { throw new IllegalArgumentException("length: " + length); } if (length > buffer.readableBytes()) { throw new IndexOutOfBoundsException(); } this.buffer = buffer; startIndex = buffer.readerIndex(); endIndex = startIndex + length; buffer.markReaderIndex(); } public int readBytes() { return buffer.readerIndex() - startIndex; } @Override public int available() throws IOException { return endIndex - buffer.readerIndex(); } @Override public synchronized void mark(int readLimit) { buffer.markReaderIndex(); } @Override public boolean markSupported() { return true; } @Override public int read() throws IOException { if (!buffer.readable()) { return -1; } return buffer.readByte() & 0xff; } @Override public int read(byte[] b, int off, int len) throws IOException { int available = available(); if (available == 0) { return -1; } len = Math.min(available, len); buffer.readBytes(b, off, len); return len; } @Override public synchronized void reset() throws IOException { buffer.resetReaderIndex(); } @Override public long skip(long n) throws IOException { if (n > Integer.MAX_VALUE) { return skipBytes(Integer.MAX_VALUE); } else { return skipBytes((int) n); } } private int skipBytes(int n) throws IOException { int nBytes = Math.min(available(), n); buffer.skipBytes(nBytes); return nBytes; } }
ChannelBufferInputStream
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MixedMutabilityReturnTypeTest.java
{ "start": 13725, "end": 14296 }
class ____ { List<Integer> ints = new ArrayList<>(); List<Integer> foo() { if (hashCode() > 0) { return Collections.emptyList(); } ints.add(1); return ints; } } """) .addOutputLines( "Test.java", """ import com.google.common.collect.ImmutableList; import java.util.ArrayList; import java.util.Collections; import java.util.List;
Test
java
apache__dubbo
dubbo-rpc/dubbo-rpc-api/src/main/java/org/apache/dubbo/rpc/protocol/PermittedSerializationKeeper.java
{ "start": 1552, "end": 3083 }
class ____ { private final ConcurrentMap<String, Set<Byte>> serviceToSerializationId = new ConcurrentHashMap<>(); private final Set<Byte> globalPermittedSerializationIds = new ConcurrentHashSet<>(); public void registerService(URL url) { Set<Byte> set = ConcurrentHashMapUtils.computeIfAbsent( serviceToSerializationId, keyWithoutGroup(url.getServiceKey()), k -> new ConcurrentHashSet<>()); Collection<String> serializations = UrlUtils.allSerializations(url); for (String serialization : serializations) { Byte id = CodecSupport.getIDByName(serialization); if (id != null) { set.add(id); globalPermittedSerializationIds.add(id); } } } public boolean checkSerializationPermitted(String serviceKeyWithoutGroup, Byte id) throws IOException { Set<Byte> set = serviceToSerializationId.get(serviceKeyWithoutGroup); if (set == null) { throw new IOException("Service " + serviceKeyWithoutGroup + " not found, invocation rejected."); } return set.contains(id); } private static String keyWithoutGroup(String serviceKey) { String interfaceName = interfaceFromServiceKey(serviceKey); String version = versionFromServiceKey(serviceKey); if (StringUtils.isEmpty(version)) { return interfaceName; } return interfaceName + CommonConstants.GROUP_CHAR_SEPARATOR + version; } }
PermittedSerializationKeeper
java
apache__camel
components/camel-aws/camel-aws-xray/src/test/java/org/apache/camel/component/aws/xray/TestDataBuilder.java
{ "start": 6296, "end": 6743 }
class ____ extends TestEntity<TestSubsegment> { public TestSubsegment(String name) { super(name); } } public static TestTrace createTrace() { return new TestTrace(); } public static TestSegment createSegment(String name) { return new TestSegment(name); } public static TestSubsegment createSubsegment(String name) { return new TestSubsegment(name); } }
TestSubsegment
java
apache__camel
core/camel-management/src/main/java/org/apache/camel/management/mbean/ManagedSuspendableRoute.java
{ "start": 1154, "end": 2201 }
class ____ extends ManagedRoute implements ManagedSuspendableRouteMBean { public ManagedSuspendableRoute(CamelContext context, Route route) { super(context, route); } @Override public void suspend() throws Exception { if (!context.getStatus().isStarted()) { throw new IllegalArgumentException("CamelContext is not started"); } context.getRouteController().suspendRoute(getRouteId()); } @Override public void suspend(long timeout) throws Exception { if (!context.getStatus().isStarted()) { throw new IllegalArgumentException("CamelContext is not started"); } context.getRouteController().suspendRoute(getRouteId(), timeout, TimeUnit.SECONDS); } @Override public void resume() throws Exception { if (!context.getStatus().isStarted()) { throw new IllegalArgumentException("CamelContext is not started"); } context.getRouteController().resumeRoute(getRouteId()); } }
ManagedSuspendableRoute
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/TypeUtilsTest_compatibleWithJavaBean_boolean.java
{ "start": 868, "end": 1161 }
class ____ { private boolean id; public VO(){ } public VO(boolean id){ this.id = id; } public boolean isID() { return id; } public void setID(boolean id) { this.id = id; } } }
VO
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/decorators/abstractimpl/AbstractDecoratorTest.java
{ "start": 982, "end": 1101 }
interface ____<T, U> { T convert(T value); U getId(); } @ApplicationScoped static
Converter
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/execution/librarycache/LibraryCacheManager.java
{ "start": 3917, "end": 4052 }
class ____ for the associated job. * * <p>This method signals that the lease holder not longer needs the user code
loader
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/creators/ValueInstantiatorTest.java
{ "start": 2713, "end": 3749 }
class ____ extends InstantiatorBase { @Override public String getValueTypeDesc() { return Object.class.getName(); } @Override public boolean canCreateFromObjectWith() { return true; } @Override public CreatorProperty[] getFromObjectArguments(DeserializationConfig config) { return new CreatorProperty[] { CreatorProperty.construct(new PropertyName("type"), config.constructType(Class.class), null, null, null, null, 0, null, PropertyMetadata.STD_REQUIRED) }; } @Override public Object createFromObjectWith(DeserializationContext ctxt, Object[] args) { try { Class<?> cls = (Class<?>) args[0]; return cls.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } } static
PolymorphicBeanInstantiator
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/compress/CodecConstants.java
{ "start": 1071, "end": 2225 }
class ____ { private CodecConstants() { } /** * Default extension for {@link org.apache.hadoop.io.compress.DefaultCodec}. */ public static final String DEFAULT_CODEC_EXTENSION = ".deflate"; /** * Default extension for {@link org.apache.hadoop.io.compress.BZip2Codec}. */ public static final String BZIP2_CODEC_EXTENSION = ".bz2"; /** * Default extension for {@link org.apache.hadoop.io.compress.GzipCodec}. */ public static final String GZIP_CODEC_EXTENSION = ".gz"; /** * Default extension for {@link org.apache.hadoop.io.compress.Lz4Codec}. */ public static final String LZ4_CODEC_EXTENSION = ".lz4"; /** * Default extension for * {@link org.apache.hadoop.io.compress.PassthroughCodec}. */ public static final String PASSTHROUGH_CODEC_EXTENSION = ".passthrough"; /** * Default extension for {@link org.apache.hadoop.io.compress.SnappyCodec}. */ public static final String SNAPPY_CODEC_EXTENSION = ".snappy"; /** * Default extension for {@link org.apache.hadoop.io.compress.ZStandardCodec}. */ public static final String ZSTANDARD_CODEC_EXTENSION = ".zst"; }
CodecConstants
java
quarkusio__quarkus
extensions/security/deployment/src/test/java/io/quarkus/security/test/permissionsallowed/AbstractMethodLevelPermissionsAllowedTest.java
{ "start": 31344, "end": 31799 }
interface ____ { String createOrUpdate(); Uni<String> createOrUpdateNonBlocking(); String getOne(); Uni<String> getOneNonBlocking(); Uni<String> predicateNonBlocking(); String predicate(); String actionsPredicate(); Uni<String> actionsPredicateNonBlocking(); User inclusive(); Uni<User> inclusiveNonBlocking(); } protected static
MultiplePermissionsAllowedBeanI
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/support/DefaultTimeoutMapTest.java
{ "start": 1655, "end": 6317 }
class ____ { private static final Logger LOG = LoggerFactory.getLogger(DefaultTimeoutMapTest.class); private final ScheduledExecutorService executor = new ScheduledThreadPoolExecutor(1); @Test public void testDefaultTimeoutMap() { DefaultTimeoutMap<?, ?> map = new DefaultTimeoutMap<>(executor); map.start(); assertTrue(map.currentTime() > 0); assertEquals(0, map.size()); map.stop(); } @Test public void testDefaultTimeoutMapPurge() { DefaultTimeoutMap<String, Integer> map = new DefaultTimeoutMap<>(executor, 100); map.start(); assertTrue(map.currentTime() > 0); assertEquals(0, map.size()); map.put("A", 123, 50); assertEquals(1, map.size()); await().atMost(Duration.ofSeconds(2)) .untilAsserted(() -> assertEquals(0, map.size())); map.stop(); } @Test public void testDefaultTimeoutMapForcePurge() throws Exception { DefaultTimeoutMap<String, Integer> map = new DefaultTimeoutMap<>(executor, 100); // map.start(); // Do not start background purge assertTrue(map.currentTime() > 0); assertEquals(0, map.size()); map.put("A", 123, 10); assertEquals(1, map.size()); Thread.sleep(50); // will purge and remove old entries map.purge(); assertEquals(0, map.size()); } @Test public void testDefaultTimeoutMapGetRemove() { DefaultTimeoutMap<String, Integer> map = new DefaultTimeoutMap<>(executor, 100); map.start(); assertTrue(map.currentTime() > 0); assertEquals(0, map.size()); map.put("A", 123, 50); assertEquals(1, map.size()); assertEquals(123, (int) map.get("A")); Object old = map.remove("A"); assertEquals(123, old); assertNull(map.get("A")); assertEquals(0, map.size()); map.stop(); } @Test public void testExecutor() { ScheduledExecutorService e = Executors.newScheduledThreadPool(2); DefaultTimeoutMap<String, Integer> map = new DefaultTimeoutMap<>(e, 50); map.start(); assertEquals(50, map.getPurgePollTime()); map.put("A", 123, 100); assertEquals(1, map.size()); // should have been timed out now await().atMost(Duration.ofSeconds(2)) .untilAsserted(() -> assertEquals(0, map.size())); assertSame(e, map.getExecutor()); map.stop(); } @Test public void testExpiredInCorrectOrder() { final List<String> keys = new ArrayList<>(); final List<Integer> values = new ArrayList<>(); DefaultTimeoutMap<String, Integer> map = new DefaultTimeoutMap<>(executor, 100); map.addListener((type, key, value) -> { if (type == TimeoutMap.Listener.Type.Evict) { keys.add(key); values.add(value); } }); map.start(); assertEquals(0, map.size()); map.put("A", 1, 50); map.put("B", 2, 30); map.put("C", 3, 40); map.put("D", 4, 20); map.put("E", 5, 40); // is not expired map.put("F", 6, 800); await().atMost(Duration.ofSeconds(2)) .untilAsserted(() -> { assertFalse(keys.isEmpty()); assertEquals("D", keys.get(0)); }); assertEquals(4, values.get(0).intValue()); assertEquals("B", keys.get(1)); assertEquals(2, values.get(1).intValue()); assertEquals("C", keys.get(2)); assertEquals(3, values.get(2).intValue()); assertEquals("E", keys.get(3)); assertEquals(5, values.get(3).intValue()); assertEquals("A", keys.get(4)); assertEquals(1, values.get(4).intValue()); assertEquals(1, map.size()); map.stop(); } @Test public void testDefaultTimeoutMapStopStart() { DefaultTimeoutMap<String, Integer> map = new DefaultTimeoutMap<>(executor, 100); map.start(); map.put("A", 1, 500); assertEquals(1, map.size()); map.stop(); assertEquals(0, map.size()); map.put("A", 1, 50); // should not timeout as the scheduler doesn't run await().atMost(Duration.ofSeconds(1)) .untilAsserted(() -> assertEquals(1, map.size())); // start map.start(); // start and wait for scheduler to purge await().atMost(2, TimeUnit.SECONDS).untilAsserted(() -> assertEquals(0, map.size())); map.stop(); } }
DefaultTimeoutMapTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/update/MySqlUpdateTest_11_using.java
{ "start": 1059, "end": 3462 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "update t1, t2, t3 inner join t4 using (col_name1, col_name2)\n" + "set t1.value_col = t3.new_value_col, t4.`some-col*` = `t2`.`***` * 2\n" + "where t1.pk = t2.fk_t1_pk and t2.id = t4.fk_id_entity;"; MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(4, visitor.getTables().size()); assertEquals(8, visitor.getColumns().size()); // assertEquals(2, visitor.getConditions().size()); assertTrue(visitor.containsTable("t4")); assertTrue(visitor.getColumns().contains(new Column("t1", "value_col"))); assertTrue(visitor.getColumns().contains(new Column("t1", "pk"))); { String output = SQLUtils.toMySqlString(stmt); assertEquals("UPDATE (t1, t2, t3)\n" + "\tINNER JOIN t4 USING (col_name1, col_name2)\n" + "SET t1.value_col = t3.new_value_col, t4.`some-col*` = `t2`.`***` * 2\n" + "WHERE t1.pk = t2.fk_t1_pk\n" + "\tAND t2.id = t4.fk_id_entity;", // output); } { String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION); assertEquals("update (t1, t2, t3)\n" + "\tinner join t4 using (col_name1, col_name2)\n" + "set t1.value_col = t3.new_value_col, t4.`some-col*` = `t2`.`***` * 2\n" + "where t1.pk = t2.fk_t1_pk\n" + "\tand t2.id = t4.fk_id_entity;", // output); } assertTrue(WallUtils.isValidateMySql(sql)); } }
MySqlUpdateTest_11_using
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/DiscoverySelectors.java
{ "start": 37805, "end": 38094 }
class ____ to use to load the enclosing and nested classes, or * {@code null} to signal that the default {@code ClassLoader} should be used * @param enclosingClassNames the names of the enclosing classes; never {@code null} or empty * @param nestedClassName the name of the nested
loader
java
elastic__elasticsearch
x-pack/plugin/eql/src/test/java/org/elasticsearch/xpack/eql/analysis/VerifierTests.java
{ "start": 1057, "end": 20713 }
class ____ extends ESTestCase { private static final String INDEX_NAME = "test"; private final IndexResolution index = loadIndexResolution("mapping-default.json"); private static Map<String, EsField> loadEqlMapping(String name) { return TypesTests.loadMapping(name); } private IndexResolution loadIndexResolution(String name) { return IndexResolution.valid(new EsIndex(INDEX_NAME, loadEqlMapping(name))); } private LogicalPlan accept(IndexResolution resolution, String eql) { EqlParser parser = new EqlParser(); PreAnalyzer preAnalyzer = new PreAnalyzer(); Analyzer analyzer = analyzer(); LogicalPlan plan = parser.createStatement(eql); return analyzer.analyze(preAnalyzer.preAnalyze(plan, resolution)); } private LogicalPlan accept(String eql) { return accept(index, eql); } private String error(String sql) { return error(index, sql); } private String error(IndexResolution resolution, String eql) { VerificationException e = expectThrows(VerificationException.class, () -> accept(resolution, eql)); assertTrue(e.getMessage().startsWith("Found ")); final String header = "Found 1 problem\nline "; return e.getMessage().substring(header.length()); } private String errorParsing(String sql) { return errorParsing(index, sql); } private String errorParsing(IndexResolution resolution, String eql) { ParsingException e = expectThrows(ParsingException.class, () -> accept(resolution, eql)); final String header = "line "; assertTrue(e.getMessage().startsWith(header)); return e.getMessage().substring(header.length()); } public void testBasicQuery() { accept("foo where true"); } public void testQueryCondition() { accept("any where bool"); assertEquals("1:11: Condition expression needs to be boolean, found [LONG]", error("any where pid")); assertEquals("1:11: Condition expression needs to be boolean, found [DATETIME]", error("any where @timestamp")); assertEquals("1:11: Condition expression needs to be boolean, found [KEYWORD]", error("any where command_line")); assertEquals("1:11: Condition expression needs to be boolean, found [TEXT]", error("any where hostname")); assertEquals("1:11: Condition expression needs to be boolean, found [KEYWORD]", error("any where constant_keyword")); assertEquals("1:11: Condition expression needs to be boolean, found [IP]", error("any where source_address")); assertEquals("1:11: Condition expression needs to be boolean, found [VERSION]", error("any where version")); } public void testQueryStartsWithNumber() { assertThat(errorParsing("42 where true"), startsWith("1:1: mismatched input '42' expecting")); } public void testMissingColumn() { assertEquals("1:11: Unknown column [xxx]", error("foo where xxx == 100")); } public void testMisspelledColumn() { assertEquals("1:11: Unknown column [md4], did you mean [md5]?", error("foo where md4 == 1")); } public void testMisspelledColumnWithMultipleOptions() { assertEquals("1:11: Unknown column [pib], did you mean any of [pid, ppid]?", error("foo where pib == 1")); } public void testProcessRelationshipsUnsupported() { assertEquals( "2:7: Process relationships are not supported", errorParsing( "process where opcode==1 and process_name == \"csrss.exe\"\n" + " and descendant of [file where file_name == \"csrss.exe\" and opcode==0]" ) ); assertEquals( "2:7: Process relationships are not supported", errorParsing( "process where process_name==\"svchost.exe\"\n" + " and child of [file where file_name=\"svchost.exe\" and opcode==0]" ) ); } // Some functions fail with "Unsupported" message at the parse stage public void testArrayFunctionsUnsupported() { assertEquals( "1:16: Unknown function [arrayContains], did you mean [stringcontains]?", error("registry where arrayContains(bytes_written_string_list, \"En\")") ); assertEquals( "1:16: Unknown function [arraySearch]", error("registry where arraySearch(bytes_written_string_list, bytes_written_string, true)") ); assertEquals( "1:16: Unknown function [arrayCount]", error("registry where arrayCount(bytes_written_string_list, bytes_written_string, true) == 1") ); } // Some functions fail with "Unknown" message at the parse stage public void testFunctionParsingUnknown() { assertEquals("1:15: Unknown function [safe]", error("network where safe(process_name)")); } // Test unsupported array indexes public void testArrayIndexesUnsupported() { assertEquals( "1:84: Array indexes are not supported", errorParsing("registry where length(bytes_written_string_list) > 0 and bytes_written_string_list[0] == \"EN-us") ); } public void testOptionalFieldsUnsupported() { assertEquals( "1:1: extraneous input '?' expecting {'any', 'join', 'sample', 'sequence', STRING, IDENTIFIER}", errorParsing("?x where true") ); } // Test valid/supported queries public void testQueryOk() { // Mismatched type, still ok accept("process where serial_event_id == \"abcdef\""); // Equals condition accept("process where serial_event_id == 1"); // Less then condition accept("process where serial_event_id < 4"); // Greater than accept("process where exit_code > -1"); accept("process where -1 < exit_code"); // Or and And/And Not accept("process where process_name == \"impossible name\" or (serial_event_id < 4.5 and serial_event_id >= 3.1)"); accept("process where (serial_event_id<=8 and not serial_event_id > 7) and (opcode==3 and opcode>2)"); // In statement accept("process where not (exit_code > -1)\n" + " and serial_event_id in (58, 64, 69, 74, 80, 85, 90, 93, 94)"); // Combination accept("file where serial_event_id == 82 and (true == (process_name in (\"svchost.EXE\", \"bad.exe\", \"bad2.exe\")))"); // String handling accept("process where process_path == \"*\\\\MACHINE\\\\SAM\\\\SAM\\\\*\\\\Account\\\\Us*ers\\\\00*03E9\\\\F\""); // Arithmetic operators accept("file where serial_event_id - 1 == 81"); accept("file where serial_event_id + 1 == 83"); accept("file where serial_event_id * 2 == 164"); accept("file where serial_event_id / 2 == 41"); accept("file where serial_event_id % 40 == 2"); // optional fields accept("file where ?foo == 123"); accept("file where ?foo == null"); accept("file where ?`?foo` == null"); accept("file where ?`f?oo` == null"); accept("file where serial_event_id == 82 and (true == (?bar in (\"abc\", \"xyz\")))"); accept("file where concat(?foo, \"test\", ?bar) == \"onetest!\""); } // Test mapping that doesn\"t have property event.category defined public void testMissingEventCategory() { final IndexResolution idxr = loadIndexResolution("mapping-missing-event-category.json"); assertEquals("1:1: Unknown column [event.category]", error(idxr, "foo where true")); } public void testAliasErrors() { final IndexResolution idxr = loadIndexResolution("mapping-alias.json"); // Check unsupported assertEquals( "1:11: Cannot use field [user_name_alias] with unsupported type [alias]", error(idxr, "foo where user_name_alias == \"bob\"") ); // Check alias name typo assertEquals( "1:11: Unknown column [user_name_alia], did you mean any of [user_name, user_domain]?", error(idxr, "foo where user_name_alia == \"bob\"") ); } // Test all elasticsearch numeric field types public void testNumeric() { final IndexResolution idxr = loadIndexResolution("mapping-numeric.json"); accept(idxr, "foo where long_field == 0"); accept(idxr, "foo where integer_field == 0"); accept(idxr, "foo where short_field == 0"); accept(idxr, "foo where byte_field == 0"); accept(idxr, "foo where double_field == 0"); accept(idxr, "foo where float_field == 0"); accept(idxr, "foo where half_float_field == 0"); accept(idxr, "foo where scaled_float_field == 0"); accept(idxr, "foo where unsigned_long_field == 0"); // Test query against unsupported field type int assertEquals( "1:11: Cannot use field [wrong_int_type_field] with unsupported type [int]", error(idxr, "foo where wrong_int_type_field == 0") ); } public void testNoDoc() { final IndexResolution idxr = loadIndexResolution("mapping-nodoc.json"); accept(idxr, "foo where description_nodoc == \"\""); // TODO: add sort test on nodoc field once we have pipes support } public void testDate() { final IndexResolution idxr = loadIndexResolution("mapping-date.json"); accept(idxr, "foo where date == \"\""); accept(idxr, "foo where date == \"2020-02-02\""); accept(idxr, "foo where date == \"2020-02-41\""); accept(idxr, "foo where date == \"20200241\""); accept(idxr, "foo where date_with_format == \"\""); accept(idxr, "foo where date_with_format == \"2020-02-02\""); accept(idxr, "foo where date_with_format == \"2020-02-41\""); accept(idxr, "foo where date_with_format == \"20200241\""); accept(idxr, "foo where date_with_multi_format == \"\""); accept(idxr, "foo where date_with_multi_format == \"2020-02-02\""); accept(idxr, "foo where date_with_multi_format == \"2020-02-41\""); accept(idxr, "foo where date_with_multi_format == \"20200241\""); accept(idxr, "foo where date_with_multi_format == \"11:12:13\""); accept(idxr, "foo where date_nanos_field == \"\""); accept(idxr, "foo where date_nanos_field == \"2020-02-02\""); accept(idxr, "foo where date_nanos_field == \"2020-02-41\""); accept(idxr, "foo where date_nanos_field == \"20200241\""); } public void testBoolean() { final IndexResolution idxr = loadIndexResolution("mapping-boolean.json"); accept(idxr, "foo where boolean_field == true"); accept(idxr, "foo where boolean_field == \"bar\""); accept(idxr, "foo where boolean_field == 0"); accept(idxr, "foo where boolean_field == 123456"); } public void testBinary() { final IndexResolution idxr = loadIndexResolution("mapping-binary.json"); accept(idxr, "foo where blob == \"\""); accept(idxr, "foo where blob == \"bar\""); accept(idxr, "foo where blob == 0"); accept(idxr, "foo where blob == 123456"); } public void testRange() { final IndexResolution idxr = loadIndexResolution("mapping-range.json"); assertEquals( "1:11: Cannot use field [integer_range_field] with unsupported type [integer_range]", error(idxr, "foo where integer_range_field == \"\"") ); assertEquals( "1:11: Cannot use field [float_range_field] with unsupported type [float_range]", error(idxr, "foo where float_range_field == \"\"") ); assertEquals( "1:11: Cannot use field [long_range_field] with unsupported type [long_range]", error(idxr, "foo where long_range_field == \"\"") ); assertEquals( "1:11: Cannot use field [double_range_field] with unsupported type [double_range]", error(idxr, "foo where double_range_field == \"\"") ); assertEquals( "1:11: Cannot use field [date_range_field] with unsupported type [date_range]", error(idxr, "foo where date_range_field == \"\"") ); assertEquals( "1:11: Cannot use field [ip_range_field] with unsupported type [ip_range]", error(idxr, "foo where ip_range_field == \"\"") ); } public void testMixedSet() { final IndexResolution idxr = loadIndexResolution("mapping-numeric.json"); assertEquals( "1:11: 2nd argument of [long_field in (1, \"string\")] must be [long], found value [\"string\"] type [keyword]", error(idxr, "foo where long_field in (1, \"string\")") ); } public void testObject() { final IndexResolution idxr = loadIndexResolution("mapping-object.json"); accept(idxr, "foo where endgame.pid == 0"); assertEquals("1:11: Unknown column [endgame.pi], did you mean [endgame.pid]?", error(idxr, "foo where endgame.pi == 0")); } public void testNested() { final IndexResolution idxr = loadIndexResolution("mapping-nested.json"); assertEquals( "1:11: Cannot use field [processes] type [nested] due to nested fields not being supported yet", error(idxr, "foo where processes == 0") ); assertEquals( "1:11: Cannot use field [processes.pid] type [long] with unsupported nested type in hierarchy (field [processes])", error(idxr, "foo where processes.pid == 0") ); assertEquals( "1:11: Unknown column [processe.pid], did you mean any of [processes.pid, processes.path, processes.path.keyword]?", error(idxr, "foo where processe.pid == 0") ); accept(idxr, "foo where long_field == 123"); } public void testGeo() { final IndexResolution idxr = loadIndexResolution("mapping-geo.json"); assertEquals("1:11: Cannot use field [location] with unsupported type [geo_point]", error(idxr, "foo where location == 0")); assertEquals("1:11: Cannot use field [site] with unsupported type [geo_shape]", error(idxr, "foo where site == 0")); } public void testIP() { final IndexResolution idxr = loadIndexResolution("mapping-ip.json"); accept(idxr, "foo where ip_addr == 0"); } public void testVersion() { final IndexResolution idxr = loadIndexResolution("mapping-version.json"); accept(idxr, "foo where version_number == \"2.1.4\""); } public void testJoin() { final IndexResolution idxr = loadIndexResolution("mapping-join.json"); accept(idxr, "foo where serial_event_id == 0"); } public void testJoinCommand() { final IndexResolution idxr = loadIndexResolution("mapping-ip.json"); assertEquals("1:1: JOIN command is not supported", error(idxr, "join [any where true] [any where true]")); assertEquals("1:1: JOIN command is not supported", error(idxr, "join [any where true] [any where true] | tail 3")); } public void testMultiField() { final IndexResolution idxr = loadIndexResolution("mapping-multi-field.json"); accept(idxr, "foo where multi_field.raw == \"bar\""); assertEquals( "1:11: [multi_field.english == \"bar\"] cannot operate on first argument field of data type [text]: " + "No keyword/multi-field defined exact matches for [english]; define one or use MATCH/QUERY instead", error(idxr, "foo where multi_field.english == \"bar\"") ); accept(idxr, "foo where multi_field_options.raw == \"bar\""); accept(idxr, "foo where multi_field_options.key == \"bar\""); accept(idxr, "foo where multi_field_ambiguous.one == \"bar\""); accept(idxr, "foo where multi_field_ambiguous.two == \"bar\""); assertEquals( "1:11: [multi_field_ambiguous.normalized == \"bar\"] cannot operate on first argument field of data type [keyword]: " + "Normalized keyword field cannot be used for exact match operations", error(idxr, "foo where multi_field_ambiguous.normalized == \"bar\"") ); assertEquals( "1:11: Cannot use field [multi_field_nested.dep_name] type [text] with unsupported nested type in hierarchy " + "(field [multi_field_nested])", error(idxr, "foo where multi_field_nested.dep_name == \"bar\"") ); assertEquals( "1:11: Cannot use field [multi_field_nested.dep_id.keyword] type [keyword] with unsupported nested type in " + "hierarchy (field [multi_field_nested])", error(idxr, "foo where multi_field_nested.dep_id.keyword == \"bar\"") ); assertEquals( "1:11: Cannot use field [multi_field_nested.end_date] type [datetime] with unsupported nested type in " + "hierarchy (field [multi_field_nested])", error(idxr, "foo where multi_field_nested.end_date == \"\"") ); assertEquals( "1:11: Cannot use field [multi_field_nested.start_date] type [datetime] with unsupported nested type in " + "hierarchy (field [multi_field_nested])", error(idxr, "foo where multi_field_nested.start_date == \"bar\"") ); } public void testStringFunctionWithText() { final IndexResolution idxr = loadIndexResolution("mapping-multi-field.json"); assertEquals( "1:15: [string(multi_field.english)] cannot operate on field " + "of data type [text]: No keyword/multi-field defined exact matches for [english]; " + "define one or use MATCH/QUERY instead", error(idxr, "process where string(multi_field.english) == \"foo\"") ); } public void testIncorrectUsageOfStringEquals() { final IndexResolution idxr = loadIndexResolution("mapping-default.json"); assertEquals( "1:11: first argument of [:] must be [string], found value [pid] type [long]; consider using [==] instead", error(idxr, "foo where pid : 123") ); } public void testKeysWithDifferentTypes() throws Exception { assertEquals( "1:62: Sequence key [md5] type [keyword] is incompatible with key [pid] type [long]", error(index, "sequence " + "[process where true] by pid " + "[process where true] by md5") ); } public void testKeysWithDifferentButCompatibleTypes() throws Exception { accept(index, "sequence " + "[process where true] by hostname " + "[process where true] by user_domain"); } public void testKeysWithSimilarYetDifferentTypes() throws Exception { assertEquals( "1:69: Sequence key [opcode] type [long] is incompatible with key [@timestamp] type [date]", error(index, "sequence " + "[process where true] by @timestamp " + "[process where true] by opcode") ); } public void testIgnoredTimestampAndTiebreakerInSamples() { LogicalPlan plan = accept("sample by hostname [any where true] [any where true]"); Sample sample = (Sample) plan.children().get(0); assertEquals(2, sample.queries().size()); for (KeyedFilter query : sample.queries()) { assertTrue(query.timestamp() instanceof EmptyAttribute); assertTrue(query.tiebreaker() instanceof EmptyAttribute); } } }
VerifierTests
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedClassIntegrationTests.java
{ "start": 41050, "end": 41427 }
class ____ { @TimesTwo private int value; @Test void test1() { assertTrue(value <= -2, "negative"); } @Test void test2() { assertTrue(value <= -2, "negative"); } } @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @ParameterizedClass(quoteTextArguments = false) @ValueSource(ints = { -1, 1 }) @
FieldInjectionWithCustomAggregatorTestCase
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/util/ServletRequestPathUtilsTests.java
{ "start": 1279, "end": 4718 }
class ____ { @Test void parseAndCache() { // basic testParseAndCache("/app/servlet/a/b/c", "/app", "/servlet", "/a/b/c"); // contextPath only, servletPathOnly, contextPath and servletPathOnly testParseAndCache("/app/a/b/c", "/app", "", "/a/b/c"); testParseAndCache("/servlet/a/b/c", "", "/servlet", "/a/b/c"); testParseAndCache("/app1/app2/servlet1/servlet2", "/app1/app2", "/servlet1/servlet2", ""); // trailing slash testParseAndCache("/app/servlet/a/", "/app", "/servlet", "/a/"); testParseAndCache("/app/servlet/a//", "/app", "/servlet", "/a//"); } @Test void modifyPathContextWithExistingContextPath() { RequestPath requestPath = createRequestPath("/app/api/persons/42", "/app", "/api", "/persons/42"); assertThatIllegalStateException().isThrownBy(() -> requestPath.modifyContextPath("/persons")) .withMessage("Could not change context path to '/api/persons': a context path is already specified"); } @Test void modifyPathContextWhenContextPathIsNotInThePath() { RequestPath requestPath = createRequestPath("/api/persons/42", "", "/api", "/persons/42"); assertThatIllegalArgumentException().isThrownBy(() -> requestPath.modifyContextPath("/something")) .withMessage("Invalid contextPath '/api/something': " + "must match the start of requestPath: '/api/persons/42'"); } @Test void modifyPathContextReplacesServletPath() { RequestPath requestPath = createRequestPath("/api/persons/42", "", "/api", "/persons/42"); RequestPath updatedRequestPath = requestPath.modifyContextPath("/persons"); assertThat(updatedRequestPath.contextPath().value()).isEqualTo("/api/persons"); assertThat(updatedRequestPath.pathWithinApplication().value()).isEqualTo("/42"); assertThat(updatedRequestPath.value()).isEqualTo("/api/persons/42"); } @Test void modifyPathContextWithContextPathNotStartingWithSlash() { RequestPath requestPath = createRequestPath("/api/persons/42", "", "/api", "/persons/42"); assertThatIllegalArgumentException().isThrownBy(() -> requestPath.modifyContextPath("persons")) .withMessage("Invalid contextPath 'persons': must start with '/' and not end with '/'"); } @Test void modifyPathContextWithContextPathEndingWithSlash() { RequestPath requestPath = createRequestPath("/api/persons/42", "", "/api", "/persons/42"); assertThatIllegalArgumentException().isThrownBy(() -> requestPath.modifyContextPath("/persons/")) .withMessage("Invalid contextPath '/persons/': must start with '/' and not end with '/'"); } private void testParseAndCache( String requestUri, String contextPath, String servletPath, String pathWithinApplication) { RequestPath requestPath = createRequestPath(requestUri, contextPath, servletPath, pathWithinApplication); assertThat(requestPath.contextPath().value()).isEqualTo(contextPath); assertThat(requestPath.pathWithinApplication().value()).isEqualTo(pathWithinApplication); } private static RequestPath createRequestPath( String requestUri, String contextPath, String servletPath, String pathWithinApplication) { MockHttpServletRequest request = new MockHttpServletRequest("GET", requestUri); request.setContextPath(contextPath); request.setServletPath(servletPath); request.setHttpServletMapping(new MockHttpServletMapping( pathWithinApplication, contextPath, "myServlet", MappingMatch.PATH)); return ServletRequestPathUtils.parseAndCache(request); } }
ServletRequestPathUtilsTests
java
spring-projects__spring-framework
spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/SimplePropertySqlParameterSource.java
{ "start": 1520, "end": 1958 }
class ____ * similar to {@link org.springframework.validation.SimpleErrors} which is * also just used for property retrieval purposes (rather than binding). * * @author Juergen Hoeller * @since 6.1 * @see NamedParameterJdbcTemplate * @see BeanPropertySqlParameterSource * @see org.springframework.jdbc.core.simple.JdbcClient.StatementSpec#paramSource(Object) * @see org.springframework.jdbc.core.SimplePropertyRowMapper */ public
is
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-applicationhistoryservice/src/main/java/org/apache/hadoop/yarn/server/applicationhistoryservice/records/impl/pb/ContainerStartDataPBImpl.java
{ "start": 2025, "end": 7687 }
class ____ extends ContainerStartData { ContainerStartDataProto proto = ContainerStartDataProto.getDefaultInstance(); ContainerStartDataProto.Builder builder = null; boolean viaProto = false; private ContainerId containerId; private Resource resource; private NodeId nodeId; private Priority priority; public ContainerStartDataPBImpl() { builder = ContainerStartDataProto.newBuilder(); } public ContainerStartDataPBImpl(ContainerStartDataProto proto) { this.proto = proto; viaProto = true; } @Override public ContainerId getContainerId() { if (this.containerId != null) { return this.containerId; } ContainerStartDataProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasContainerId()) { return null; } this.containerId = convertFromProtoFormat(p.getContainerId()); return this.containerId; } @Override public void setContainerId(ContainerId containerId) { maybeInitBuilder(); if (containerId == null) { builder.clearContainerId(); } this.containerId = containerId; } @Override public Resource getAllocatedResource() { if (this.resource != null) { return this.resource; } ContainerStartDataProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasAllocatedResource()) { return null; } this.resource = convertFromProtoFormat(p.getAllocatedResource()); return this.resource; } @Override public void setAllocatedResource(Resource resource) { maybeInitBuilder(); if (resource == null) { builder.clearAllocatedResource(); } this.resource = resource; } @Override public NodeId getAssignedNode() { if (this.nodeId != null) { return this.nodeId; } ContainerStartDataProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasAssignedNodeId()) { return null; } this.nodeId = convertFromProtoFormat(p.getAssignedNodeId()); return this.nodeId; } @Override public void setAssignedNode(NodeId nodeId) { maybeInitBuilder(); if (nodeId == null) { builder.clearAssignedNodeId(); } this.nodeId = nodeId; } @Override public Priority getPriority() { if (this.priority != null) { return this.priority; } ContainerStartDataProtoOrBuilder p = viaProto ? proto : builder; if (!p.hasPriority()) { return null; } this.priority = convertFromProtoFormat(p.getPriority()); return this.priority; } @Override public void setPriority(Priority priority) { maybeInitBuilder(); if (priority == null) { builder.clearPriority(); } this.priority = priority; } @Override public long getStartTime() { ContainerStartDataProtoOrBuilder p = viaProto ? proto : builder; return p.getStartTime(); } @Override public void setStartTime(long startTime) { maybeInitBuilder(); builder.setStartTime(startTime); } public ContainerStartDataProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } @Override public int hashCode() { return getProto().hashCode(); } @Override public boolean equals(Object other) { if (other == null) return false; if (other.getClass().isAssignableFrom(this.getClass())) { return this.getProto().equals(this.getClass().cast(other).getProto()); } return false; } @Override public String toString() { return TextFormat.shortDebugString(getProto()); } private void mergeLocalToBuilder() { if (this.containerId != null && !((ContainerIdPBImpl) this.containerId).getProto().equals( builder.getContainerId())) { builder.setContainerId(convertToProtoFormat(this.containerId)); } if (this.resource != null) { builder.setAllocatedResource(convertToProtoFormat(this.resource)); } if (this.nodeId != null && !((NodeIdPBImpl) this.nodeId).getProto().equals( builder.getAssignedNodeId())) { builder.setAssignedNodeId(convertToProtoFormat(this.nodeId)); } if (this.priority != null && !((PriorityPBImpl) this.priority).getProto().equals( builder.getPriority())) { builder.setPriority(convertToProtoFormat(this.priority)); } } private void mergeLocalToProto() { if (viaProto) { maybeInitBuilder(); } mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = ContainerStartDataProto.newBuilder(proto); } viaProto = false; } private ContainerIdProto convertToProtoFormat(ContainerId containerId) { return ((ContainerIdPBImpl) containerId).getProto(); } private ContainerIdPBImpl convertFromProtoFormat(ContainerIdProto containerId) { return new ContainerIdPBImpl(containerId); } private ResourceProto convertToProtoFormat(Resource resource) { return ProtoUtils.convertToProtoFormat(resource); } private ResourcePBImpl convertFromProtoFormat(ResourceProto resource) { return new ResourcePBImpl(resource); } private NodeIdProto convertToProtoFormat(NodeId nodeId) { return ((NodeIdPBImpl) nodeId).getProto(); } private NodeIdPBImpl convertFromProtoFormat(NodeIdProto nodeId) { return new NodeIdPBImpl(nodeId); } private PriorityProto convertToProtoFormat(Priority priority) { return ((PriorityPBImpl) priority).getProto(); } private PriorityPBImpl convertFromProtoFormat(PriorityProto priority) { return new PriorityPBImpl(priority); } }
ContainerStartDataPBImpl
java
quarkusio__quarkus
independent-projects/bootstrap/app-model/src/main/java/io/quarkus/bootstrap/resolver/AppModelResolverException.java
{ "start": 87, "end": 414 }
class ____ extends Exception { /** * */ private static final long serialVersionUID = 1L; public AppModelResolverException(String message, Throwable cause) { super(message, cause); } public AppModelResolverException(String message) { super(message); } }
AppModelResolverException
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/BeanRegistry.java
{ "start": 9058, "end": 9557 }
interface ____ superclass * @return an instance of the bean. * @see BeanFactory#getBean(String, Class) */ <T> T bean(String name, Class<T> beanClass) throws BeansException; /** * Return a provider for the specified bean, allowing for lazy on-demand retrieval * of instances, including availability and uniqueness options. * <p>For matching a generic type, consider {@link #beanProvider(ParameterizedTypeReference)}. * @param beanClass the type the bean must match; can be an
or
java
spring-projects__spring-boot
module/spring-boot-transaction/src/test/java/org/springframework/boot/transaction/autoconfigure/TransactionManagerCustomizersTests.java
{ "start": 1154, "end": 1837 }
class ____ { @Test void customizeWithNullCustomizersShouldDoNothing() { TransactionManagerCustomizers.of(null).customize(mock(TransactionManager.class)); } @Test void customizeShouldCheckGeneric() { List<TestCustomizer<?>> list = new ArrayList<>(); list.add(new TestCustomizer<>()); list.add(new TestJtaCustomizer()); TransactionManagerCustomizers customizers = TransactionManagerCustomizers.of(list); customizers.customize(mock(PlatformTransactionManager.class)); customizers.customize(mock(JtaTransactionManager.class)); assertThat(list.get(0).getCount()).isEqualTo(2); assertThat(list.get(1).getCount()).isOne(); } static
TransactionManagerCustomizersTests
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/TestDataNodeLifeline.java
{ "start": 12802, "end": 15228 }
class ____<T> implements Answer<T> { private final CountDownLatch latch; public LatchCountingAnswer(CountDownLatch latch) { this.latch = latch; } @Override @SuppressWarnings("unchecked") public T answer(InvocationOnMock invocation) throws Throwable { T result = (T)invocation.callRealMethod(); latch.countDown(); LOG.info("Countdown, remaining latch count is {}.", latch.getCount()); return result; } } /** * Mock an exception in HeartbeatManager#updateHeartbeat and HeartbeatManager#updateLifeline * respectively, and trigger the heartbeat and lifeline in sequence. The capacityTotal obtained * before and after this operation should be the same. * @throws Exception */ @Test public void testHeartbeatAndLifelineOnError() throws Exception { final Configuration config = new HdfsConfiguration(); config.set(DFS_NAMENODE_LIFELINE_RPC_ADDRESS_KEY, "0.0.0.0:0"); try(MiniDFSCluster cluster = new MiniDFSCluster.Builder(config).numDataNodes(1).build()) { cluster.waitActive(); final FSNamesystem fsNamesystem = cluster.getNamesystem(); // Get capacityTotal before triggering heartbeat and lifeline. DatanodeStatistics datanodeStatistics = fsNamesystem.getBlockManager().getDatanodeManager().getDatanodeStatistics(); long capacityTotalBefore = datanodeStatistics.getCapacityTotal(); // Mock an exception in HeartbeatManager#updateHeartbeat and HeartbeatManager#updateLifeline. BlockManagerFaultInjector.instance = injector; DataNode dataNode = cluster.getDataNodes().get(0); BlockPoolManager blockPoolManager = dataNode.getBlockPoolManager(); for (BPOfferService bpos : blockPoolManager.getAllNamenodeThreads()) { if (bpos != null) { for (BPServiceActor actor : bpos.getBPServiceActors()) { try { actor.triggerHeartbeatForTests(); actor.sendLifelineForTests(); } catch (Throwable e) { assertTrue(e.getMessage().contains("Unknown exception")); } } } } // Get capacityTotal after triggering heartbeat and lifeline. long capacityTotalAfter = datanodeStatistics.getCapacityTotal(); // The capacityTotal should be same. assertEquals(capacityTotalBefore, capacityTotalAfter); } } }
LatchCountingAnswer
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/CsdsServiceTest.java
{ "start": 2973, "end": 4072 }
class ____ { private static final String SERVER_URI = "trafficdirector.googleapis.com"; private static final String NODE_ID = "projects/42/networks/default/nodes/5c85b298-6f5b-4722-b74a-f7d1f0ccf5ad"; private static final EnvoyProtoData.Node BOOTSTRAP_NODE = EnvoyProtoData.Node.newBuilder().setId(NODE_ID).build(); private static final BootstrapInfo BOOTSTRAP_INFO = BootstrapInfo.builder() .servers(ImmutableList.of( ServerInfo.create(SERVER_URI, InsecureChannelCredentials.create()))) .node(BOOTSTRAP_NODE) .build(); private static final FakeXdsClient XDS_CLIENT_NO_RESOURCES = new FakeXdsClient(); private static final XdsResourceType<?> LDS = XdsListenerResource.getInstance(); private static final XdsResourceType<?> CDS = XdsClusterResource.getInstance(); private static final XdsResourceType<?> RDS = XdsRouteConfigureResource.getInstance(); private static final XdsResourceType<?> EDS = XdsEndpointResource.getInstance(); public static final String FAKE_CLIENT_SCOPE = "fake"; @RunWith(JUnit4.class) public static
CsdsServiceTest
java
quarkusio__quarkus
core/deployment/src/test/java/io/quarkus/deployment/util/OuterParam.java
{ "start": 1813, "end": 2106 }
class ____<X extends Number & Comparable<X>> { public <T extends Number & Comparable<T>, U extends Comparable<U>, V extends Exception> T hhh( List<?> arg, X arg2, W arg3, InnerParamBound<X> self) throws V { return null; } public
InnerParamBound
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FunctionalInterfaceMethodChangedTest.java
{ "start": 5485, "end": 5825 }
interface ____ extends ValueReturningSuperFI { String subSam(); @Override default String superSam() { return subSam(); } } // Regression test for b/68075767 @FunctionalInterface public
ValueReturningSubFI
java
apache__flink
flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/table/SpecificAvroSavepointTypeInformationFactory.java
{ "start": 1110, "end": 1341 }
class ____ implements SavepointTypeInformationFactory { @Override public TypeInformation<?> getTypeInformation() { return new AvroTypeInfo<>(AvroRecord.class); } }
SpecificAvroSavepointTypeInformationFactory
java
qos-ch__slf4j
slf4j-simple/src/main/java/org/slf4j/simple/SimpleLogger.java
{ "start": 6677, "end": 17845 }
class ____ extends LegacyAbstractLogger { private static final long serialVersionUID = -632788891211436180L; private static final long START_TIME = System.currentTimeMillis(); protected static final int LOG_LEVEL_TRACE = LocationAwareLogger.TRACE_INT; protected static final int LOG_LEVEL_DEBUG = LocationAwareLogger.DEBUG_INT; protected static final int LOG_LEVEL_INFO = LocationAwareLogger.INFO_INT; protected static final int LOG_LEVEL_WARN = LocationAwareLogger.WARN_INT; protected static final int LOG_LEVEL_ERROR = LocationAwareLogger.ERROR_INT; static char SP = ' '; static final String TID_PREFIX = "tid="; // The OFF level can only be used in configuration files to disable logging. // It has // no printing method associated with it in o.s.Logger interface. protected static final int LOG_LEVEL_OFF = LOG_LEVEL_ERROR + 10; private static boolean INITIALIZED = false; static final SimpleLoggerConfiguration CONFIG_PARAMS = new SimpleLoggerConfiguration(); static void lazyInit() { if (INITIALIZED) { return; } INITIALIZED = true; init(); } // external software might be invoking this method directly. Do not rename // or change its semantics. static void init() { CONFIG_PARAMS.init(); } /** The current log level */ protected int currentLogLevel = LOG_LEVEL_INFO; /** The short name of this simple log instance */ private transient String shortLogName = null; /** * All system properties used by <code>SimpleLogger</code> start with this * prefix */ public static final String SYSTEM_PREFIX = "org.slf4j.simpleLogger."; public static final String LOG_KEY_PREFIX = SimpleLogger.SYSTEM_PREFIX + "log."; public static final String CACHE_OUTPUT_STREAM_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "cacheOutputStream"; public static final String WARN_LEVEL_STRING_KEY = SimpleLogger.SYSTEM_PREFIX + "warnLevelString"; public static final String LEVEL_IN_BRACKETS_KEY = SimpleLogger.SYSTEM_PREFIX + "levelInBrackets"; public static final String LOG_FILE_KEY = SimpleLogger.SYSTEM_PREFIX + "logFile"; public static final String SHOW_SHORT_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showShortLogName"; public static final String SHOW_LOG_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showLogName"; public static final String SHOW_THREAD_NAME_KEY = SimpleLogger.SYSTEM_PREFIX + "showThreadName"; public static final String SHOW_THREAD_ID_KEY = SimpleLogger.SYSTEM_PREFIX + "showThreadId"; public static final String DATE_TIME_FORMAT_KEY = SimpleLogger.SYSTEM_PREFIX + "dateTimeFormat"; public static final String SHOW_DATE_TIME_KEY = SimpleLogger.SYSTEM_PREFIX + "showDateTime"; public static final String DEFAULT_LOG_LEVEL_KEY = SimpleLogger.SYSTEM_PREFIX + "defaultLogLevel"; /** * Protected access allows only {@link SimpleLoggerFactory} and also derived classes to instantiate * SimpleLogger instances. */ protected SimpleLogger(String name) { this.name = name; String levelString = recursivelyComputeLevelString(); if (levelString != null) { this.currentLogLevel = SimpleLoggerConfiguration.stringToLevel(levelString); } else { this.currentLogLevel = CONFIG_PARAMS.defaultLogLevel; } } String recursivelyComputeLevelString() { String tempName = name; String levelString = null; int indexOfLastDot = tempName.length(); while ((levelString == null) && (indexOfLastDot > -1)) { tempName = tempName.substring(0, indexOfLastDot); levelString = CONFIG_PARAMS.getStringProperty(SimpleLogger.LOG_KEY_PREFIX + tempName, null); indexOfLastDot = String.valueOf(tempName).lastIndexOf("."); } return levelString; } /** * To avoid intermingling of log messages and associated stack traces, the two * operations are done in a synchronized block. * * @param buf * @param t */ void write(StringBuilder buf, Throwable t) { PrintStream targetStream = CONFIG_PARAMS.outputChoice.getTargetPrintStream(); synchronized (CONFIG_PARAMS) { targetStream.println(buf.toString()); writeThrowable(t, targetStream); targetStream.flush(); } } protected void writeThrowable(Throwable t, PrintStream targetStream) { if (t != null) { t.printStackTrace(targetStream); } } private String getFormattedDate() { Date now = new Date(); String dateText; synchronized (CONFIG_PARAMS.dateFormatter) { dateText = CONFIG_PARAMS.dateFormatter.format(now); } return dateText; } private String computeShortName() { return name.substring(name.lastIndexOf(".") + 1); } // /** // * For formatted messages, first substitute arguments and then log. // * // * @param level // * @param format // * @param arg1 // * @param arg2 // */ // private void formatAndLog(int level, String format, Object arg1, Object arg2) { // if (!isLevelEnabled(level)) { // return; // } // FormattingTuple tp = MessageFormatter.format(format, arg1, arg2); // log(level, tp.getMessage(), tp.getThrowable()); // } // /** // * For formatted messages, first substitute arguments and then log. // * // * @param level // * @param format // * @param arguments // * a list of 3 ore more arguments // */ // private void formatAndLog(int level, String format, Object... arguments) { // if (!isLevelEnabled(level)) { // return; // } // FormattingTuple tp = MessageFormatter.arrayFormat(format, arguments); // log(level, tp.getMessage(), tp.getThrowable()); // } /** * Is the given log level currently enabled? * * @param logLevel is this level enabled? * @return whether the logger is enabled for the given level */ protected boolean isLevelEnabled(int logLevel) { // log level are numerically ordered so can use simple numeric // comparison return (logLevel >= currentLogLevel); } /** Are {@code trace} messages currently enabled? */ public boolean isTraceEnabled() { return isLevelEnabled(LOG_LEVEL_TRACE); } /** Are {@code debug} messages currently enabled? */ public boolean isDebugEnabled() { return isLevelEnabled(LOG_LEVEL_DEBUG); } /** Are {@code info} messages currently enabled? */ public boolean isInfoEnabled() { return isLevelEnabled(LOG_LEVEL_INFO); } /** Are {@code warn} messages currently enabled? */ public boolean isWarnEnabled() { return isLevelEnabled(LOG_LEVEL_WARN); } /** Are {@code error} messages currently enabled? */ public boolean isErrorEnabled() { return isLevelEnabled(LOG_LEVEL_ERROR); } /** * SimpleLogger's implementation of * {@link org.slf4j.helpers.AbstractLogger#handleNormalizedLoggingCall(Level, Marker, String, Object[], Throwable) AbstractLogger#handleNormalizedLoggingCall} * } * * @param level the SLF4J level for this event * @param marker The marker to be used for this event, may be null. * @param messagePattern The message pattern which will be parsed and formatted * @param arguments the array of arguments to be formatted, may be null * @param throwable The exception whose stack trace should be logged, may be null */ @Override protected void handleNormalizedLoggingCall(Level level, Marker marker, String messagePattern, Object[] arguments, Throwable throwable) { List<Marker> markers = null; if (marker != null) { markers = new ArrayList<>(); markers.add(marker); } innerHandleNormalizedLoggingCall(level, markers, messagePattern, arguments, throwable); } private void innerHandleNormalizedLoggingCall(Level level, List<Marker> markers, String messagePattern, Object[] arguments, Throwable t) { StringBuilder buf = new StringBuilder(32); // Append date-time if so configured if (CONFIG_PARAMS.showDateTime) { if (CONFIG_PARAMS.dateFormatter != null) { buf.append(getFormattedDate()); buf.append(SP); } else { buf.append(System.currentTimeMillis() - START_TIME); buf.append(SP); } } // Append current thread name if so configured if (CONFIG_PARAMS.showThreadName) { buf.append('['); buf.append(Thread.currentThread().getName()); buf.append("] "); } if (CONFIG_PARAMS.showThreadId) { buf.append(TID_PREFIX); buf.append(Thread.currentThread().getId()); buf.append(SP); } if (CONFIG_PARAMS.levelInBrackets) buf.append('['); // Append a readable representation of the log level String levelStr = renderLevel(level.toInt()); buf.append(levelStr); if (CONFIG_PARAMS.levelInBrackets) buf.append(']'); buf.append(SP); // Append the name of the log instance if so configured if (CONFIG_PARAMS.showShortLogName) { if (shortLogName == null) shortLogName = computeShortName(); buf.append(String.valueOf(shortLogName)).append(" - "); } else if (CONFIG_PARAMS.showLogName) { buf.append(String.valueOf(name)).append(" - "); } if (markers != null) { buf.append(SP); for (Marker marker : markers) { buf.append(marker.getName()).append(SP); } } String formattedMessage = MessageFormatter.basicArrayFormat(messagePattern, arguments); // Append the message buf.append(formattedMessage); write(buf, t); } protected String renderLevel(int levelInt) { switch (levelInt) { case LOG_LEVEL_TRACE: return "TRACE"; case LOG_LEVEL_DEBUG: return("DEBUG"); case LOG_LEVEL_INFO: return "INFO"; case LOG_LEVEL_WARN: return CONFIG_PARAMS.warnLevelString; case LOG_LEVEL_ERROR: return "ERROR"; } throw new IllegalStateException("Unrecognized level ["+levelInt+"]"); } public void log(LoggingEvent event) { int levelInt = event.getLevel().toInt(); if (!isLevelEnabled(levelInt)) { return; } NormalizedParameters np = NormalizedParameters.normalize(event); innerHandleNormalizedLoggingCall(event.getLevel(), event.getMarkers(), np.getMessage(), np.getArguments(), event.getThrowable()); } @Override protected String getFullyQualifiedCallerName() { return null; } }
SimpleLogger
java
apache__camel
components/camel-azure/camel-azure-storage-blob/src/main/java/org/apache/camel/component/azure/storage/blob/operations/BlobChangeFeedOperations.java
{ "start": 1264, "end": 2688 }
class ____ { private final BlobChangefeedClient client; private final BlobConfigurationOptionsProxy configurationOptionsProxy; public BlobChangeFeedOperations(BlobChangefeedClient client, BlobConfigurationOptionsProxy configurationOptionsProxy) { ObjectHelper.notNull(client, "client cannot be null"); this.client = client; this.configurationOptionsProxy = configurationOptionsProxy; } public BlobOperationResponse getEvents(final Exchange exchange) { final OffsetDateTime startTime = configurationOptionsProxy.getChangeFeedStartTime(exchange); final OffsetDateTime endTime = configurationOptionsProxy.getChangeFeedEndTime(exchange); final Context context = configurationOptionsProxy.getChangeFeedContext(exchange); if (ObjectHelper.isEmpty(startTime) || ObjectHelper.isEmpty(endTime)) { return BlobOperationResponse.create(getEvents()); } else { return BlobOperationResponse.create(getEvents(startTime, endTime, context)); } } private List<BlobChangefeedEvent> getEvents() { return client.getEvents().stream().toList(); } private List<BlobChangefeedEvent> getEvents( final OffsetDateTime startTime, final OffsetDateTime endTime, final Context context) { return client.getEvents(startTime, endTime, context).stream().toList(); } }
BlobChangeFeedOperations
java
google__guava
android/guava/src/com/google/common/collect/ImmutableSortedMap.java
{ "start": 2600, "end": 5015 }
class ____<K, V> extends ImmutableMap<K, V> implements NavigableMap<K, V> { /** * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSortedMap} whose * keys and values are the result of applying the provided mapping functions to the input * elements. The generated map is sorted by the specified comparator. * * <p>If the mapped keys contain duplicates (according to the specified comparator), an {@code * IllegalArgumentException} is thrown when the collection operation is performed. (This differs * from the {@code Collector} returned by {@link Collectors#toMap(Function, Function)}, which * throws an {@code IllegalStateException}.) * * @since 33.2.0 (available since 21.0 in guava-jre) */ @IgnoreJRERequirement // Users will use this only if they're already using streams. public static <T extends @Nullable Object, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap( Comparator<? super K> comparator, Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction) { return CollectCollectors.toImmutableSortedMap(comparator, keyFunction, valueFunction); } /** * Returns a {@link Collector} that accumulates elements into an {@code ImmutableSortedMap} whose * keys and values are the result of applying the provided mapping functions to the input * elements. * * <p>If the mapped keys contain duplicates (according to the comparator), the values are merged * using the specified merging function. Entries will appear in the encounter order of the first * occurrence of the key. * * @since 33.2.0 (available since 21.0 in guava-jre) */ @IgnoreJRERequirement // Users will use this only if they're already using streams. public static <T extends @Nullable Object, K, V> Collector<T, ?, ImmutableSortedMap<K, V>> toImmutableSortedMap( Comparator<? super K> comparator, Function<? super T, ? extends K> keyFunction, Function<? super T, ? extends V> valueFunction, BinaryOperator<V> mergeFunction) { return CollectCollectors.toImmutableSortedMap( comparator, keyFunction, valueFunction, mergeFunction); } /* * TODO(kevinb): Confirm that ImmutableSortedMap is faster to construct and * uses less memory than TreeMap; then say so in the
ImmutableSortedMap
java
apache__camel
components/camel-xj/src/main/java/org/apache/camel/component/xj/XJConstants.java
{ "start": 1080, "end": 3975 }
class ____ { /** * The namespace used by xj for typehints */ public static final String NS_XJ = "http://camel.apache.org/component/xj"; /** * The namespace prefix used by xj for typehints */ public static final String NS_PREFIX_XJ = "xj"; /** * Name typehint. Used to instruct xj to write a field with that name when converting to json. On the otherhand when * converting to xml xj writes the json field name in that attribute. */ public static final String TYPE_HINT_NAME = "name"; /** * JSON-Type hint. Used to instruct xj of which type the output is when converting to json. Otherwise when * converting to xml the attribute holds the type that was in the original json document. */ public static final String TYPE_HINT_TYPE = "type"; @Metadata(description = "The XSLT file name", javaType = "String") public static final String XSLT_FILE_NAME = Exchange.XSLT_FILE_NAME; /** * Mapping from json-types to typehint names */ static final Map<JsonToken, String> JSONTYPE_TYPE_MAP; /** * Mapping from typehint names to json-types */ static final Map<String, JsonToken> TYPE_JSONTYPE_MAP; static final String UNSUPPORTED_OPERATION_EXCEPTION_MESSAGE = "unsupported / not yet implemented"; /** * Field name when xml contains mixed-content */ static final String JSON_WRITER_MIXED_CONTENT_TEXT_KEY = "#text"; static { final Map<JsonToken, String> jsonTypeTypeMap = new EnumMap<>(JsonToken.class); jsonTypeTypeMap.put(JsonToken.START_OBJECT, "object"); jsonTypeTypeMap.put(JsonToken.END_OBJECT, "object"); jsonTypeTypeMap.put(JsonToken.START_ARRAY, "array"); jsonTypeTypeMap.put(JsonToken.END_ARRAY, "array"); jsonTypeTypeMap.put(JsonToken.VALUE_STRING, "string"); jsonTypeTypeMap.put(JsonToken.VALUE_NUMBER_INT, "int"); jsonTypeTypeMap.put(JsonToken.VALUE_NUMBER_FLOAT, "float"); jsonTypeTypeMap.put(JsonToken.VALUE_TRUE, "boolean"); jsonTypeTypeMap.put(JsonToken.VALUE_FALSE, "boolean"); jsonTypeTypeMap.put(JsonToken.VALUE_NULL, "null"); JSONTYPE_TYPE_MAP = Collections.unmodifiableMap(jsonTypeTypeMap); final Map<String, JsonToken> typeJsonTypeMap = new HashMap<>(); typeJsonTypeMap.put("object", JsonToken.START_OBJECT); typeJsonTypeMap.put("array", JsonToken.START_ARRAY); typeJsonTypeMap.put("string", JsonToken.VALUE_STRING); typeJsonTypeMap.put("int", JsonToken.VALUE_NUMBER_INT); typeJsonTypeMap.put("float", JsonToken.VALUE_NUMBER_FLOAT); typeJsonTypeMap.put("boolean", JsonToken.VALUE_TRUE); typeJsonTypeMap.put("null", JsonToken.VALUE_NULL); TYPE_JSONTYPE_MAP = Collections.unmodifiableMap(typeJsonTypeMap); } private XJConstants() { } }
XJConstants
java
google__guice
core/test/com/google/inject/spi/ProviderMethodsTest.java
{ "start": 23449, "end": 24074 }
class ____ extends SuperClassModule { @Override Number providerMethod() { return 2D; } } try { Guice.createInjector(new SubClassModule()); fail(); } catch (CreationException e) { assertContains( e.getMessage(), "Overriding @Provides methods is not allowed.", "@Provides method: ProviderMethodsTest$SuperClassModule.providerMethod()", "overridden by: ProviderMethodsTest$3SubClassModule.providerMethod()"); } } @Test public void testOverrideProviderMethod_overrideDoesntHaveProvides_withNewAnnotation() {
SubClassModule
java
spring-projects__spring-boot
module/spring-boot-hazelcast/src/main/java/org/springframework/boot/hazelcast/autoconfigure/HazelcastJpaDependencyAutoConfiguration.java
{ "start": 2539, "end": 2776 }
class ____ extends EntityManagerFactoryDependsOnPostProcessor { HazelcastInstanceEntityManagerFactoryDependsOnPostProcessor() { super("hazelcastInstance"); } } static
HazelcastInstanceEntityManagerFactoryDependsOnPostProcessor
java
apache__camel
core/camel-main/src/main/java/org/apache/camel/main/Main.java
{ "start": 1085, "end": 1143 }
class ____ booting up Camel in standalone mode. */ public
for
java
apache__camel
components/camel-salesforce/camel-salesforce-component/src/test/java/org/apache/camel/component/salesforce/SalesforceEndpointTest.java
{ "start": 2017, "end": 2356 }
enum ____ of the operationName field in SalesforceEndpoint, set the enums parameter to:\n" + Arrays.stream(operationNamesInEnum) .collect(Collectors.joining(","))); } }
parameter
java
apache__camel
components/camel-telemetry/src/main/java/org/apache/camel/telemetry/TagConstants.java
{ "start": 847, "end": 2440 }
class ____ { public static final String ERROR = "error"; public static final String COMPONENT = "component"; public static final String EXCHANGE_ID = "exchangeId"; public static final String OP = "op"; // General attributes public static final String SERVER_ADDRESS = "server.address"; public static final String SERVER_PROTOCOL = "server.protocol"; public static final String SERVER_REGION = "server.region"; // User attributes public static final String USER_NAME = "user.name"; public static final String USER_ID = "user.id"; // HTTP attributes public static final String HTTP_STATUS = "http.status_code"; public static final String HTTP_METHOD = "http.method"; public static final String HTTP_URL = "http.url"; public static final String URL_SCHEME = "url.scheme"; public static final String URL_PATH = "url.path"; public static final String URL_QUERY = "url.query"; // Messaging attributes public static final String MESSAGE_BUS_DESTINATION = "messaging.destination.name"; public static final String MESSAGE_ID = "messaging.message.id"; // File attributes public static final String FILE_NAME = "file.name"; // Database attributes public static final String DB_SYSTEM = "db.system"; public static final String DB_NAME = "db.name"; public static final String DB_STATEMENT = "db.statement"; // Exception attributes public static final String EXCEPTION_ESCAPED = "exception.escaped"; public static final String EXCEPTION_MESSAGE = "exception.message"; }
TagConstants
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/ser/TestJsonSerialize.java
{ "start": 2736, "end": 3051 }
class ____{ @JsonProperty protected String id; @JsonProperty protected String name; public Bar294() { } public Bar294(String id) { this.id = id; } public String getId() { return id; } public String getName() { return name; } } static
Bar294
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/node/DiscoveryNodes.java
{ "start": 22755, "end": 28295 }
class ____ { private final String localNodeId; @Nullable private final DiscoveryNode previousMasterNode; @Nullable private final DiscoveryNode newMasterNode; private final List<DiscoveryNode> removed; private final List<DiscoveryNode> added; private Delta( @Nullable DiscoveryNode previousMasterNode, @Nullable DiscoveryNode newMasterNode, String localNodeId, List<DiscoveryNode> removed, List<DiscoveryNode> added ) { this.previousMasterNode = previousMasterNode; this.newMasterNode = newMasterNode; this.localNodeId = localNodeId; this.removed = removed; this.added = added; } public boolean hasChanges() { return masterNodeChanged() || removed.isEmpty() == false || added.isEmpty() == false; } public boolean masterNodeChanged() { return Objects.equals(newMasterNode, previousMasterNode) == false; } @Nullable public DiscoveryNode previousMasterNode() { return previousMasterNode; } @Nullable public DiscoveryNode newMasterNode() { return newMasterNode; } public boolean removed() { return removed.isEmpty() == false; } public List<DiscoveryNode> removedNodes() { return removed; } public boolean added() { return added.isEmpty() == false; } public List<DiscoveryNode> addedNodes() { return added; } @Override public String toString() { return shortSummary(); } public String shortSummary() { final StringBuilder summary = new StringBuilder(); if (masterNodeChanged()) { summary.append("master node changed {previous ["); if (previousMasterNode != null) { previousMasterNode.appendDescriptionWithoutAttributes(summary); } summary.append("], current ["); if (newMasterNode != null) { newMasterNode.appendDescriptionWithoutAttributes(summary); } summary.append("]}"); } if (removed()) { if (summary.length() > 0) { summary.append(", "); } summary.append("removed {"); addCommaSeparatedNodesWithoutAttributes(removedNodes().iterator(), summary); summary.append('}'); } if (added()) { // ignore ourselves when reporting on nodes being added final Iterator<DiscoveryNode> addedNodesIterator = addedNodes().stream() .filter(node -> node.getId().equals(localNodeId) == false) .iterator(); if (addedNodesIterator.hasNext()) { if (summary.length() > 0) { summary.append(", "); } summary.append("added {"); addCommaSeparatedNodesWithoutAttributes(addedNodesIterator, summary); summary.append('}'); } } return summary.toString(); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(masterNodeId); if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_9_X)) { out.writeVLong(nodeLeftGeneration); } // else nodeLeftGeneration is zero, or we're sending this to a remote cluster which does not care about the nodeLeftGeneration out.writeCollection(nodes.values()); } public static DiscoveryNodes readFrom(StreamInput in, DiscoveryNode localNode) throws IOException { Builder builder = new Builder(); if (in.readBoolean()) { builder.masterNodeId(in.readString()); } if (localNode != null) { builder.localNodeId(localNode.getId()); } if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_9_X)) { builder.nodeLeftGeneration(in.readVLong()); } // else nodeLeftGeneration is zero, or we're receiving this from a remote cluster so the nodeLeftGeneration does not matter to us int size = in.readVInt(); for (int i = 0; i < size; i++) { DiscoveryNode node = new DiscoveryNode(in); if (localNode != null && node.getId().equals(localNode.getId())) { // reuse the same instance of our address and local node id for faster equality node = localNode; } // some one already built this and validated it's OK, skip the n2 scans assert builder.validateAdd(node) == null : "building disco nodes from network doesn't pass preflight: " + builder.validateAdd(node); builder.putUnsafe(node); } return builder.build(); } public static Diff<DiscoveryNodes> readDiffFrom(StreamInput in, DiscoveryNode localNode) throws IOException { return SimpleDiffable.readDiffFrom(in1 -> readFrom(in1, localNode), in); } public static Builder builder() { return new Builder(); } public static Builder builder(DiscoveryNodes nodes) { return new Builder(nodes); } public static
Delta
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/checkpointing/StreamCheckpointingITCase.java
{ "start": 2048, "end": 2136 }
interface ____ the "exactly once" semantics. */ @SuppressWarnings("serial") public
reflects
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/utils/LogTest.java
{ "start": 1104, "end": 3034 }
class ____ { @Test void testLogName() { Log log1 = new Log(); Log log2 = new Log(); Log log3 = new Log(); log1.setLogName("log-name"); log2.setLogName("log-name"); log3.setLogName("log-name-other"); assertThat(log1.getLogName(), equalTo("log-name")); Assertions.assertEquals(log1, log2); Assertions.assertEquals(log1.hashCode(), log2.hashCode()); Assertions.assertNotEquals(log1, log3); } @Test void testLogLevel() { Log log1 = new Log(); Log log2 = new Log(); Log log3 = new Log(); log1.setLogLevel(Level.ALL); log2.setLogLevel(Level.ALL); log3.setLogLevel(Level.DEBUG); assertThat(log1.getLogLevel(), is(Level.ALL)); Assertions.assertEquals(log1, log2); Assertions.assertEquals(log1.hashCode(), log2.hashCode()); Assertions.assertNotEquals(log1, log3); } @Test void testLogMessage() { Log log1 = new Log(); Log log2 = new Log(); Log log3 = new Log(); log1.setLogMessage("log-message"); log2.setLogMessage("log-message"); log3.setLogMessage("log-message-other"); assertThat(log1.getLogMessage(), equalTo("log-message")); Assertions.assertEquals(log1, log2); Assertions.assertEquals(log1.hashCode(), log2.hashCode()); Assertions.assertNotEquals(log1, log3); } @Test void testLogThread() { Log log1 = new Log(); Log log2 = new Log(); Log log3 = new Log(); log1.setLogThread("log-thread"); log2.setLogThread("log-thread"); log3.setLogThread("log-thread-other"); assertThat(log1.getLogThread(), equalTo("log-thread")); Assertions.assertEquals(log1, log2); Assertions.assertEquals(log1.hashCode(), log2.hashCode()); Assertions.assertNotEquals(log1, log3); } }
LogTest
java
quarkusio__quarkus
core/deployment/src/main/java/io/quarkus/deployment/configuration/tracker/ConfigTrackingInterceptor.java
{ "start": 984, "end": 1294 }
interface ____ { void write(ConfigTrackingConfig config, BuildTimeConfigurationReader.ReadResult configReadResult, LaunchMode launchMode, Path buildDirectory); } /** * Provides an immutable map of options that were read during the build. */ public
ConfigurationWriter
java
apache__kafka
clients/src/test/java/org/apache/kafka/clients/consumer/internals/metrics/OffsetCommitMetricsManagerTest.java
{ "start": 1167, "end": 2487 }
class ____ { private final Time time = new MockTime(); private final Metrics metrics = new Metrics(time); @Test public void testOffsetCommitMetrics() { // Assuming 'metrics' is an instance of your Metrics class // Create an instance of OffsetCommitMetricsManager OffsetCommitMetricsManager metricsManager = new OffsetCommitMetricsManager(metrics); // Assert the existence of metrics assertNotNull(metrics.metric(metricsManager.commitLatencyAvg)); assertNotNull(metrics.metric(metricsManager.commitLatencyMax)); assertNotNull(metrics.metric(metricsManager.commitRate)); assertNotNull(metrics.metric(metricsManager.commitTotal)); // Record request latency metricsManager.recordRequestLatency(100); metricsManager.recordRequestLatency(102); metricsManager.recordRequestLatency(98); // Assert the recorded latency assertEquals(100d, metrics.metric(metricsManager.commitLatencyAvg).metricValue()); assertEquals(102d, metrics.metric(metricsManager.commitLatencyMax).metricValue()); assertEquals(0.1d, metrics.metric(metricsManager.commitRate).metricValue()); assertEquals(3d, metrics.metric(metricsManager.commitTotal).metricValue()); } }
OffsetCommitMetricsManagerTest
java
elastic__elasticsearch
x-pack/plugin/async-search/src/main/java/org/elasticsearch/xpack/search/TransportSubmitAsyncSearchAction.java
{ "start": 1889, "end": 12482 }
class ____ extends HandledTransportAction<SubmitAsyncSearchRequest, AsyncSearchResponse> { private final ClusterService clusterService; private final NodeClient nodeClient; private final SearchService searchService; private final TransportSearchAction searchAction; private final ThreadContext threadContext; private final AsyncTaskIndexService<AsyncSearchResponse> store; @Inject public TransportSubmitAsyncSearchAction( ClusterService clusterService, TransportService transportService, ActionFilters actionFilters, NamedWriteableRegistry registry, Client client, NodeClient nodeClient, SearchService searchService, TransportSearchAction searchAction, BigArrays bigArrays ) { super( SubmitAsyncSearchAction.NAME, transportService, actionFilters, SubmitAsyncSearchRequest::new, EsExecutors.DIRECT_EXECUTOR_SERVICE ); this.clusterService = clusterService; this.nodeClient = nodeClient; this.searchService = searchService; this.searchAction = searchAction; this.threadContext = transportService.getThreadPool().getThreadContext(); this.store = new AsyncTaskIndexService<>( XPackPlugin.ASYNC_RESULTS_INDEX, clusterService, threadContext, client, ASYNC_SEARCH_ORIGIN, AsyncSearchResponse::new, registry, bigArrays ); } @Override protected void doExecute(Task submitTask, SubmitAsyncSearchRequest request, ActionListener<AsyncSearchResponse> submitListener) { final SearchRequest searchRequest = createSearchRequest(request, submitTask, request.getKeepAlive()); try (var ignored = threadContext.newTraceContext()) { AsyncSearchTask searchTask = (AsyncSearchTask) taskManager.register( "transport", TransportSearchAction.TYPE.name(), searchRequest ); searchAction.execute(searchTask, searchRequest, searchTask.getSearchProgressActionListener()); ActionListener<AsyncSearchResponse> submitListenerWithHeaders = submitListener.map(response -> { threadContext.addResponseHeader(AsyncExecutionId.ASYNC_EXECUTION_IS_RUNNING_HEADER, response.isRunning() ? "?1" : "?0"); if (response.getId() != null) { threadContext.addResponseHeader(AsyncExecutionId.ASYNC_EXECUTION_ID_HEADER, response.getId()); } return response; }); searchTask.addCompletionListener(new ActionListener<>() { @Override public void onResponse(AsyncSearchResponse searchResponse) { if (searchResponse.isRunning() || request.isKeepOnCompletion()) { // the task is still running and the user cannot wait more so we create // a document for further retrieval try { final String docId = searchTask.getExecutionId().getDocId(); // creates the fallback response if the node crashes/restarts in the middle of the request // TODO: store intermediate results ? AsyncSearchResponse initialResp = searchResponse.clone(searchResponse.getId()); searchResponse.mustIncRef(); try { store.createResponse( docId, searchTask.getOriginHeaders(), initialResp, ActionListener.runAfter(new ActionListener<>() { @Override public void onResponse(DocWriteResponse r) { if (searchResponse.isRunning()) { try { // store the final response on completion unless the submit is cancelled searchTask.addCompletionListener( finalResponse -> onFinalResponse(searchTask, finalResponse, () -> {}) ); } finally { submitListenerWithHeaders.onResponse(searchResponse); } } else { searchResponse.mustIncRef(); onFinalResponse( searchTask, searchResponse, () -> ActionListener.respondAndRelease(submitListenerWithHeaders, searchResponse) ); } } @Override public void onFailure(Exception exc) { onFatalFailure( searchTask, exc, searchResponse.isRunning(), "fatal failure: unable to store initial response", submitListenerWithHeaders ); } }, searchResponse::decRef) ); } finally { initialResp.decRef(); } } catch (Exception exc) { onFatalFailure( searchTask, exc, searchResponse.isRunning(), "fatal failure: generic error", submitListenerWithHeaders ); } } else { try (searchTask) { // the task completed within the timeout so the response is sent back to the user // with a null id since nothing was stored on the cluster. taskManager.unregister(searchTask); ActionListener.respondAndRelease(submitListenerWithHeaders, searchResponse.clone(null)); } } } @Override public void onFailure(Exception exc) { // this will only ever be called if there is an issue scheduling the thread that executes // the completion listener once the wait for completion timeout expires. onFatalFailure(searchTask, exc, true, "fatal failure: addCompletionListener", submitListenerWithHeaders); } }, request.getWaitForCompletionTimeout()); } } private SearchRequest createSearchRequest(SubmitAsyncSearchRequest request, Task submitTask, TimeValue keepAlive) { String docID = UUIDs.randomBase64UUID(); Map<String, String> originHeaders = ClientHelper.getPersistableSafeSecurityHeaders( nodeClient.threadPool().getThreadContext(), clusterService.state() ); var originalSearchRequest = request.getSearchRequest(); SearchRequest searchRequest = new SearchRequest(originalSearchRequest) { @Override public AsyncSearchTask createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> taskHeaders) { AsyncExecutionId searchId = new AsyncExecutionId(docID, new TaskId(nodeClient.getLocalNodeId(), id)); return new AsyncSearchTask( id, type, action, parentTaskId, this::buildDescription, keepAlive, originHeaders, taskHeaders, searchId, store.getClientWithOrigin(), nodeClient.threadPool(), isCancelled -> () -> searchService.aggReduceContextBuilder(isCancelled, originalSearchRequest.source().aggregations()) .forFinalReduction(), store ); } }; searchRequest.setParentTask(new TaskId(nodeClient.getLocalNodeId(), submitTask.getId())); return searchRequest; } private void onFatalFailure( AsyncSearchTask task, Exception error, boolean shouldCancel, String cancelReason, ActionListener<AsyncSearchResponse> listener ) { if (shouldCancel && task.isCancelled() == false) { task.cancelTask(() -> closeTaskAndFail(task, error, listener), cancelReason); } else { closeTaskAndFail(task, error, listener); } } private void closeTaskAndFail(AsyncSearchTask task, Exception error, ActionListener<AsyncSearchResponse> listener) { try { task.addCompletionListener(finalResponse -> { try (task) { taskManager.unregister(task); } }); } finally { listener.onFailure(error); } } private void onFinalResponse(AsyncSearchTask searchTask, AsyncSearchResponse response, Runnable nextAction) { store.updateResponse( searchTask.getExecutionId().getDocId(), threadContext.getResponseHeaders(), response, ActionListener.running(() -> { try (searchTask) { taskManager.unregister(searchTask); } nextAction.run(); }) ); } }
TransportSubmitAsyncSearchAction
java
elastic__elasticsearch
x-pack/plugin/ml/src/internalClusterTest/java/org/elasticsearch/xpack/ml/integration/DataFrameAnalyticsConfigProviderIT.java
{ "start": 2303, "end": 19767 }
class ____ extends MlSingleNodeTestCase { private static final TimeValue TIMEOUT = TimeValue.timeValueSeconds(5); private DataFrameAnalyticsConfigProvider configProvider; private String dummyAuthenticationHeader; @Before public void createComponents() throws Exception { configProvider = new DataFrameAnalyticsConfigProvider( client(), xContentRegistry(), // We can't change the signature of createComponents to e.g. pass differing values of includeNodeInfo to pass to the // DataFrameAnalyticsAuditor constructor. Instead we generate a random boolean value for that purpose. new DataFrameAnalyticsAuditor( client(), getInstanceFromNode(ClusterService.class), TestIndexNameExpressionResolver.newInstance(), randomBoolean() ), getInstanceFromNode(ClusterService.class) ); dummyAuthenticationHeader = Authentication.newRealmAuthentication( new User("dummy"), new Authentication.RealmRef("name", "type", "node") ).encode(); waitForMlTemplates(); } public void testGet_ConfigDoesNotExist() throws InterruptedException { AtomicReference<DataFrameAnalyticsConfig> configHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); blockingCall(actionListener -> configProvider.get("missing", actionListener), configHolder, exceptionHolder); assertThat(configHolder.get(), is(nullValue())); assertThat(exceptionHolder.get(), is(notNullValue())); assertThat(exceptionHolder.get(), is(instanceOf(ResourceNotFoundException.class))); } public void testPutAndGet() throws InterruptedException { String configId = "config-id"; // Create valid config DataFrameAnalyticsConfig config = DataFrameAnalyticsConfigTests.createRandom(configId); { // Put the config and verify the response AtomicReference<DataFrameAnalyticsConfig> configHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); blockingCall(actionListener -> configProvider.put(config, emptyMap(), TIMEOUT, actionListener), configHolder, exceptionHolder); assertThat(configHolder.get(), is(notNullValue())); assertThat(configHolder.get(), is(equalTo(config))); assertThat(exceptionHolder.get(), is(nullValue())); } { // Get the config back and verify the response AtomicReference<DataFrameAnalyticsConfig> configHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); blockingCall(actionListener -> configProvider.get(configId, actionListener), configHolder, exceptionHolder); assertThat(configHolder.get(), is(notNullValue())); assertThat(configHolder.get(), is(equalTo(config))); assertThat(exceptionHolder.get(), is(nullValue())); } } public void testPutAndGet_WithSecurityHeaders() throws InterruptedException { String configId = "config-id"; DataFrameAnalyticsConfig config = DataFrameAnalyticsConfigTests.createRandom(configId); Map<String, String> securityHeaders = Collections.singletonMap("_xpack_security_authentication", dummyAuthenticationHeader); { // Put the config and verify the response AtomicReference<DataFrameAnalyticsConfig> configHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); blockingCall( actionListener -> configProvider.put(config, securityHeaders, TIMEOUT, actionListener), configHolder, exceptionHolder ); assertThat(configHolder.get(), is(notNullValue())); assertThat(configHolder.get(), is(equalTo(new DataFrameAnalyticsConfig.Builder(config).setHeaders(securityHeaders).build()))); assertThat(exceptionHolder.get(), is(nullValue())); } { // Get the config back and verify the response AtomicReference<DataFrameAnalyticsConfig> configHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); blockingCall(actionListener -> configProvider.get(configId, actionListener), configHolder, exceptionHolder); assertThat(configHolder.get(), is(notNullValue())); assertThat(configHolder.get(), is(equalTo(new DataFrameAnalyticsConfig.Builder(config).setHeaders(securityHeaders).build()))); assertThat(exceptionHolder.get(), is(nullValue())); } } public void testPut_ConfigAlreadyExists() throws InterruptedException { String configId = "config-id"; { // Put the config and verify the response AtomicReference<DataFrameAnalyticsConfig> configHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); DataFrameAnalyticsConfig initialConfig = DataFrameAnalyticsConfigTests.createRandom(configId); blockingCall( actionListener -> configProvider.put(initialConfig, emptyMap(), TIMEOUT, actionListener), configHolder, exceptionHolder ); assertThat(configHolder.get(), is(notNullValue())); assertThat(configHolder.get(), is(equalTo(initialConfig))); assertThat(exceptionHolder.get(), is(nullValue())); } { // Try putting the config with the same id and verify the response AtomicReference<DataFrameAnalyticsConfig> configHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); DataFrameAnalyticsConfig configWithSameId = DataFrameAnalyticsConfigTests.createRandom(configId); blockingCall( actionListener -> configProvider.put(configWithSameId, emptyMap(), TIMEOUT, actionListener), configHolder, exceptionHolder ); assertThat(configHolder.get(), is(nullValue())); assertThat(exceptionHolder.get(), is(notNullValue())); assertThat(exceptionHolder.get(), is(instanceOf(ResourceAlreadyExistsException.class))); } } public void testUpdate() throws Exception { String configId = "config-id"; DataFrameAnalyticsConfig initialConfig = DataFrameAnalyticsConfigTests.createRandom(configId); { AtomicReference<DataFrameAnalyticsConfig> configHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); blockingCall( actionListener -> configProvider.put(initialConfig, emptyMap(), TIMEOUT, actionListener), configHolder, exceptionHolder ); assertNoException(exceptionHolder); assertThat(configHolder.get(), is(notNullValue())); assertThat(configHolder.get(), is(equalTo(initialConfig))); } { // Update that changes description AtomicReference<DataFrameAnalyticsConfig> updatedConfigHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); DataFrameAnalyticsConfigUpdate configUpdate = new DataFrameAnalyticsConfigUpdate.Builder(configId).setDescription( "description-1" ).build(); blockingCall( actionListener -> configProvider.update(configUpdate, emptyMap(), ClusterState.EMPTY_STATE, actionListener), updatedConfigHolder, exceptionHolder ); assertNoException(exceptionHolder); assertThat(updatedConfigHolder.get(), is(notNullValue())); assertThat( updatedConfigHolder.get(), is(equalTo(new DataFrameAnalyticsConfig.Builder(initialConfig).setDescription("description-1").build())) ); } { // Update that changes model memory limit AtomicReference<DataFrameAnalyticsConfig> updatedConfigHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); DataFrameAnalyticsConfigUpdate configUpdate = new DataFrameAnalyticsConfigUpdate.Builder(configId).setModelMemoryLimit( ByteSizeValue.ofBytes(1024) ).build(); blockingCall( actionListener -> configProvider.update(configUpdate, emptyMap(), ClusterState.EMPTY_STATE, actionListener), updatedConfigHolder, exceptionHolder ); assertNoException(exceptionHolder); assertThat(updatedConfigHolder.get(), is(notNullValue())); assertThat( updatedConfigHolder.get(), is( equalTo( new DataFrameAnalyticsConfig.Builder(initialConfig).setDescription("description-1") .setModelMemoryLimit(ByteSizeValue.ofBytes(1024)) .build() ) ) ); } { // Noop update AtomicReference<DataFrameAnalyticsConfig> updatedConfigHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); DataFrameAnalyticsConfigUpdate configUpdate = new DataFrameAnalyticsConfigUpdate.Builder(configId).build(); blockingCall( actionListener -> configProvider.update(configUpdate, emptyMap(), ClusterState.EMPTY_STATE, actionListener), updatedConfigHolder, exceptionHolder ); assertNoException(exceptionHolder); assertThat(updatedConfigHolder.get(), is(notNullValue())); assertThat( updatedConfigHolder.get(), is( equalTo( new DataFrameAnalyticsConfig.Builder(initialConfig).setDescription("description-1") .setModelMemoryLimit(ByteSizeValue.ofBytes(1024)) .build() ) ) ); } { // Update that changes both description and model memory limit AtomicReference<DataFrameAnalyticsConfig> updatedConfigHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); DataFrameAnalyticsConfigUpdate configUpdate = new DataFrameAnalyticsConfigUpdate.Builder(configId).setDescription( "description-2" ).setModelMemoryLimit(ByteSizeValue.ofBytes(2048)).build(); blockingCall( actionListener -> configProvider.update(configUpdate, emptyMap(), ClusterState.EMPTY_STATE, actionListener), updatedConfigHolder, exceptionHolder ); assertNoException(exceptionHolder); assertThat(updatedConfigHolder.get(), is(notNullValue())); assertThat( updatedConfigHolder.get(), is( equalTo( new DataFrameAnalyticsConfig.Builder(initialConfig).setDescription("description-2") .setModelMemoryLimit(ByteSizeValue.ofBytes(2048)) .build() ) ) ); } { // Update that applies security headers Map<String, String> securityHeaders = Collections.singletonMap("_xpack_security_authentication", dummyAuthenticationHeader); AtomicReference<DataFrameAnalyticsConfig> updatedConfigHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); DataFrameAnalyticsConfigUpdate configUpdate = new DataFrameAnalyticsConfigUpdate.Builder(configId).build(); blockingCall( actionListener -> configProvider.update(configUpdate, securityHeaders, ClusterState.EMPTY_STATE, actionListener), updatedConfigHolder, exceptionHolder ); assertNoException(exceptionHolder); assertThat(updatedConfigHolder.get(), is(notNullValue())); assertThat( updatedConfigHolder.get(), is( equalTo( new DataFrameAnalyticsConfig.Builder(initialConfig).setDescription("description-2") .setModelMemoryLimit(ByteSizeValue.ofBytes(2048)) .setHeaders(securityHeaders) .build() ) ) ); } } public void testUpdate_ConfigDoesNotExist() throws InterruptedException { AtomicReference<DataFrameAnalyticsConfig> updatedConfigHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); DataFrameAnalyticsConfigUpdate configUpdate = new DataFrameAnalyticsConfigUpdate.Builder("missing").build(); blockingCall( actionListener -> configProvider.update(configUpdate, emptyMap(), ClusterState.EMPTY_STATE, actionListener), updatedConfigHolder, exceptionHolder ); assertThat(updatedConfigHolder.get(), is(nullValue())); assertThat(exceptionHolder.get(), is(notNullValue())); assertThat(exceptionHolder.get(), is(instanceOf(ResourceNotFoundException.class))); } public void testUpdate_UpdateCannotBeAppliedWhenTaskIsRunning() throws InterruptedException { String configId = "config-id"; DataFrameAnalyticsConfig initialConfig = DataFrameAnalyticsConfigTests.createRandom(configId); { AtomicReference<DataFrameAnalyticsConfig> configHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); blockingCall( actionListener -> configProvider.put(initialConfig, emptyMap(), TIMEOUT, actionListener), configHolder, exceptionHolder ); assertThat(configHolder.get(), is(notNullValue())); assertThat(configHolder.get(), is(equalTo(initialConfig))); assertThat(exceptionHolder.get(), is(nullValue())); } { // Update that tries to change model memory limit while the analytics is running AtomicReference<DataFrameAnalyticsConfig> updatedConfigHolder = new AtomicReference<>(); AtomicReference<Exception> exceptionHolder = new AtomicReference<>(); // Important: the new value specified here must be one that it's impossible for DataFrameAnalyticsConfigTests.createRandom // to have used originally. If the update is a no-op then the test fails. DataFrameAnalyticsConfigUpdate configUpdate = new DataFrameAnalyticsConfigUpdate.Builder(configId).setModelMemoryLimit( ByteSizeValue.ofMb(1234) ).build(); ClusterState clusterState = clusterStateWithRunningAnalyticsTask(configId, DataFrameAnalyticsState.ANALYZING); blockingCall( actionListener -> configProvider.update(configUpdate, emptyMap(), clusterState, actionListener), updatedConfigHolder, exceptionHolder ); assertThat(updatedConfigHolder.get(), is(nullValue())); assertThat(exceptionHolder.get(), is(notNullValue())); assertThat(exceptionHolder.get(), is(instanceOf(ElasticsearchStatusException.class))); ElasticsearchStatusException e = (ElasticsearchStatusException) exceptionHolder.get(); assertThat(e.status(), is(equalTo(RestStatus.CONFLICT))); assertThat(e.getMessage(), is(equalTo("Cannot update analytics [config-id] unless it's stopped"))); } } private static ClusterState clusterStateWithRunningAnalyticsTask(String analyticsId, DataFrameAnalyticsState analyticsState) { PersistentTasksCustomMetadata.Builder builder = PersistentTasksCustomMetadata.builder(); builder.addTask( MlTasks.dataFrameAnalyticsTaskId(analyticsId), MlTasks.DATA_FRAME_ANALYTICS_TASK_NAME, new StartDataFrameAnalyticsAction.TaskParams(analyticsId, MlConfigVersion.CURRENT, false), new PersistentTasksCustomMetadata.Assignment("node", "test assignment") ); builder.updateTaskState( MlTasks.dataFrameAnalyticsTaskId(analyticsId), new DataFrameAnalyticsTaskState(analyticsState, builder.getLastAllocationId(), null, Instant.now()) ); PersistentTasksCustomMetadata tasks = builder.build(); return ClusterState.builder(new ClusterName("cluster")) .metadata(Metadata.builder().putCustom(PersistentTasksCustomMetadata.TYPE, tasks).build()) .build(); } }
DataFrameAnalyticsConfigProviderIT
java
quarkusio__quarkus
extensions/smallrye-graphql/runtime/src/main/java/io/quarkus/smallrye/graphql/runtime/SmallRyeGraphQLRuntimeConfig.java
{ "start": 502, "end": 1958 }
interface ____ { /** * If GraphQL UI should be enabled. By default, GraphQL UI is enabled if it is included (see {@code always-include}). */ @WithName("ui.enabled") @WithDefault("true") boolean enabled(); /** * If GraphQL UI should be enabled. By default, GraphQL UI is enabled if it is included (see {@code always-include}). * * @deprecated use {@code quarkus.smallrye-graphql.ui.enabled} instead */ @WithName("ui.enable") @Deprecated(since = "3.26", forRemoval = true) Optional<Boolean> enable(); /** * Specifies the field visibility for the GraphQL schema. * This configuration item allows you to define comma-separated list of patterns (GraphQLType.GraphQLField). * These patterns are used to determine which fields should be excluded from the schema. * Special value {@code no-introspection} will disable introspection fields. * For more info see <a href="https://smallrye.io/smallrye-graphql/docs/schema/field-visibility">graphql-java * documentation</a> */ @WithDefault("default") String fieldVisibility(); /** * Excludes all the 'null' fields in the GraphQL response's <code>data</code> field, * except for the non-successfully resolved fields (errors). * Disabled by default. */ Optional<Boolean> excludeNullFieldsInResponses(); /** * Exceptions that should be unwrapped (
SmallRyeGraphQLRuntimeConfig
java
netty__netty
example/src/main/java/io/netty/example/stomp/websocket/StompSubscription.java
{ "start": 768, "end": 2068 }
class ____ { private final String id; private final String destination; private final Channel channel; public StompSubscription(String id, String destination, Channel channel) { this.id = ObjectUtil.checkNotNull(id, "id"); this.destination = ObjectUtil.checkNotNull(destination, "destination"); this.channel = ObjectUtil.checkNotNull(channel, "channel"); } public String id() { return id; } public String destination() { return destination; } public Channel channel() { return channel; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } StompSubscription that = (StompSubscription) obj; if (!id.equals(that.id)) { return false; } if (!destination.equals(that.destination)) { return false; } return channel.equals(that.channel); } @Override public int hashCode() { int result = id.hashCode(); result = 31 * result + destination.hashCode(); result = 31 * result + channel.hashCode(); return result; } }
StompSubscription
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/RedundantOverrideTest.java
{ "start": 6271, "end": 6678 }
class ____ extends A { @Nullable @Override Object swap(int a, int b) { return super.swap(a, b); } } """) .doTest(); } @Test public void protectedOverrideInDifferentPackage() { testHelper .addSourceLines( "A.java", """ package foo; public
B
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/scheduling/config/SchedulerBeanDefinitionParser.java
{ "start": 1084, "end": 1608 }
class ____ extends AbstractSingleBeanDefinitionParser { @Override protected String getBeanClassName(Element element) { return "org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler"; } @Override protected void doParse(Element element, BeanDefinitionBuilder builder) { String poolSize = element.getAttribute("pool-size"); if (StringUtils.hasText(poolSize)) { builder.addPropertyValue("poolSize", poolSize); } builder.setRole(BeanDefinition.ROLE_INFRASTRUCTURE); } }
SchedulerBeanDefinitionParser
java
quarkusio__quarkus
integration-tests/test-extension/tests/src/test/java/io/quarkus/it/extension/it/ParameterDevModeIT.java
{ "start": 634, "end": 2305 }
class ____ extends RunAndCheckMojoTestBase { @Override protected int getPort() { return 8098; } protected void runAndCheck(boolean performCompile, String... options) throws MavenInvocationException, FileNotFoundException { run(performCompile, options); String resp = devModeClient.getHttpResponse(); assertThat(resp).containsIgnoringCase("ready").containsIgnoringCase("application") .containsIgnoringCase("1.0-SNAPSHOT"); // There's no json endpoints, so nothing else to check } @Test public void testThatTheTestsPassed() throws MavenInvocationException, IOException { //we also check continuous testing String executionDir = "projects/project-using-test-parameter-injection-processed"; testDir = initProject("projects/project-using-test-parameter-injection", executionDir); runAndCheck(); ContinuousTestingMavenTestUtils testingTestUtils = new ContinuousTestingMavenTestUtils(getPort()); ContinuousTestingMavenTestUtils.TestStatus results = testingTestUtils.waitForNextCompletion(); // This is a bit brittle when we add tests, but failures are often so catastrophic they're not even reported as failures, // so we need to check the pass count explicitly Assertions.assertEquals(0, results.getTestsFailed()); Assertions.assertEquals(1, results.getTestsPassed()); // Also check stdout out for errors of the form // 2025-05-12 15:58:46,729 WARNING [org.jun.jup.eng.con.InstantiatingConfigurationParameterConverter] (Test runner thread) Failed to load default
ParameterDevModeIT
java
netty__netty
handler/src/test/java/io/netty/handler/ssl/MockAlternativeKeyProvider.java
{ "start": 10173, "end": 10402 }
class ____ extends MockSignature { public MockSha512WithEcdsaSignature() throws NoSuchAlgorithmException, NoSuchProviderException { super("SHA512withECDSA", "SunEC"); } } }
MockSha512WithEcdsaSignature
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/ShouldBeEqual_equals_hashCode_Test.java
{ "start": 1448, "end": 2900 }
class ____ { private static ShouldBeEqual factory; @BeforeAll public static void setUpOnce() { factory = shouldBeEqual("Yoda", "Luke", new StandardRepresentation()); } @Test void should_have_reflexive_equals() { assertEqualsIsReflexive(factory); } @Test void should_have_symmetric_equals() { assertEqualsIsSymmetric(factory, shouldBeEqual("Yoda", "Luke", new StandardRepresentation())); } @Test void should_have_transitive_equals() { assertEqualsIsTransitive(factory, shouldBeEqual("Yoda", "Luke", new StandardRepresentation()), shouldBeEqual("Yoda", "Luke", new StandardRepresentation())); } @Test void should_maintain_equals_and_hashCode_contract() { assertMaintainsEqualsAndHashCodeContract(factory, shouldBeEqual("Yoda", "Luke", new StandardRepresentation())); } @Test void should_not_be_equal_to_Object_of_different_type() { then(factory.equals("Yoda")).isFalse(); } @Test void should_not_be_equal_to_null() { then(factory.equals(null)).isFalse(); } @Test void should_not_be_equal_to_IsNotEqual_with_different_actual() { then(factory.equals(shouldBeEqual("Leia", "Luke", new StandardRepresentation()))).isFalse(); } @Test void should_not_be_equal_to_IsNotEqual_with_different_expected() { then(factory.equals(shouldBeEqual("Yoda", "Leia", new StandardRepresentation()))).isFalse(); } }
ShouldBeEqual_equals_hashCode_Test
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/description/JoinDescription_value_Test.java
{ "start": 1035, "end": 3455 }
class ____ { @Test void should_not_use_newline_when_empty() { // GIVEN JoinDescription joinDescription = allOf(); // with no descriptions // WHEN String actual = joinDescription.value(); // THEN assertThat(actual).isEqualTo("all of:[]"); } @Test void should_use_new_line_when_non_empty() { // GIVEN JoinDescription joinDescription = allOf(description("1"), description("2")); // WHEN String actual = joinDescription.value(); // THEN assertThat(actual).isEqualTo(format("all of:[%n" + " 1,%n" + " 2%n" + "]")); } @Test void should_indent_nested_join_descriptions() { // GIVEN JoinDescription joinDescription = allOf(description("1"), anyOf(allOf(description("2"), anyOf(description("3a"), description("3b"))), description("4"), description("5"))); // WHEN String actual = joinDescription.value(); // THEN assertThat(actual).isEqualTo(format("all of:[%n" + " 1,%n" + " any of:[%n" + " all of:[%n" + " 2,%n" + " any of:[%n" + " 3a,%n" + " 3b%n" + " ]%n" + " ],%n" + " 4,%n" + " 5%n" + " ]%n" + "]")); } private static Description description(String desc) { return new TestDescription(desc); } private static JoinDescription allOf(Description... descriptions) { return new JoinDescription("all of:[", "]", list(descriptions)); } private static JoinDescription anyOf(Description... descriptions) { return new JoinDescription("any of:[", "]", list(descriptions)); } }
JoinDescription_value_Test
java
google__jimfs
jimfs/src/test/java/com/google/common/jimfs/PathSubject.java
{ "start": 13479, "end": 13781 }
class ____ implements Subject.Factory<PathSubject, Path> { @Override public PathSubject createSubject(FailureMetadata failureMetadata, Path that) { return new PathSubject(failureMetadata, that); } } /** Interface for assertions about a file attribute. */ public
PathSubjectFactory
java
redisson__redisson
redisson/src/main/java/org/redisson/api/RBatch.java
{ "start": 16856, "end": 18715 }
interface ____ Redis Function feature using provided codec * * @param codec - codec for params and result * @return function interface */ RFunctionAsync getFunction(Codec codec); /** * Returns keys operations. * Each of Redis/Redisson object associated with own key * * @return Keys object */ RKeysAsync getKeys(); /** * Returns API for RediSearch module * * @return RSearchAsync object */ RSearchAsync getSearch(); /** * Returns API for RediSearch module using defined codec for attribute values. * * @param codec codec for entry * @return RSearchAsync object */ RSearchAsync getSearch(Codec codec); /** * Executes all operations accumulated during async methods invocations. * <p> * If cluster configuration used then operations are grouped by slot ids * and may be executed on different servers. Thus command execution order could be changed * * @return List with result object for each command * @throws RedisException in case of any error * */ BatchResult<?> execute() throws RedisException; /** * Executes all operations accumulated during async methods invocations asynchronously. * <p> * In cluster configurations operations grouped by slot ids * so may be executed on different servers. Thus command execution order could be changed * * @return List with result object for each command */ RFuture<BatchResult<?>> executeAsync(); /** * Discard batched commands and release allocated buffers used for parameters encoding. */ void discard(); /** * Discard batched commands and release allocated buffers used for parameters encoding. * * @return void */ RFuture<Void> discardAsync(); }
for
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/ValidatingDomProcessorTest.java
{ "start": 1164, "end": 1916 }
class ____ extends ValidatingProcessorTest { @Override @Test public void testNonWellFormedXml() throws Exception { MockEndpoint mock = getMockEndpoint("mock:invalid"); mock.expectedMessageCount(1); String xml = "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>" + "user xmlns=\"http://foo.com/bar\">" + " <id>1</id>" + " <username>davsclaus</username>"; try { template.sendBody("direct:start", xml); fail("Should have thrown a RuntimeCamelException"); } catch (CamelExecutionException e) { assertIsInstanceOf(SchemaValidationException.class, e.getCause()); } assertMockEndpointsSatisfied(); } }
ValidatingDomProcessorTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryQualifierTest.java
{ "start": 4194, "end": 4515 }
class ____ { @Inject @Qual int x; } """) .doTest(); } @Test public void exemptedClassAnnotation_noFinding() { helper .addSourceLines( "Test.java", """ import dagger.Component; @Component.Builder
Test
java
apache__camel
test-infra/camel-test-infra-keycloak/src/test/java/org/apache/camel/test/infra/keycloak/services/KeycloakServiceFactory.java
{ "start": 1363, "end": 1491 }
class ____ extends KeycloakLocalContainerInfraService implements KeycloakService { } }
KeycloakLocalContainerService