language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__flink
flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/strategy/TumblingTimeWindowStrategy.java
{ "start": 1044, "end": 1940 }
class ____ extends WindowStrategy { private final Duration windowSize; private final TimeType timeType; private final Duration allowedLateness; public TumblingTimeWindowStrategy(Duration windowSize) { this(windowSize, TimeType.EVENT); } public TumblingTimeWindowStrategy(Duration windowSize, TimeType timeType) { this(windowSize, timeType, Duration.ZERO); } public TumblingTimeWindowStrategy( Duration windowSize, TimeType timeType, Duration allowedLateness) { this.windowSize = windowSize; this.timeType = timeType; this.allowedLateness = allowedLateness; } public Duration getWindowSize() { return windowSize; } public TimeType getTimeType() { return timeType; } public Duration getAllowedLateness() { return allowedLateness; } }
TumblingTimeWindowStrategy
java
spring-projects__spring-security
test/src/test/java/org/springframework/security/test/aot/hint/WithSecurityContextTestRuntimeHintsTests.java
{ "start": 3969, "end": 4228 }
class ____ implements WithSecurityContextFactory<WithMockTestUser> { @Override public SecurityContext createSecurityContext(WithMockTestUser annotation) { return SecurityContextHolder.createEmptyContext(); } } }
WithMockTestUserSecurityContextFactory
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/TestAppManagerWithFairScheduler.java
{ "start": 3183, "end": 11611 }
class ____ extends AppManagerTestBase { private static final String TEST_FOLDER = "test-queues"; private static YarnConfiguration conf = new YarnConfiguration(); private PlacementManager placementMgr; private TestRMAppManager rmAppManager; private RMContext rmContext; private static String allocFileName = GenericTestUtils.getTestDir(TEST_FOLDER).getAbsolutePath(); @BeforeEach public void setup() throws IOException { // Basic config with one queue (override in test if needed) AllocationFileWriter.create() .addQueue(new AllocationFileQueue.Builder("test").build()) .writeToFile(allocFileName); conf.setClass(YarnConfiguration.RM_SCHEDULER, FairScheduler.class, ResourceScheduler.class); conf.set(FairSchedulerConfiguration.ALLOCATION_FILE, allocFileName); placementMgr = mock(PlacementManager.class); MockRM mockRM = new MockRM(conf); rmContext = mockRM.getRMContext(); rmContext.setQueuePlacementManager(placementMgr); ApplicationMasterService masterService = new ApplicationMasterService( rmContext, rmContext.getScheduler()); rmAppManager = new TestRMAppManager(rmContext, new ClientToAMTokenSecretManagerInRM(), rmContext.getScheduler(), masterService, new ApplicationACLsManager(conf), conf); } @AfterEach public void teardown(){ File allocFile = GenericTestUtils.getTestDir(TEST_FOLDER); allocFile.delete(); } @Test public void testQueueSubmitWithHighQueueContainerSize() throws YarnException, IOException { int maxAlloc = YarnConfiguration.DEFAULT_RM_SCHEDULER_MINIMUM_ALLOCATION_MB; // scheduler config with a limited queue AllocationFileWriter.create() .addQueue(new AllocationFileQueue.Builder("root") .subQueue(new AllocationFileQueue.Builder("limited") .maxContainerAllocation(maxAlloc + " mb 1 vcores") .build()) .subQueue(new AllocationFileQueue.Builder("unlimited") .build()) .build()) .writeToFile(allocFileName); rmContext.getScheduler().reinitialize(conf, rmContext); ApplicationId appId = MockApps.newAppID(1); Resource res = Resources.createResource(maxAlloc + 1); ApplicationSubmissionContext asContext = createAppSubmitCtx(appId, res); // Submit to limited queue when(placementMgr.placeApplication(any(), any(), any(Boolean.class))) .thenReturn(new ApplicationPlacementContext("limited")); try { rmAppManager.submitApplication(asContext, "test"); fail("Test should fail on too high allocation!"); } catch (InvalidResourceRequestException e) { assertEquals(GREATER_THEN_MAX_ALLOCATION, e.getInvalidResourceType()); } // submit same app but now place it in the unlimited queue when(placementMgr.placeApplication(any(), any(), any(Boolean.class))) .thenReturn(new ApplicationPlacementContext("root.unlimited")); rmAppManager.submitApplication(asContext, "test"); } @Test public void testQueueSubmitWithPermissionLimits() throws YarnException, IOException { conf.set(YarnConfiguration.YARN_ACL_ENABLE, "true"); AllocationFileWriter.create() .addQueue(new AllocationFileQueue.Builder("root") .aclSubmitApps(" ") .aclAdministerApps(" ") .subQueue(new AllocationFileQueue.Builder("noaccess") .build()) .subQueue(new AllocationFileQueue.Builder("submitonly") .aclSubmitApps("test ") .aclAdministerApps(" ") .build()) .subQueue(new AllocationFileQueue.Builder("adminonly") .aclSubmitApps(" ") .aclAdministerApps("test ") .build()) .build()) .writeToFile(allocFileName); rmContext.getScheduler().reinitialize(conf, rmContext); ApplicationId appId = MockApps.newAppID(1); Resource res = Resources.createResource(1024, 1); ApplicationSubmissionContext asContext = createAppSubmitCtx(appId, res); // Submit to no access queue when(placementMgr.placeApplication(any(), any(), any(Boolean.class))) .thenReturn(new ApplicationPlacementContext("noaccess")); try { rmAppManager.submitApplication(asContext, "test"); fail("Test should have failed with access denied"); } catch (YarnException e) { assertTrue(e.getCause() instanceof AccessControlException, "Access exception not found"); } // Submit to submit access queue when(placementMgr.placeApplication(any(), any(), any(Boolean.class))) .thenReturn(new ApplicationPlacementContext("submitonly")); rmAppManager.submitApplication(asContext, "test"); // Submit second app to admin access queue appId = MockApps.newAppID(2); asContext = createAppSubmitCtx(appId, res); when(placementMgr.placeApplication(any(), any(), any(Boolean.class))) .thenReturn(new ApplicationPlacementContext("adminonly")); rmAppManager.submitApplication(asContext, "test"); } @Test public void testQueueSubmitWithRootPermission() throws YarnException, IOException { conf.set(YarnConfiguration.YARN_ACL_ENABLE, "true"); AllocationFileWriter.create() .addQueue(new AllocationFileQueue.Builder("root") .subQueue(new AllocationFileQueue.Builder("noaccess") .aclSubmitApps(" ") .aclAdministerApps(" ") .build()) .build()) .writeToFile(allocFileName); rmContext.getScheduler().reinitialize(conf, rmContext); ApplicationId appId = MockApps.newAppID(1); Resource res = Resources.createResource(1024, 1); ApplicationSubmissionContext asContext = createAppSubmitCtx(appId, res); // Submit to noaccess queue should be allowed by root ACL when(placementMgr.placeApplication(any(), any())) .thenReturn(new ApplicationPlacementContext("noaccess")); rmAppManager.submitApplication(asContext, "test"); } @Test public void testQueueSubmitWithAutoCreateQueue() throws YarnException, IOException { conf.set(YarnConfiguration.YARN_ACL_ENABLE, "true"); AllocationFileWriter.create() .addQueue(new AllocationFileQueue.Builder("root") .aclSubmitApps(" ") .aclAdministerApps(" ") .subQueue(new AllocationFileQueue.Builder("noaccess") .parent(true) .build()) .subQueue(new AllocationFileQueue.Builder("submitonly") .parent(true) .aclSubmitApps("test ") .build()) .build()) .writeToFile(allocFileName); rmContext.getScheduler().reinitialize(conf, rmContext); ApplicationId appId = MockApps.newAppID(1); Resource res = Resources.createResource(1024, 1); ApplicationSubmissionContext asContext = createAppSubmitCtx(appId, res); // Submit to noaccess parent with non existent child queue when(placementMgr.placeApplication(any(), any(), any(Boolean.class))) .thenReturn(new ApplicationPlacementContext("root.noaccess.child")); try { rmAppManager.submitApplication(asContext, "test"); fail("Test should have failed with access denied"); } catch (YarnException e) { assertTrue(e.getCause() instanceof AccessControlException, "Access exception not found"); } // Submit to submitonly parent with non existent child queue when(placementMgr.placeApplication(any(), any(), any(Boolean.class))) .thenReturn(new ApplicationPlacementContext("root.submitonly.child")); rmAppManager.submitApplication(asContext, "test"); } private ApplicationSubmissionContext createAppSubmitCtx(ApplicationId appId, Resource res) { ApplicationSubmissionContext asContext = Records.newRecord(ApplicationSubmissionContext.class); asContext.setApplicationId(appId); ResourceRequest resReg = ResourceRequest.newInstance(Priority.newInstance(0), ResourceRequest.ANY, res, 1); asContext.setAMContainerResourceRequests( Collections.singletonList(resReg)); asContext.setAMContainerSpec(mock(ContainerLaunchContext.class)); asContext.setQueue("default"); return asContext; } }
TestAppManagerWithFairScheduler
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/subjects/ReplaySubjectBoundedConcurrencyTest.java
{ "start": 1210, "end": 10711 }
class ____ extends RxJavaTest { @Test public void replaySubjectConcurrentSubscribersDoingReplayDontBlockEachOther() throws InterruptedException { final ReplaySubject<Long> replay = ReplaySubject.createUnbounded(); Thread source = new Thread(new Runnable() { @Override public void run() { Observable.unsafeCreate(new ObservableSource<Long>() { @Override public void subscribe(Observer<? super Long> o) { o.onSubscribe(Disposable.empty()); System.out.println("********* Start Source Data ***********"); for (long l = 1; l <= 10000; l++) { o.onNext(l); } System.out.println("********* Finished Source Data ***********"); o.onComplete(); } }).subscribe(replay); } }); source.start(); long v = replay.blockingLast(); assertEquals(10000, v); // it's been played through once so now it will all be replays final CountDownLatch slowLatch = new CountDownLatch(1); Thread slowThread = new Thread(new Runnable() { @Override public void run() { Observer<Long> slow = new DefaultObserver<Long>() { @Override public void onComplete() { System.out.println("*** Slow Observer completed"); slowLatch.countDown(); } @Override public void onError(Throwable e) { } @Override public void onNext(Long args) { if (args == 1) { System.out.println("*** Slow Observer STARTED"); } try { if (args % 10 == 0) { Thread.sleep(1); } } catch (InterruptedException e) { e.printStackTrace(); } } }; replay.subscribe(slow); try { slowLatch.await(); } catch (InterruptedException e1) { e1.printStackTrace(); } } }); slowThread.start(); Thread fastThread = new Thread(new Runnable() { @Override public void run() { final CountDownLatch fastLatch = new CountDownLatch(1); Observer<Long> fast = new DefaultObserver<Long>() { @Override public void onComplete() { System.out.println("*** Fast Observer completed"); fastLatch.countDown(); } @Override public void onError(Throwable e) { } @Override public void onNext(Long args) { if (args == 1) { System.out.println("*** Fast Observer STARTED"); } } }; replay.subscribe(fast); try { fastLatch.await(); } catch (InterruptedException e1) { e1.printStackTrace(); } } }); fastThread.start(); fastThread.join(); // slow should not yet be completed when fast completes assertEquals(1, slowLatch.getCount()); slowThread.join(); } @Test public void replaySubjectConcurrentSubscriptions() throws InterruptedException { final ReplaySubject<Long> replay = ReplaySubject.createUnbounded(); Thread source = new Thread(new Runnable() { @Override public void run() { Observable.unsafeCreate(new ObservableSource<Long>() { @Override public void subscribe(Observer<? super Long> o) { o.onSubscribe(Disposable.empty()); System.out.println("********* Start Source Data ***********"); for (long l = 1; l <= 10000; l++) { o.onNext(l); } System.out.println("********* Finished Source Data ***********"); o.onComplete(); } }).subscribe(replay); } }); // used to collect results of each thread final List<List<Long>> listOfListsOfValues = Collections.synchronizedList(new ArrayList<>()); final List<Thread> threads = Collections.synchronizedList(new ArrayList<>()); for (int i = 1; i <= 200; i++) { final int count = i; if (count == 20) { // start source data after we have some already subscribed // and while others are in process of subscribing source.start(); } if (count == 100) { // wait for source to finish then keep adding after it's done source.join(); } Thread t = new Thread(new Runnable() { @Override public void run() { List<Long> values = replay.toList().blockingGet(); listOfListsOfValues.add(values); System.out.println("Finished thread: " + count); } }); t.start(); System.out.println("Started thread: " + i); threads.add(t); } // wait for all threads to complete for (Thread t : threads) { t.join(); } // assert all threads got the same results List<Long> sums = new ArrayList<>(); for (List<Long> values : listOfListsOfValues) { long v = 0; for (long l : values) { v += l; } sums.add(v); } long expected = sums.get(0); boolean success = true; for (long l : sums) { if (l != expected) { success = false; System.out.println("FAILURE => Expected " + expected + " but got: " + l); } } if (success) { System.out.println("Success! " + sums.size() + " each had the same sum of " + expected); } else { throw new RuntimeException("Concurrency Bug"); } } /** * Can receive timeout if subscribe never receives an onError/onComplete ... which reveals a race condition. */ @Test public void subscribeCompletionRaceCondition() { for (int i = 0; i < 50; i++) { final ReplaySubject<String> subject = ReplaySubject.createUnbounded(); final AtomicReference<String> value1 = new AtomicReference<>(); subject.subscribe(new Consumer<String>() { @Override public void accept(String t1) { try { // simulate a slow observer Thread.sleep(50); } catch (InterruptedException e) { e.printStackTrace(); } value1.set(t1); } }); Thread t1 = new Thread(new Runnable() { @Override public void run() { subject.onNext("value"); subject.onComplete(); } }); SubjectObserverThread t2 = new SubjectObserverThread(subject); SubjectObserverThread t3 = new SubjectObserverThread(subject); SubjectObserverThread t4 = new SubjectObserverThread(subject); SubjectObserverThread t5 = new SubjectObserverThread(subject); t2.start(); t3.start(); t1.start(); t4.start(); t5.start(); try { t1.join(); t2.join(); t3.join(); t4.join(); t5.join(); } catch (InterruptedException e) { throw new RuntimeException(e); } assertEquals("value", value1.get()); assertEquals("value", t2.value.get()); assertEquals("value", t3.value.get()); assertEquals("value", t4.value.get()); assertEquals("value", t5.value.get()); } } /** * Make sure emission-subscription races are handled correctly. * https://github.com/ReactiveX/RxJava/issues/1147 */ @Test public void raceForTerminalState() { final List<Integer> expected = Arrays.asList(1); for (int i = 0; i < 100000; i++) { TestObserverEx<Integer> to = new TestObserverEx<>(); Observable.just(1).subscribeOn(Schedulers.computation()).cache().subscribe(to); to.awaitDone(5, TimeUnit.SECONDS); to.assertValueSequence(expected); to.assertTerminated(); } } static
ReplaySubjectBoundedConcurrencyTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/assumptions/BDDAssumptionsTest.java
{ "start": 10224, "end": 10632 }
class ____ { private final float[] actual = { 1.0f, 2.0f }; @Test void should_run_test_when_assumption_passes() { thenCode(() -> given(actual).contains(1.0f)).doesNotThrowAnyException(); } @Test void should_ignore_test_when_assumption_fails() { expectAssumptionNotMetException(() -> given(actual).contains(0.0f)); } } @Nested
BDDAssumptions_given_float_array_Test
java
google__gson
gson/src/test/java/com/google/gson/functional/VersioningTest.java
{ "start": 3515, "end": 5842 }
class ____ versioned to be after 1.0, we expect null // This is the new behavior in Gson 2.0 assertThat(version1_2).isNull(); } @Test public void testVersionedGsonWithUnversionedClassesSerialization() { Gson gson = gsonWithVersion(1.0); BagOfPrimitives target = new BagOfPrimitives(10, 20, false, "stringValue"); assertThat(gson.toJson(target)).isEqualTo(target.getExpectedJson()); } @Test public void testVersionedGsonWithUnversionedClassesDeserialization() { Gson gson = gsonWithVersion(1.0); String json = "{\"longValue\":10,\"intValue\":20,\"booleanValue\":false}"; BagOfPrimitives expected = new BagOfPrimitives(); expected.longValue = 10; expected.intValue = 20; expected.booleanValue = false; BagOfPrimitives actual = gson.fromJson(json, BagOfPrimitives.class); assertThat(actual).isEqualTo(expected); } @Test public void testVersionedGsonMixingSinceAndUntilSerialization() { Gson gson = gsonWithVersion(1.0); SinceUntilMixing target = new SinceUntilMixing(); String json = gson.toJson(target); assertThat(json).doesNotContain("\"b\":" + B); gson = gsonWithVersion(1.2); json = gson.toJson(target); assertThat(json).contains("\"b\":" + B); gson = gsonWithVersion(1.3); json = gson.toJson(target); assertThat(json).doesNotContain("\"b\":" + B); gson = gsonWithVersion(1.4); json = gson.toJson(target); assertThat(json).doesNotContain("\"b\":" + B); } @Test public void testVersionedGsonMixingSinceAndUntilDeserialization() { String json = "{\"a\":5,\"b\":6}"; Gson gson = gsonWithVersion(1.0); SinceUntilMixing result = gson.fromJson(json, SinceUntilMixing.class); assertThat(result.a).isEqualTo(5); assertThat(result.b).isEqualTo(B); gson = gsonWithVersion(1.2); result = gson.fromJson(json, SinceUntilMixing.class); assertThat(result.a).isEqualTo(5); assertThat(result.b).isEqualTo(6); gson = gsonWithVersion(1.3); result = gson.fromJson(json, SinceUntilMixing.class); assertThat(result.a).isEqualTo(5); assertThat(result.b).isEqualTo(B); gson = gsonWithVersion(1.4); result = gson.fromJson(json, SinceUntilMixing.class); assertThat(result.a).isEqualTo(5); assertThat(result.b).isEqualTo(B); } private static
is
java
elastic__elasticsearch
x-pack/plugin/security/qa/jwt-realm/src/javaRestTest/java/org/elasticsearch/xpack/security/authc/jwt/JwtRestIT.java
{ "start": 3045, "end": 44032 }
class ____ extends ESRestTestCase { private static final String HMAC_JWKSET = """ {"keys":[ {"kty":"oct","kid":"test-hmac-384","k":"W3mR8v_MP0_YdDo1OB0uwOgPX6-7PzkICVxMDVCZlPGw3vyPr8SRb5akrRSNU-zV"}, {"kty":"oct","kid":"test-hmac-512","k":"U4kMAa7tBwKOD4ggab4ZRGeHlFTILgNbescS1b5nambKJPmrB7QjeTryvfrE8zjYSvLxW2-tzFJUpk38a6FjPA"} ]}""".replaceAll("\\s", ""); public static final String HMAC_PASSPHRASE = "test-HMAC/secret passphrase-value"; private static final String VALID_SHARED_SECRET = "test-secret"; private static final MutableSettingsProvider keystoreSettings = new MutableSettingsProvider() { { put("xpack.security.authc.realms.jwt.jwt2.client_authentication.shared_secret", VALID_SHARED_SECRET); } }; private static final String KEYSTORE_PASSWORD = "keystore-password"; @ClassRule public static ElasticsearchCluster cluster = ElasticsearchCluster.local() .nodes(2) .distribution(DistributionType.DEFAULT) .keystorePassword(KEYSTORE_PASSWORD) .configFile("http.key", Resource.fromClasspath("ssl/http.key")) .configFile("http.crt", Resource.fromClasspath("ssl/http.crt")) .configFile("ca.crt", Resource.fromClasspath("ssl/ca.crt")) .configFile("ca-transport.crt", Resource.fromClasspath("ssl/ca-transport.crt")) .configFile("transport.key", Resource.fromClasspath("ssl/transport.key")) .configFile("transport.crt", Resource.fromClasspath("ssl/transport.crt")) .configFile("rsa.jwkset", Resource.fromClasspath("jwk/rsa-public-jwkset.json")) .setting("xpack.ml.enabled", "false") .setting("xpack.license.self_generated.type", "trial") .setting("xpack.security.enabled", "true") .setting("xpack.security.transport.ssl.enabled", "true") .setting("xpack.security.transport.ssl.certificate", "transport.crt") .setting("xpack.security.transport.ssl.key", "transport.key") .setting("xpack.security.transport.ssl.certificate_authorities", "ca-transport.crt") .setting("xpack.security.authc.token.enabled", "true") .setting("xpack.security.authc.api_key.enabled", "true") .setting("xpack.security.http.ssl.enabled", "true") .setting("xpack.security.http.ssl.certificate", "http.crt") .setting("xpack.security.http.ssl.key", "http.key") .setting("xpack.security.http.ssl.certificate_authorities", "ca.crt") .setting("xpack.security.http.ssl.client_authentication", "optional") .settings(JwtRestIT::realmSettings) .keystore("xpack.security.authc.realms.jwt.jwt2.hmac_key", HMAC_PASSPHRASE) .keystore("xpack.security.authc.realms.jwt.jwt3.hmac_jwkset", HMAC_JWKSET) .keystore("xpack.security.http.ssl.secure_key_passphrase", "http-password") .keystore("xpack.security.transport.ssl.secure_key_passphrase", "transport-password") .keystore("xpack.security.authc.realms.jwt.jwt3.client_authentication.shared_secret", VALID_SHARED_SECRET) .keystore(keystoreSettings) .user("admin_user", "admin-password") .user("test_file_user", "test-password", "viewer", false) .build(); private static final SetOnce<String> SERVICE_SUBJECT = new SetOnce<>(); private static Path httpCertificateAuthority; private TestSecurityClient adminSecurityClient; private static Map<String, String> realmSettings(LocalClusterSpec.LocalNodeSpec localNodeSpec) { final boolean explicitIdTokenType = randomBoolean(); SERVICE_SUBJECT.trySet("service_" + randomIntBetween(1, 9) + "@app" + randomIntBetween(1, 9) + ".example.com"); final Map<String, String> settings = new HashMap<>(); settings.put("xpack.security.authc.realms.file.admin_file.order", "0"); settings.put("xpack.security.authc.realms.jwt.jwt1.order", "1"); if (explicitIdTokenType) { settings.put("xpack.security.authc.realms.jwt.jwt1.token_type", "id_token"); } settings.put("xpack.security.authc.realms.jwt.jwt1.allowed_issuer", "https://issuer.example.com/"); settings.put("xpack.security.authc.realms.jwt.jwt1.allowed_audiences", "https://audience.example.com/"); settings.put("xpack.security.authc.realms.jwt.jwt1.claims.principal", "sub"); settings.put("xpack.security.authc.realms.jwt.jwt1.claims.groups", "roles"); settings.put("xpack.security.authc.realms.jwt.jwt1.claims.dn", "dn"); settings.put("xpack.security.authc.realms.jwt.jwt1.claims.name", "name"); settings.put("xpack.security.authc.realms.jwt.jwt1.claims.mail", "mail"); settings.put("xpack.security.authc.realms.jwt.jwt1.required_claims.token_use", "id"); settings.put("xpack.security.authc.realms.jwt.jwt1.required_claims.version", "2.0"); settings.put("xpack.security.authc.realms.jwt.jwt1.client_authentication.type", "NONE"); // Use default value (RS256) for signature algorithm settings.put("xpack.security.authc.realms.jwt.jwt1.pkc_jwkset_path", "rsa.jwkset"); // Place native realm after JWT realm to verify realm chain fall-through settings.put("xpack.security.authc.realms.native.lookup_native.order", "2"); settings.put("xpack.security.authc.realms.jwt.jwt2.order", "3"); settings.put("xpack.security.authc.realms.jwt.jwt2.token_type", "access_token"); settings.put("xpack.security.authc.realms.jwt.jwt2.fallback_claims.sub", "email"); settings.put("xpack.security.authc.realms.jwt.jwt2.fallback_claims.aud", "scope"); settings.put("xpack.security.authc.realms.jwt.jwt2.allowed_issuer", "my-issuer"); if (randomBoolean()) { if (randomBoolean()) { settings.put("xpack.security.authc.realms.jwt.jwt2.allowed_subjects", SERVICE_SUBJECT.get()); } else { settings.put("xpack.security.authc.realms.jwt.jwt2.allowed_subject_patterns", SERVICE_SUBJECT.get()); } } else { settings.put("xpack.security.authc.realms.jwt.jwt2.allowed_subject_patterns", "service_*@app?.example.com"); } settings.put("xpack.security.authc.realms.jwt.jwt2.allowed_audiences", "es01,es02,es03"); settings.put("xpack.security.authc.realms.jwt.jwt2.allowed_signature_algorithms", "HS256,HS384"); // Both email or sub works because of fallback if (randomBoolean()) { settings.put("xpack.security.authc.realms.jwt.jwt2.claims.principal", "email"); } else { settings.put("xpack.security.authc.realms.jwt.jwt2.claims.principal", "sub"); } settings.put("xpack.security.authc.realms.jwt.jwt2.claim_patterns.principal", "^(.*)@[^.]*[.]example[.]com$"); settings.put("xpack.security.authc.realms.jwt.jwt2.required_claims.token_use", "access"); settings.put("xpack.security.authc.realms.jwt.jwt2.authorization_realms", "lookup_native"); settings.put("xpack.security.authc.realms.jwt.jwt2.client_authentication.type", "shared_secret"); settings.put("xpack.security.authc.realms.jwt.jwt2.client_authentication.rotation_grace_period", "0s"); // Place PKI realm after JWT realm to verify realm chain fall-through settings.put("xpack.security.authc.realms.pki.pki_realm.order", "4"); settings.put("xpack.security.authc.realms.jwt.jwt3.order", "5"); if (explicitIdTokenType) { settings.put("xpack.security.authc.realms.jwt.jwt3.token_type", "id_token"); } settings.put("xpack.security.authc.realms.jwt.jwt3.allowed_issuer", "jwt3-issuer"); settings.put("xpack.security.authc.realms.jwt.jwt3.allowed_audiences", "[jwt3-audience]"); settings.put("xpack.security.authc.realms.jwt.jwt3.allowed_signature_algorithms", "[HS384, HS512]"); settings.put("xpack.security.authc.realms.jwt.jwt3.claims.principal", "sub"); settings.put("xpack.security.authc.realms.jwt.jwt3.client_authentication.type", "Shared_Secret"); return settings; } @BeforeClass public static void findTrustStore() throws Exception { JwtRestIT.httpCertificateAuthority = findResource("/ssl/ca.crt"); } private static Path findResource(String name) throws FileNotFoundException, URISyntaxException { final URL resource = JwtRestIT.class.getResource(name); if (resource == null) { throw new FileNotFoundException("Cannot find classpath resource " + name); } final Path path = PathUtils.get(resource.toURI()); return path; } @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } @Override protected String getProtocol() { return "https"; } @Override protected Settings restAdminSettings() { String token = basicAuthHeaderValue("admin_user", new SecureString("admin-password".toCharArray())); return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", token).put(restSslSettings()).build(); } @Override protected Settings restClientSettings() { return Settings.builder().put(super.restClientSettings()).put(restSslSettings()).build(); } private Settings restSslSettings() { return Settings.builder().put(CERTIFICATE_AUTHORITIES, httpCertificateAuthority).build(); } protected TestSecurityClient getAdminSecurityClient() { if (adminSecurityClient == null) { adminSecurityClient = new TestSecurityClient(adminClient()); } return adminSecurityClient; } /** * Tests against realm "jwt1" in build.gradle * This realm * - use the "sub" claim as the principal * - performs role mapping * - supports RSA signed keys * - has no client authentication */ public void testAuthenticateWithRsaSignedJWTAndRoleMappingByPrincipal() throws Exception { final String principal = randomPrincipal(); final String dn = randomDn(); final String name = randomName(); final String mail = randomMail(); final String rules = Strings.format(""" { "all": [ { "field": { "realm.name": "jwt1" } }, { "field": { "username": "%s" } } ] } """, principal); authenticateToRealm1WithRoleMapping(principal, dn, name, mail, List.of(), rules); } public void testAuthenticateWithRsaSignedJWTAndRoleMappingByDn() throws Exception { final String principal = randomPrincipal(); final String dn = randomDn(); final String name = randomName(); final String mail = randomMail(); final String rules = Strings.format(""" { "all": [ { "field": { "realm.name": "jwt1" } }, { "field": { "dn": "%s" } } ] } """, dn); authenticateToRealm1WithRoleMapping(principal, dn, name, mail, List.of(), rules); } public void testAuthenticateWithRsaSignedJWTAndRoleMappingByGroups() throws Exception { final String principal = randomPrincipal(); final String dn = randomDn(); final String name = randomName(); final String mail = randomMail(); final List<String> groups = randomList(1, 12, () -> randomAlphaOfLengthBetween(4, 12)); final String mappedGroup = randomFrom(groups); final String rules = Strings.format(""" { "all": [ { "field": { "realm.name": "jwt1" } }, { "field": { "groups": "%s" } } ] } """, mappedGroup); authenticateToRealm1WithRoleMapping(principal, dn, name, mail, groups, rules); } public void testAuthenticateWithRsaSignedJWTAndRoleMappingByMetadata() throws Exception { final String principal = randomPrincipal(); final String dn = randomDn(); final String name = randomName(); final String mail = randomMail(); final String rules = Strings.format(""" { "all": [ { "field": { "realm.name": "jwt1" } }, { "field": { "metadata.jwt_claim_sub": "%s" } } ] } """, principal); authenticateToRealm1WithRoleMapping(principal, dn, name, mail, List.of(), rules); } private void authenticateToRealm1WithRoleMapping( String principal, String dn, String name, String mail, List<String> groups, String roleMappingRules ) throws Exception { final List<String> roles = randomRoles(); final String roleMappingName = createRoleMapping(roles, roleMappingRules); try { final SignedJWT jwt = buildAndSignJwtForRealm1(principal, dn, name, mail, groups, Instant.now()); final TestSecurityClient client = getSecurityClient(jwt, Optional.empty()); final Map<String, Object> response = client.authenticate(); final String description = "Authentication response [" + response + "]"; assertThat(description, response, hasEntry(User.Fields.USERNAME.getPreferredName(), principal)); assertThat( description, assertMap(response, User.Fields.AUTHENTICATION_REALM), hasEntry(User.Fields.REALM_NAME.getPreferredName(), "jwt1") ); assertThat(description, assertList(response, User.Fields.ROLES), Matchers.containsInAnyOrder(roles.toArray(String[]::new))); assertThat(description, assertMap(response, User.Fields.METADATA), hasEntry("jwt_token_type", "id_token")); // The user has no real role (we never define them) so everything they try to do will be FORBIDDEN final ResponseException exception = expectThrows( ResponseException.class, () -> client.getRoleDescriptors(new String[] { "*" }) ); assertThat(exception.getResponse(), hasStatusCode(RestStatus.FORBIDDEN)); } finally { deleteRoleMapping(roleMappingName); } } public void testFailureOnExpiredJwt() throws Exception { final String principal = randomPrincipal(); final String dn = randomDn(); final String name = randomName(); final String mail = randomMail(); { // Test with valid time final SignedJWT jwt = buildAndSignJwtForRealm1(principal, dn, name, mail, List.of(), Instant.now()); final TestSecurityClient client = getSecurityClient(jwt, Optional.empty()); assertThat(client.authenticate(), hasEntry(User.Fields.USERNAME.getPreferredName(), principal)); } { // Test with expired time final SignedJWT jwt = buildAndSignJwtForRealm1(principal, dn, name, mail, List.of(), Instant.now().minus(12, ChronoUnit.HOURS)); TestSecurityClient client = getSecurityClient(jwt, Optional.empty()); // This fails because the JWT is expired final ResponseException exception = expectThrows(ResponseException.class, client::authenticate); assertThat(exception.getResponse(), hasStatusCode(RestStatus.UNAUTHORIZED)); } } public void testFailureOnNonMatchingRsaSignature() throws Exception { final String originalPrincipal = randomPrincipal(); final String dn = randomDn(); final String name = randomName(); final String mail = randomMail(); final SignedJWT originalJwt = buildAndSignJwtForRealm1(originalPrincipal, dn, name, mail, List.of(), Instant.now()); { // Test with valid signed JWT final TestSecurityClient client = getSecurityClient(originalJwt, Optional.empty()); assertThat(client.authenticate(), hasEntry(User.Fields.USERNAME.getPreferredName(), originalPrincipal)); } { // Create a new JWT with the header + signature from the original JWT, but a falsified set of claim final JWTClaimsSet falsifiedClaims = new JWTClaimsSet.Builder(originalJwt.getJWTClaimsSet()).claim("roles", "superuser") .build(); final SignedJWT falsifiedJwt = new SignedJWT( originalJwt.getHeader().toBase64URL(), falsifiedClaims.toPayload().toBase64URL(), originalJwt.getSignature() ); final TestSecurityClient client = getSecurityClient(falsifiedJwt, Optional.empty()); // This fails because the JWT signature does not match the payload final ResponseException exception = expectThrows(ResponseException.class, client::authenticate); assertThat(exception.getResponse(), hasStatusCode(RestStatus.UNAUTHORIZED)); } } /** * Tests against realm "jwt2" in build.gradle * This realm * - use the "email" claim as the principal (with the domain removed) * - performs lookup on the native realm * - supports HMAC signed keys (using a OIDC style passphrase) * - uses a shared-secret for client authentication */ public void testAuthenticateWithHmacSignedJWTAndDelegatedAuthorization() throws Exception { final String principal = SERVICE_SUBJECT.get(); final String username = getUsernameFromPrincipal(principal); final List<String> roles = randomRoles(); final String randomMetadata = randomAlphaOfLengthBetween(6, 18); createUser(username, roles, Map.of("test_key", randomMetadata)); try { final SignedJWT jwt = buildAndSignJwtForRealm2(principal); final TestSecurityClient client = getSecurityClient(jwt, Optional.of(VALID_SHARED_SECRET)); final Map<String, Object> response = client.authenticate(); assertThat(response.get(User.Fields.USERNAME.getPreferredName()), is(username)); assertThat(assertMap(response, User.Fields.AUTHENTICATION_REALM), hasEntry(User.Fields.REALM_NAME.getPreferredName(), "jwt2")); assertThat(assertList(response, User.Fields.ROLES), Matchers.containsInAnyOrder(roles.toArray(String[]::new))); assertThat(assertMap(response, User.Fields.METADATA), hasEntry("test_key", randomMetadata)); // The user has no real role (we never define them) so everything they try to do will be FORBIDDEN final ResponseException exception = expectThrows( ResponseException.class, () -> client.getRoleDescriptors(new String[] { "*" }) ); assertThat(exception.getResponse(), hasStatusCode(RestStatus.FORBIDDEN)); } finally { deleteUser(username); } } public void testFailureOnInvalidHMACSignature() throws Exception { final String principal = SERVICE_SUBJECT.get(); final String username = getUsernameFromPrincipal(principal); final List<String> roles = randomRoles(); createUser(username, roles, Map.of()); try { final JWTClaimsSet claimsSet = buildJwtForRealm2(principal, Instant.now()); { // This is the correct HMAC passphrase (from build.gradle) final SignedJWT jwt = signHmacJwt(claimsSet, HMAC_PASSPHRASE, false); final TestSecurityClient client = getSecurityClient(jwt, Optional.of(VALID_SHARED_SECRET)); assertThat(client.authenticate(), hasEntry(User.Fields.USERNAME.getPreferredName(), username)); } { // This is not the correct HMAC passphrase final SignedJWT invalidJwt = signHmacJwt(claimsSet, "invalid-HMAC-passphrase-" + randomAlphaOfLength(12), false); final TestSecurityClient client = getSecurityClient(invalidJwt, Optional.of(VALID_SHARED_SECRET)); // This fails because the HMAC is wrong final ResponseException exception = expectThrows(ResponseException.class, client::authenticate); assertThat(exception.getResponse(), hasStatusCode(RestStatus.UNAUTHORIZED)); } } finally { deleteUser(username); } } public void testFailureOnRequiredClaims() throws JOSEException, IOException { final String principal = SERVICE_SUBJECT.get(); final String username = getUsernameFromPrincipal(principal); final List<String> roles = randomRoles(); createUser(username, roles, Map.of()); try { final String audience = "es0" + randomIntBetween(1, 3); final Map<String, Object> data = new HashMap<>(Map.of("iss", "my-issuer", "aud", audience, "email", principal)); // The required claim is either missing or mismatching if (randomBoolean()) { data.put("token_use", randomValueOtherThan("access", () -> randomAlphaOfLengthBetween(3, 10))); } final JWTClaimsSet claimsSet = buildJwt(data, Instant.now(), false, false); final SignedJWT jwt = signHmacJwt(claimsSet, "test-HMAC/secret passphrase-value", false); final TestSecurityClient client = getSecurityClient(jwt, Optional.of(VALID_SHARED_SECRET)); final ResponseException exception = expectThrows(ResponseException.class, client::authenticate); assertThat(exception.getResponse(), hasStatusCode(RestStatus.UNAUTHORIZED)); } finally { deleteUser(username); } } public void testAuthenticationFailureIfDelegatedAuthorizationFails() throws Exception { final String principal = SERVICE_SUBJECT.get(); final String username = getUsernameFromPrincipal(principal); final SignedJWT jwt = buildAndSignJwtForRealm2(principal); final TestSecurityClient client = getSecurityClient(jwt, Optional.of(VALID_SHARED_SECRET)); // This fails because we didn't create a native user final ResponseException exception = expectThrows(ResponseException.class, client::authenticate); assertThat(exception.getResponse(), hasStatusCode(RestStatus.UNAUTHORIZED)); createUser(username, List.of(), Map.of()); try { // Now it works assertThat(client.authenticate(), hasEntry(User.Fields.USERNAME.getPreferredName(), username)); } finally { deleteUser(username); } } public void testReloadClientSecret() throws Exception { final String principal = SERVICE_SUBJECT.get(); final String username = getUsernameFromPrincipal(principal); final List<String> roles = randomRoles(); createUser(username, roles, Map.of()); try { getSecurityClient(buildAndSignJwtForRealm2(principal), Optional.of(VALID_SHARED_SECRET)).authenticate(); // secret not updated yet, so authentication fails final String newValidSharedSecret = "new-valid-secret"; assertThat( expectThrows( ResponseException.class, () -> getSecurityClient(buildAndSignJwtForRealm2(principal), Optional.of(newValidSharedSecret)).authenticate() ).getResponse(), hasStatusCode(RestStatus.UNAUTHORIZED) ); writeSettingToKeystoreThenReload( "xpack.security.authc.realms.jwt.jwt2.client_authentication.shared_secret", newValidSharedSecret ); // secret updated, so authentication succeeds getSecurityClient(buildAndSignJwtForRealm2(principal), Optional.of(newValidSharedSecret)).authenticate(); // removing setting should not work since it can // lead to inconsistency in realm's configuration // and eventual authentication failures writeSettingToKeystoreThenReload("xpack.security.authc.realms.jwt.jwt2.client_authentication.shared_secret", null); getSecurityClient(buildAndSignJwtForRealm2(principal), Optional.of(newValidSharedSecret)).authenticate(); } finally { // Restore setting for other tests writeSettingToKeystoreThenReload( "xpack.security.authc.realms.jwt.jwt2.client_authentication.shared_secret", VALID_SHARED_SECRET ); deleteUser(username); } } private void writeSettingToKeystoreThenReload(String setting, @Nullable String value) throws IOException { if (value == null) { keystoreSettings.remove(setting); } else { keystoreSettings.put(setting, value); } cluster.updateStoredSecureSettings(); final var reloadRequest = new Request("POST", "/_nodes/reload_secure_settings"); reloadRequest.setJsonEntity("{\"secure_settings_password\":\"" + KEYSTORE_PASSWORD + "\"}"); assertOK(adminClient().performRequest(reloadRequest)); } public void testFailureOnInvalidClientAuthentication() throws Exception { final String principal = SERVICE_SUBJECT.get(); final String username = getUsernameFromPrincipal(principal); final List<String> roles = randomRoles(); createUser(username, roles, Map.of()); try { final SignedJWT jwt = buildAndSignJwtForRealm2(principal); final TestSecurityClient client = getSecurityClient(jwt, Optional.of("not-the-correct-secret")); // This fails because we didn't use the correct shared-secret final ResponseException exception = expectThrows(ResponseException.class, client::authenticate); assertThat(exception.getResponse(), hasStatusCode(RestStatus.UNAUTHORIZED)); } finally { deleteUser(username); } } /** * Tests against realm "jwt3" in build.gradle * This realm * - use the "sub" claim as the principal * - uses role mapping * - supports HMAC signed keys(using a JWKSet) * - uses a shared-secret for client authentication */ public void testAuthenticateWithHmacSignedJWTAndMissingRoleMapping() throws Exception { final String principal = randomPrincipal(); final SignedJWT jwt = buildAndSignJwtForRealm3(principal); final TestSecurityClient client = getSecurityClient(jwt, Optional.of(VALID_SHARED_SECRET)); final Map<String, Object> response = client.authenticate(); assertThat(response.get(User.Fields.USERNAME.getPreferredName()), is(principal)); assertThat(assertMap(response, User.Fields.AUTHENTICATION_REALM), hasEntry(User.Fields.REALM_NAME.getPreferredName(), "jwt3")); assertThat(assertList(response, User.Fields.ROLES), empty()); assertThat(assertMap(response, User.Fields.METADATA), hasEntry("jwt_claim_sub", principal)); assertThat(assertMap(response, User.Fields.METADATA), hasEntry("jwt_claim_aud", List.of("jwt3-audience"))); assertThat(assertMap(response, User.Fields.METADATA), hasEntry("jwt_claim_iss", "jwt3-issuer")); assertThat(assertMap(response, User.Fields.METADATA), hasEntry("jwt_token_type", "id_token")); } public void testAuthenticateToOtherRealmsInChain() throws IOException, URISyntaxException { // File realm, order 0 (before JWT realms) final Map<String, Object> fileUser = getSecurityClient( new UsernamePasswordToken("test_file_user", new SecureString("test-password".toCharArray())) ).authenticate(); assertThat(fileUser.get(User.Fields.USERNAME.getPreferredName()), is("test_file_user")); assertThat( assertMap(fileUser, User.Fields.AUTHENTICATION_REALM), hasEntry(User.Fields.REALM_NAME.getPreferredName(), "admin_file") ); assertThat(assertList(fileUser, User.Fields.ROLES), contains("viewer")); // Native realm, order 2 (between JWT1 and JWT2 realms) final String principal = randomPrincipal(); final SecureString password = new SecureString(randomAlphaOfLength(12).toCharArray()); final List<String> roles = randomRoles(); createUser(principal, password, roles, Map.of()); final Map<String, Object> nativeUser = getSecurityClient(new UsernamePasswordToken(principal, password)).authenticate(); assertThat(nativeUser.get(User.Fields.USERNAME.getPreferredName()), is(principal)); assertThat( assertMap(nativeUser, User.Fields.AUTHENTICATION_REALM), hasEntry(User.Fields.REALM_NAME.getPreferredName(), "lookup_native") ); assertThat(assertList(nativeUser, User.Fields.ROLES), containsInAnyOrder(roles.toArray(String[]::new))); // PKI realm, order 4 (between JWT2 and JWT3) final Path pkiCert = findResource("/ssl/pki.crt"); final Path pkiKey = findResource("/ssl/pki.key"); try ( RestClient pkiClient = buildClient( Settings.builder() .put(restClientSettings()) .put(CLIENT_CERT_PATH, pkiCert) .put(CLIENT_KEY_PATH, pkiKey) .put(CLIENT_KEY_PASSWORD, "pki-password") .build(), super.getClusterHosts().toArray(new HttpHost[0]) ) ) { final Map<String, Object> pkiUser = new TestSecurityClient(pkiClient).authenticate(); assertThat(pkiUser.get(User.Fields.USERNAME.getPreferredName()), is("pki")); assertThat( assertMap(pkiUser, User.Fields.AUTHENTICATION_REALM), hasEntry(User.Fields.REALM_NAME.getPreferredName(), "pki_realm") ); } } private String randomPrincipal() { // We append _test so that it cannot randomly conflict with builtin user return randomAlphaOfLengthBetween(4, 12) + "_test"; } private String randomDn() { return "CN=" + randomPrincipal(); } private String randomName() { return randomPrincipal() + "_name"; } private String randomMail() { return randomPrincipal() + "_mail@example.com"; } private List<String> randomRoles() { // We append _test so that it cannot randomly conflict with builtin roles return randomList(1, 3, () -> randomAlphaOfLengthBetween(4, 12) + "_test"); } private SignedJWT buildAndSignJwtForRealm1( String principal, String dn, String name, String mail, List<String> groups, Instant issueTime ) throws JOSEException, ParseException, IOException { final JWTClaimsSet claimsSet = buildJwt( Map.ofEntries( Map.entry("iss", "https://issuer.example.com/"), Map.entry("aud", "https://audience.example.com/"), Map.entry("sub", principal), Map.entry("dn", dn), Map.entry("name", name), Map.entry("mail", mail), Map.entry("roles", groups), // Realm realm config has `claim.groups: "roles"` Map.entry("token_use", "id"), Map.entry("version", "2.0") ), issueTime ); return signJwtForRealm1(claimsSet); } private SignedJWT buildAndSignJwtForRealm2(String principal) throws JOSEException, ParseException { return buildAndSignJwtForRealm2(principal, Instant.now()); } private SignedJWT buildAndSignJwtForRealm2(String principal, Instant issueTime) throws JOSEException, ParseException { final JWTClaimsSet claimsSet = buildJwtForRealm2(principal, issueTime); return signJwtForRealm2(claimsSet); } private JWTClaimsSet buildJwtForRealm2(String principal, Instant issueTime) { // The "jwt2" realm, supports 3 audiences (es01/02/03) final String audience = "es0" + randomIntBetween(1, 3); final Map<String, Object> data = new HashMap<>(Map.of("iss", "my-issuer", "email", principal, "token_use", "access")); if (randomBoolean()) { data.put("aud", audience); // scope (fallback audience) is ignored since aud exists data.put("scope", randomAlphaOfLength(20)); } else { data.put("scope", audience); } final JWTClaimsSet claimsSet = buildJwt(data, issueTime, false, false); return claimsSet; } private SignedJWT buildAndSignJwtForRealm3(String principal) throws Exception { return buildAndSignJwtForRealm3(principal, Instant.now()); } private SignedJWT buildAndSignJwtForRealm3(String principal, Instant issueTime) throws Exception { final JWTClaimsSet claimsSet = buildJwt( Map.ofEntries(Map.entry("iss", "jwt3-issuer"), Map.entry("aud", "jwt3-audience"), Map.entry("sub", principal)), issueTime ); return signJwtForRealm3(claimsSet); } private SignedJWT signJwtForRealm1(JWTClaimsSet claimsSet) throws IOException, JOSEException, ParseException { final RSASSASigner signer = loadRsaSigner(); return signJWT(signer, "RS256", claimsSet, false); } private SignedJWT signJwtForRealm2(JWTClaimsSet claimsSet) throws JOSEException { // Input string is configured in build.gradle return signHmacJwt(claimsSet, "test-HMAC/secret passphrase-value", true); } private SignedJWT signJwtForRealm3(JWTClaimsSet claimsSet) throws JOSEException, ParseException, IOException { final int bitSize = randomFrom(384, 512); final MACSigner signer = loadHmacSigner("test-hmac-" + bitSize); return signJWT(signer, "HS" + bitSize, claimsSet, false); } private RSASSASigner loadRsaSigner() throws IOException, ParseException, JOSEException { // The "jwt1" realm is configured using public JWKSet (in build.gradle) try (var in = getDataInputStream("/jwk/rsa-private-jwkset.json")) { final JWKSet jwkSet = JWKSet.load(in); final JWK key = jwkSet.getKeyByKeyId("test-rsa-key"); assertThat(key, instanceOf(RSAKey.class)); return new RSASSASigner((RSAKey) key); } } private MACSigner loadHmacSigner(String keyId) throws IOException, ParseException, JOSEException { // The "jwt3" realm is configured using secret JWKSet (in build.gradle) try (var in = getDataInputStream("/jwk/hmac-jwkset.json")) { final JWKSet jwkSet = JWKSet.load(in); final JWK key = jwkSet.getKeyByKeyId(keyId); assertThat("Key [" + keyId + "] from [" + jwkSet.getKeys() + "]", key, instanceOf(OctetSequenceKey.class)); return new MACSigner((OctetSequenceKey) key); } } private SignedJWT signHmacJwt(JWTClaimsSet claimsSet, String hmacPassphrase, boolean allowAtJwtType) throws JOSEException { final OctetSequenceKey hmac = JwkValidateUtil.buildHmacKeyFromString(hmacPassphrase); final JWSSigner signer = new MACSigner(hmac); return signJWT(signer, "HS256", claimsSet, allowAtJwtType); } // JWT construction static JWTClaimsSet buildJwt(Map<String, Object> claims, Instant issueTime) { return buildJwt(claims, issueTime, true, true); } static JWTClaimsSet buildJwt(Map<String, Object> claims, Instant issueTime, boolean includeSub, boolean includeAud) { final JWTClaimsSet.Builder builder = new JWTClaimsSet.Builder(); builder.issuer(randomAlphaOfLengthBetween(4, 24)); if (includeSub) { builder.subject(randomAlphaOfLengthBetween(4, 24)); } if (includeAud) { builder.audience(randomList(1, 6, () -> randomAlphaOfLengthBetween(4, 12))); } if (randomBoolean()) { builder.jwtID(UUIDs.randomBase64UUID(random())); } issueTime = issueTime.truncatedTo(ChronoUnit.SECONDS); builder.issueTime(Date.from(issueTime)); if (randomBoolean()) { builder.claim("auth_time", Date.from(issueTime.minusSeconds(randomLongBetween(0, 1800)))); } builder.expirationTime(Date.from(issueTime.plusSeconds(randomLongBetween(180, 1800)))); if (randomBoolean()) { builder.notBeforeTime(Date.from(issueTime.minusSeconds(randomLongBetween(10, 90)))); } // This may overwrite the aud/sub/iss set above. That is an intended behaviour for (String key : claims.keySet()) { builder.claim(key, claims.get(key)); } return builder.build(); } static SignedJWT signJWT(JWSSigner signer, String algorithm, JWTClaimsSet claimsSet, boolean allowAtJwtType) throws JOSEException { final JWSHeader.Builder builder = new JWSHeader.Builder(JWSAlgorithm.parse(algorithm)); if (randomBoolean()) { if (allowAtJwtType && randomBoolean()) { builder.type(new JOSEObjectType("at+jwt")); } else { builder.type(JOSEObjectType.JWT); } } final JWSHeader jwtHeader = builder.build(); final SignedJWT jwt = new SignedJWT(jwtHeader, claimsSet); jwt.sign(signer); return jwt; } private TestSecurityClient getSecurityClient(SignedJWT jwt, Optional<String> sharedSecret) { return getSecurityClient(options -> { final String bearerHeader = "Bearer " + jwt.serialize(); options.addHeader("Authorization", bearerHeader); sharedSecret.ifPresent(secret -> options.addHeader("ES-Client-Authentication", "SharedSecret " + secret)); }); } private TestSecurityClient getSecurityClient(UsernamePasswordToken basicAuth) { return getSecurityClient( options -> options.addHeader("Authorization", basicAuthHeaderValue(basicAuth.principal(), basicAuth.credentials())) ); } private TestSecurityClient getSecurityClient(Consumer<RequestOptions.Builder> configuration) { final RequestOptions.Builder options = RequestOptions.DEFAULT.toBuilder(); configuration.accept(options); return new TestSecurityClient(client(), options.build()); } // Utility methods static Map<?, ?> assertMap(Map<String, ?> response, ParseField field) { assertThat(response, hasKey(field.getPreferredName())); assertThat(response, hasEntry(is(field.getPreferredName()), instanceOf(Map.class))); return (Map<?, ?>) response.get(field.getPreferredName()); } static List<?> assertList(Map<String, ?> response, ParseField field) { assertThat(response, hasKey(field.getPreferredName())); assertThat(response, hasEntry(is(field.getPreferredName()), instanceOf(List.class))); return (List<?>) response.get(field.getPreferredName()); } private void createUser(String principal, List<String> roles, Map<String, Object> metadata) throws IOException { createUser(principal, new SecureString(randomAlphaOfLength(12).toCharArray()), roles, metadata); } private void createUser(String principal, SecureString password, List<String> roles, Map<String, Object> metadata) throws IOException { final String username; if (principal.contains("@")) { username = principal.substring(0, principal.indexOf("@")); } else { username = principal; } final String realName = randomAlphaOfLengthBetween(6, 18); final User user = new User(username, roles.toArray(String[]::new), realName, null, metadata, true); getAdminSecurityClient().putUser(user, password); } private void deleteUser(String principal) throws IOException { final String username; if (principal.contains("@")) { username = principal.substring(0, principal.indexOf("@")); } else { username = principal; } getAdminSecurityClient().deleteUser(username); } private String getUsernameFromPrincipal(String principal) { final String username; if (principal.contains("@")) { username = principal.substring(0, principal.indexOf("@")); } else { username = principal; } return username; } private String createRoleMapping(List<String> roles, String rules) throws IOException { Map<String, Object> mapping = new HashMap<>(); mapping.put("enabled", true); mapping.put("roles", roles); mapping.put("rules", XContentHelper.convertToMap(XContentType.JSON.xContent(), rules, true)); final String mappingName = "test-" + getTestName() + "-" + randomAlphaOfLength(8); getAdminSecurityClient().putRoleMapping(mappingName, mapping); return mappingName; } private void deleteRoleMapping(String name) throws IOException { getAdminSecurityClient().deleteRoleMapping(name); } }
JwtRestIT
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/samples/context/JavaConfigTests.java
{ "start": 6626, "end": 7292 }
class ____ implements WebMvcConfigurer { @Autowired private RootConfig rootConfig; @Bean public PersonController personController() { return new PersonController(this.rootConfig.personDao()); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/").setViewName("home"); } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } } }
WebConfig
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/bug/EmptyParseArrayTest.java
{ "start": 144, "end": 320 }
class ____ extends TestCase { public void test_0() throws Exception { Assert.assertNull(JSON.parseArray("", VO.class)); } public static
EmptyParseArrayTest
java
spring-projects__spring-boot
documentation/spring-boot-actuator-docs/src/test/java/org/springframework/boot/actuate/docs/info/InfoEndpointDocumentationTests.java
{ "start": 2625, "end": 10790 }
class ____ extends MockMvcEndpointDocumentationTests { @Test void info() { assertThat(this.mvc.get().uri("/actuator/info")).hasStatusOk() .apply(MockMvcRestDocumentation.document("info", gitInfo(), buildInfo(), osInfo(), processInfo(), javaInfo(), sslInfo())); } private ResponseFieldsSnippet gitInfo() { return responseFields(beneathPath("git"), fieldWithPath("branch").description("Name of the Git branch, if any."), fieldWithPath("commit").description("Details of the Git commit, if any."), fieldWithPath("commit.time").description("Timestamp of the commit, if any.").type(JsonFieldType.VARIES), fieldWithPath("commit.id").description("ID of the commit, if any.")); } private ResponseFieldsSnippet buildInfo() { return responseFields(beneathPath("build"), fieldWithPath("artifact").description("Artifact ID of the application, if any.").optional(), fieldWithPath("group").description("Group ID of the application, if any.").optional(), fieldWithPath("name").description("Name of the application, if any.") .type(JsonFieldType.STRING) .optional(), fieldWithPath("version").description("Version of the application, if any.").optional(), fieldWithPath("time").description("Timestamp of when the application was built, if any.") .type(JsonFieldType.VARIES) .optional()); } private ResponseFieldsSnippet osInfo() { return responseFields(beneathPath("os"), osInfoField("name", "Name of the operating system"), osInfoField("version", "Version of the operating system"), osInfoField("arch", "Architecture of the operating system")); } private FieldDescriptor osInfoField(String field, String desc) { return fieldWithPath(field).description(desc + " (as obtained from the 'os." + field + "' system property).") .type(JsonFieldType.STRING) .optional(); } private ResponseFieldsSnippet processInfo() { return responseFields(beneathPath("process"), fieldWithPath("pid").description("Process ID.").type(JsonFieldType.NUMBER), fieldWithPath("parentPid").description("Parent Process ID (or -1).").type(JsonFieldType.NUMBER), fieldWithPath("owner").description("Process owner.").type(JsonFieldType.STRING), fieldWithPath("cpus").description("Number of CPUs available to the process.") .type(JsonFieldType.NUMBER), fieldWithPath("memory").description("Memory information."), fieldWithPath("memory.heap").description("Heap memory."), fieldWithPath("memory.heap.init").description("Number of bytes initially requested by the JVM."), fieldWithPath("memory.heap.used").description("Number of bytes currently being used."), fieldWithPath("memory.heap.committed").description("Number of bytes committed for JVM use."), fieldWithPath("memory.heap.max") .description("Maximum number of bytes that can be used by the JVM (or -1)."), fieldWithPath("memory.nonHeap").description("Non-heap memory."), fieldWithPath("memory.nonHeap.init").description("Number of bytes initially requested by the JVM."), fieldWithPath("memory.nonHeap.used").description("Number of bytes currently being used."), fieldWithPath("memory.nonHeap.committed").description("Number of bytes committed for JVM use."), fieldWithPath("memory.nonHeap.max") .description("Maximum number of bytes that can be used by the JVM (or -1)."), fieldWithPath("memory.garbageCollectors").description("Details for garbage collectors."), fieldWithPath("memory.garbageCollectors[].name").description("Name of of the garbage collector."), fieldWithPath("memory.garbageCollectors[].collectionCount") .description("Total number of collections that have occurred."), fieldWithPath("virtualThreads") .description("Virtual thread information (if VirtualThreadSchedulerMXBean is available)") .type(JsonFieldType.OBJECT) .optional(), fieldWithPath("virtualThreads.mounted") .description("Estimate of the number of virtual threads currently mounted by the scheduler.") .type(JsonFieldType.NUMBER) .optional(), fieldWithPath("virtualThreads.queued").description( "Estimate of the number of virtual threads queued to the scheduler to start or continue execution.") .type(JsonFieldType.NUMBER) .optional(), fieldWithPath("virtualThreads.parallelism").description("Scheduler's target parallelism.") .type(JsonFieldType.NUMBER) .optional(), fieldWithPath("virtualThreads.poolSize") .description( "Current number of platform threads that the scheduler has started but have not terminated") .type(JsonFieldType.NUMBER) .optional()); } private ResponseFieldsSnippet javaInfo() { return responseFields(beneathPath("java"), fieldWithPath("version").description("Java version, if available.") .type(JsonFieldType.STRING) .optional(), fieldWithPath("vendor").description("Vendor details."), fieldWithPath("vendor.name").description("Vendor name, if available.") .type(JsonFieldType.STRING) .optional(), fieldWithPath("vendor.version").description("Vendor version, if available.") .type(JsonFieldType.STRING) .optional(), fieldWithPath("runtime").description("Runtime details."), fieldWithPath("runtime.name").description("Runtime name, if available.") .type(JsonFieldType.STRING) .optional(), fieldWithPath("runtime.version").description("Runtime version, if available.") .type(JsonFieldType.STRING) .optional(), fieldWithPath("jvm").description("JVM details."), fieldWithPath("jvm.name").description("JVM name, if available.").type(JsonFieldType.STRING).optional(), fieldWithPath("jvm.vendor").description("JVM vendor, if available.") .type(JsonFieldType.STRING) .optional(), fieldWithPath("jvm.version").description("JVM version, if available.") .type(JsonFieldType.STRING) .optional()); } private ResponseFieldsSnippet sslInfo() { return responseFields(beneathPath("ssl"), fieldWithPath("bundles").description("SSL bundles information.").type(JsonFieldType.ARRAY), fieldWithPath("bundles[].name").description("Name of the SSL bundle.").type(JsonFieldType.STRING), fieldWithPath("bundles[].certificateChains").description("Certificate chains in the bundle.") .type(JsonFieldType.ARRAY), fieldWithPath("bundles[].certificateChains[].alias").description("Alias of the certificate chain.") .type(JsonFieldType.STRING), fieldWithPath("bundles[].certificateChains[].certificates").description("Certificates in the chain.") .type(JsonFieldType.ARRAY), fieldWithPath("bundles[].certificateChains[].certificates[].subject") .description("Subject of the certificate.") .type(JsonFieldType.STRING), fieldWithPath("bundles[].certificateChains[].certificates[].version") .description("Version of the certificate.") .type(JsonFieldType.STRING), fieldWithPath("bundles[].certificateChains[].certificates[].issuer") .description("Issuer of the certificate.") .type(JsonFieldType.STRING), fieldWithPath("bundles[].certificateChains[].certificates[].validityStarts") .description("Certificate validity start date.") .type(JsonFieldType.STRING), fieldWithPath("bundles[].certificateChains[].certificates[].serialNumber") .description("Serial number of the certificate.") .type(JsonFieldType.STRING), fieldWithPath("bundles[].certificateChains[].certificates[].validityEnds") .description("Certificate validity end date.") .type(JsonFieldType.STRING), fieldWithPath("bundles[].certificateChains[].certificates[].validity") .description("Certificate validity information.") .type(JsonFieldType.OBJECT), fieldWithPath("bundles[].certificateChains[].certificates[].validity.status") .description("Certificate validity status.") .type(JsonFieldType.STRING), fieldWithPath("bundles[].certificateChains[].certificates[].signatureAlgorithmName") .description("Signature algorithm name.") .type(JsonFieldType.STRING)); } @Configuration(proxyBeanMethods = false) static
InfoEndpointDocumentationTests
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/utils/ExecNodeMetadataUtil.java
{ "start": 8362, "end": 17261 }
class ____ { private ExecNodeMetadataUtil() { // no instantiation } private static final Set<Class<? extends ExecNode<?>>> EXEC_NODES = new HashSet<>() { { add(StreamExecCalc.class); add(StreamExecChangelogNormalize.class); add(StreamExecCorrelate.class); add(StreamExecDeduplicate.class); add(StreamExecDropUpdateBefore.class); add(StreamExecExchange.class); add(StreamExecExpand.class); add(StreamExecGlobalGroupAggregate.class); add(StreamExecGlobalWindowAggregate.class); add(StreamExecGroupAggregate.class); add(StreamExecGroupWindowAggregate.class); add(StreamExecIncrementalGroupAggregate.class); add(StreamExecIntervalJoin.class); add(StreamExecJoin.class); add(StreamExecLimit.class); add(StreamExecLocalGroupAggregate.class); add(StreamExecLocalWindowAggregate.class); add(StreamExecLookupJoin.class); add(StreamExecMatch.class); add(StreamExecMiniBatchAssigner.class); add(StreamExecMultiJoin.class); add(StreamExecOverAggregate.class); add(StreamExecRank.class); add(StreamExecSink.class); add(StreamExecSortLimit.class); add(StreamExecSort.class); add(StreamExecTableSourceScan.class); add(StreamExecTemporalJoin.class); add(StreamExecTemporalSort.class); add(StreamExecUnion.class); add(StreamExecValues.class); add(StreamExecWatermarkAssigner.class); add(StreamExecWindowAggregate.class); add(StreamExecWindowDeduplicate.class); add(StreamExecWindowJoin.class); add(StreamExecWindowRank.class); add(StreamExecWindowTableFunction.class); add(StreamExecPythonCalc.class); add(StreamExecAsyncCalc.class); add(StreamExecProcessTableFunction.class); add(StreamExecAsyncCorrelate.class); add(StreamExecPythonCorrelate.class); add(StreamExecPythonGroupAggregate.class); add(StreamExecPythonGroupWindowAggregate.class); add(StreamExecPythonOverAggregate.class); add(StreamExecMLPredictTableFunction.class); add(StreamExecDeltaJoin.class); add(StreamExecVectorSearchTableFunction.class); // Batch execution mode add(BatchExecSink.class); add(BatchExecTableSourceScan.class); add(BatchExecCalc.class); add(BatchExecExchange.class); add(BatchExecSort.class); add(BatchExecValues.class); add(BatchExecCorrelate.class); add(BatchExecHashJoin.class); add(BatchExecNestedLoopJoin.class); add(BatchExecLimit.class); add(BatchExecUnion.class); add(BatchExecHashAggregate.class); add(BatchExecExpand.class); add(BatchExecSortAggregate.class); add(BatchExecSortLimit.class); add(BatchExecWindowTableFunction.class); add(BatchExecLookupJoin.class); add(BatchExecMatch.class); add(BatchExecOverAggregate.class); add(BatchExecRank.class); } }; private static final Map<ExecNodeNameVersion, Class<? extends ExecNode<?>>> LOOKUP_MAP = new HashMap<>(); static { for (Class<? extends ExecNode<?>> execNodeClass : EXEC_NODES) { addToLookupMap(execNodeClass); } } @SuppressWarnings("rawtypes") static final Set<Class<? extends ExecNode>> UNSUPPORTED_JSON_SERDE_CLASSES = new HashSet<Class<? extends ExecNode>>() { { add(StreamExecDataStreamScan.class); add(StreamExecLegacyTableSourceScan.class); add(StreamExecLegacySink.class); add(StreamExecGroupTableAggregate.class); add(StreamExecPythonGroupTableAggregate.class); add(StreamExecMultipleInput.class); } }; public static final Set<ConfigOption<?>> TABLE_CONFIG_OPTIONS; static { TABLE_CONFIG_OPTIONS = ConfigUtils.getAllConfigOptions(TableConfigOptions.class); } public static final Set<ConfigOption<?>> EXECUTION_CONFIG_OPTIONS; static { EXECUTION_CONFIG_OPTIONS = ConfigUtils.getAllConfigOptions(ExecutionConfigOptions.class); } public static Set<Class<? extends ExecNode<?>>> execNodes() { return EXEC_NODES; } public static Map<ExecNodeNameVersion, Class<? extends ExecNode<?>>> getVersionedExecNodes() { return LOOKUP_MAP; } public static Class<? extends ExecNode<?>> retrieveExecNode(String name, int version) { return LOOKUP_MAP.get(new ExecNodeNameVersion(name, version)); } public static <T extends ExecNode<?>> boolean isUnsupported(Class<T> execNode) { boolean streamOrKnownExecNode = StreamExecNode.class.isAssignableFrom(execNode) || execNodes().contains(execNode); return !streamOrKnownExecNode || UNSUPPORTED_JSON_SERDE_CLASSES.contains(execNode); } public static void addTestNode(Class<? extends ExecNode<?>> execNodeClass) { addToLookupMap(execNodeClass); } public static <T extends ExecNode<?>> List<ExecNodeMetadata> extractMetadataFromAnnotation( Class<T> execNodeClass) { List<ExecNodeMetadata> metadata = new ArrayList<>(); ExecNodeMetadata annotation = execNodeClass.getDeclaredAnnotation(ExecNodeMetadata.class); if (annotation != null) { metadata.add(annotation); } MultipleExecNodeMetadata annotations = execNodeClass.getDeclaredAnnotation(MultipleExecNodeMetadata.class); if (annotations != null) { if (metadata.isEmpty()) { for (ExecNodeMetadata annot : annotations.value()) { if (annot != null) { metadata.add(annot); } } } else { throw new IllegalStateException( String.format( "ExecNode: %s is annotated both with %s and %s. Please use only " + "%s or multiple %s", execNodeClass.getCanonicalName(), ExecNodeMetadata.class, MultipleExecNodeMetadata.class, MultipleExecNodeMetadata.class, ExecNodeMetadata.class)); } } return metadata; } private static void addToLookupMap(Class<? extends ExecNode<?>> execNodeClass) { if (!hasJsonCreatorAnnotation(execNodeClass)) { throw new IllegalStateException( String.format( "ExecNode: %s does not implement @JsonCreator annotation on " + "constructor.", execNodeClass.getCanonicalName())); } List<ExecNodeMetadata> metadata = extractMetadataFromAnnotation(execNodeClass); if (metadata.isEmpty()) { throw new IllegalStateException( String.format( "ExecNode: %s is missing %s annotation.", execNodeClass.getCanonicalName(), ExecNodeMetadata.class.getSimpleName())); } for (ExecNodeMetadata meta : metadata) { doAddToMap(new ExecNodeNameVersion(meta.name(), meta.version()), execNodeClass); } } private static void doAddToMap( ExecNodeNameVersion key, Class<? extends ExecNode<?>> execNodeClass) { if (LOOKUP_MAP.containsKey(key)) { throw new IllegalStateException(String.format("Found duplicate ExecNode: %s.", key)); } LOOKUP_MAP.put(key, execNodeClass); } /** * Returns the {@link ExecNodeMetadata} annotation of the
ExecNodeMetadataUtil
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/GuardedByCheckerTest.java
{ "start": 43951, "end": 44661 }
class ____ { public final Object mu1 = new Object(); public final Object mu2 = new Object(); @GuardedBy("mu1") int x = 1; { synchronized (mu2) { x++; } synchronized (mu1) { x++; } } } """) .doTest(); } @Test public void classInitializersAreUnchecked() { compilationHelper .addSourceLines( "threadsafety/Test.java", """ package threadsafety; import com.google.errorprone.annotations.concurrent.GuardedBy; public
Test
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhance/internal/bytebuddy/DirtyCheckingWithEmbeddableExtedingAnotherEmbeddableAndTwiceRemovedNonVisibleGenericMappedSuperclassTest.java
{ "start": 1910, "end": 2066 }
class ____<C extends MyAbstractEmbeddable> extends MyNonVisibleGenericMappedSuperclass<C> { } @Entity(name = "myentity") public static
MyMappedSuperclass
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/api/operators/sorted/state/NonCheckpointingStorageAccess.java
{ "start": 1458, "end": 3314 }
class ____ implements CheckpointStorageAccess { @Override public boolean supportsHighlyAvailableStorage() { return false; } @Override public boolean hasDefaultSavepointLocation() { return false; } @Override public CompletedCheckpointStorageLocation resolveCheckpoint(String externalPointer) { throw new UnsupportedOperationException( "Checkpoints are not supported in a single key state backend"); } @Override public void initializeBaseLocationsForCheckpoint() {} @Override public CheckpointStorageLocation initializeLocationForCheckpoint(long checkpointId) { throw new UnsupportedOperationException( "Checkpoints are not supported in a single key state backend"); } @Override public CheckpointStorageLocation initializeLocationForSavepoint( long checkpointId, @Nullable String externalLocationPointer) { throw new UnsupportedOperationException( "Checkpoints are not supported in a single key state backend"); } @Override public CheckpointStreamFactory resolveCheckpointStorageLocation( long checkpointId, CheckpointStorageLocationReference reference) { throw new UnsupportedOperationException( "Checkpoints are not supported in a single key state backend"); } @Override public CheckpointStateOutputStream createTaskOwnedStateStream() { throw new UnsupportedOperationException( "Checkpoints are not supported in a single key state backend"); } @Override public CheckpointStateToolset createTaskOwnedCheckpointStateToolset() { throw new UnsupportedOperationException( "Checkpoints are not supported in a single key state backend"); } }
NonCheckpointingStorageAccess
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/http/AbstractHttpServerTransportTests.java
{ "start": 4542, "end": 52376 }
class ____ extends ESTestCase { private NetworkService networkService; private ThreadPool threadPool; private Recycler<BytesRef> recycler; private static final int LONG_GRACE_PERIOD_MS = 20_000; private static final int SHORT_GRACE_PERIOD_MS = 1; @Before public void setup() throws Exception { networkService = new NetworkService(Collections.emptyList()); threadPool = new TestThreadPool("test"); recycler = new BytesRefRecycler(new MockPageCacheRecycler(Settings.EMPTY)); } @After public void shutdown() throws Exception { if (threadPool != null) { threadPool.shutdownNow(); } threadPool = null; networkService = null; recycler = null; } public void testHttpPublishPort() throws Exception { int boundPort = randomIntBetween(9000, 9100); int otherBoundPort = randomIntBetween(9200, 9300); int publishPort = resolvePublishPort( Settings.builder().put(HttpTransportSettings.SETTING_HTTP_PUBLISH_PORT.getKey(), 9080).build(), randomAddresses(), getByName("127.0.0.2") ); assertThat("Publish port should be explicitly set to 9080", publishPort, equalTo(9080)); publishPort = resolvePublishPort( Settings.EMPTY, asList(address("127.0.0.1", boundPort), address("127.0.0.2", otherBoundPort)), getByName("127.0.0.1") ); assertThat("Publish port should be derived from matched address", publishPort, equalTo(boundPort)); publishPort = resolvePublishPort( Settings.EMPTY, asList(address("127.0.0.1", boundPort), address("127.0.0.2", boundPort)), getByName("127.0.0.3") ); assertThat("Publish port should be derived from unique port of bound addresses", publishPort, equalTo(boundPort)); final BindHttpException e = expectThrows( BindHttpException.class, () -> resolvePublishPort( Settings.EMPTY, asList(address("127.0.0.1", boundPort), address("127.0.0.2", otherBoundPort)), getByName("127.0.0.3") ) ); assertThat(e.getMessage(), containsString("Failed to auto-resolve http publish port")); publishPort = resolvePublishPort( Settings.EMPTY, asList(address("0.0.0.0", boundPort), address("127.0.0.2", otherBoundPort)), getByName("127.0.0.1") ); assertThat("Publish port should be derived from matching wildcard address", publishPort, equalTo(boundPort)); if (NetworkUtils.SUPPORTS_V6) { publishPort = resolvePublishPort( Settings.EMPTY, asList(address("0.0.0.0", boundPort), address("127.0.0.2", otherBoundPort)), getByName("::1") ); assertThat("Publish port should be derived from matching wildcard address", publishPort, equalTo(boundPort)); } } public void testDispatchDoesNotModifyThreadContext() { final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() { @Override public void dispatchRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext) { threadContext.putHeader("foo", "bar"); threadContext.putTransient("bar", "baz"); } @Override public void dispatchBadRequest(final RestChannel channel, final ThreadContext threadContext, final Throwable cause) { threadContext.putHeader("foo_bad", "bar"); threadContext.putTransient("bar_bad", "baz"); } }; try ( AbstractHttpServerTransport transport = new AbstractHttpServerTransport( Settings.EMPTY, networkService, recycler, threadPool, xContentRegistry(), dispatcher, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), TelemetryProvider.NOOP ) { @Override protected HttpServerChannel bind(InetSocketAddress hostAddress) { return null; } @Override protected void startInternal() {} @Override protected void stopInternal() {} @Override public HttpStats stats() { return null; } } ) { transport.dispatchRequest(null, null, null); assertNull(threadPool.getThreadContext().getHeader("foo")); assertNull(threadPool.getThreadContext().getTransient("bar")); transport.dispatchRequest(null, null, new Exception()); assertNull(threadPool.getThreadContext().getHeader("foo_bad")); assertNull(threadPool.getThreadContext().getTransient("bar_bad")); } } public void testRequestHeadersPopulateThreadContext() { final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() { @Override public void dispatchRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext) { // specified request headers value are copied into the thread context assertEquals("true", threadContext.getHeader("header.1")); assertEquals("true", threadContext.getHeader("header.2")); // trace start time is also set assertThat(threadContext.getTransient(Task.TRACE_START_TIME), notNullValue()); // but unknown headers are not copied at all assertNull(threadContext.getHeader("header.3")); } @Override public void dispatchBadRequest(final RestChannel channel, final ThreadContext threadContext, final Throwable cause) { // no request headers are copied in to the context of malformed requests assertNull(threadContext.getHeader("header.1")); assertNull(threadContext.getHeader("header.2")); assertNull(threadContext.getHeader("header.3")); assertNull(threadContext.getTransient(Task.TRACE_START_TIME)); } }; // the set of headers to copy final Set<RestHeaderDefinition> headers = new HashSet<>( Arrays.asList(new RestHeaderDefinition("header.1", true), new RestHeaderDefinition("header.2", true)) ); // sample request headers to test with final Map<String, List<String>> restHeaders = new HashMap<>(); restHeaders.put("header.1", Collections.singletonList("true")); restHeaders.put("header.2", Collections.singletonList("true")); restHeaders.put("header.3", Collections.singletonList("true")); final RestRequest fakeRequest = new FakeRestRequest.Builder(xContentRegistry()).withHeaders(restHeaders).build(); final RestControllerTests.AssertingChannel channel = new RestControllerTests.AssertingChannel( fakeRequest, randomBoolean(), RestStatus.BAD_REQUEST ); try ( AbstractHttpServerTransport transport = new AbstractHttpServerTransport( Settings.EMPTY, networkService, recycler, threadPool, xContentRegistry(), dispatcher, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), TelemetryProvider.NOOP ) { @Override protected HttpServerChannel bind(InetSocketAddress hostAddress) { return null; } @Override protected void startInternal() {} @Override protected void stopInternal() {} @Override public HttpStats stats() { return null; } @Override protected void populatePerRequestThreadContext(RestRequest restRequest, ThreadContext threadContext) { getFakeActionModule(headers).copyRequestHeadersToThreadContext(restRequest.getHttpRequest(), threadContext); } } ) { transport.dispatchRequest(fakeRequest, channel, null); // headers are "null" here, aka not present, because the thread context changes containing them is to be confined to the request assertNull(threadPool.getThreadContext().getHeader("header.1")); assertNull(threadPool.getThreadContext().getHeader("header.2")); assertNull(threadPool.getThreadContext().getHeader("header.3")); transport.dispatchRequest(null, null, new Exception()); // headers are "null" here, aka not present, because the thread context changes containing them is to be confined to the request assertNull(threadPool.getThreadContext().getHeader("header.1")); assertNull(threadPool.getThreadContext().getHeader("header.2")); assertNull(threadPool.getThreadContext().getHeader("header.3")); } } /** * Check that the REST controller picks up and propagates W3C trace context headers via the {@link ThreadContext}. * @see <a href="https://www.w3.org/TR/trace-context/">Trace Context - W3C Recommendation</a> */ public void testTraceParentAndTraceId() { final String traceParentValue = "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"; final AtomicReference<Instant> traceStartTimeRef = new AtomicReference<>(); final HttpServerTransport.Dispatcher dispatcher = new HttpServerTransport.Dispatcher() { @Override public void dispatchRequest(final RestRequest request, final RestChannel channel, final ThreadContext threadContext) { assertThat(threadContext.getHeader(Task.TRACE_ID), equalTo("0af7651916cd43dd8448eb211c80319c")); assertThat(threadContext.getHeader(Task.TRACE_PARENT_HTTP_HEADER), nullValue()); assertThat(threadContext.getTransient(Task.PARENT_TRACE_PARENT_HEADER), equalTo(traceParentValue)); // request trace start time is also set assertTrue(traceStartTimeRef.compareAndSet(null, threadContext.getTransient(Task.TRACE_START_TIME))); assertNotNull(traceStartTimeRef.get()); } @Override public void dispatchBadRequest(final RestChannel channel, final ThreadContext threadContext, final Throwable cause) { // but they're not copied in for bad requests assertThat(threadContext.getHeader(Task.TRACE_ID), nullValue()); assertThat(threadContext.getHeader(Task.TRACE_PARENT_HTTP_HEADER), nullValue()); assertThat(threadContext.getTransient(Task.PARENT_TRACE_PARENT_HEADER), nullValue()); assertThat(threadContext.getTransient(Task.TRACE_START_TIME), nullValue()); } }; // sample request headers to test with Map<String, List<String>> restHeaders = new HashMap<>(); restHeaders.put(Task.TRACE_PARENT_HTTP_HEADER, Collections.singletonList(traceParentValue)); RestRequest fakeRequest = new FakeRestRequest.Builder(xContentRegistry()).withHeaders(restHeaders).build(); RestControllerTests.AssertingChannel channel = new RestControllerTests.AssertingChannel( fakeRequest, randomBoolean(), RestStatus.BAD_REQUEST ); try ( AbstractHttpServerTransport transport = new AbstractHttpServerTransport( Settings.EMPTY, networkService, recycler, threadPool, xContentRegistry(), dispatcher, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), TelemetryProvider.NOOP ) { @Override protected HttpServerChannel bind(InetSocketAddress hostAddress) { return null; } @Override protected void startInternal() {} @Override protected void stopInternal() {} @Override public HttpStats stats() { return null; } @Override protected void populatePerRequestThreadContext(RestRequest restRequest, ThreadContext threadContext) { getFakeActionModule(Set.of()).copyRequestHeadersToThreadContext(restRequest.getHttpRequest(), threadContext); } } ) { final var systemTimeBeforeRequest = System.currentTimeMillis(); transport.dispatchRequest(fakeRequest, channel, null); final var systemTimeAfterRequest = System.currentTimeMillis(); // headers are "null" here, aka not present, because the thread context changes containing them is to be confined to the request assertThat(threadPool.getThreadContext().getHeader(Task.TRACE_ID), nullValue()); assertThat(threadPool.getThreadContext().getHeader(Task.TRACE_PARENT_HTTP_HEADER), nullValue()); assertThat(threadPool.getThreadContext().getTransient(Task.PARENT_TRACE_PARENT_HEADER), nullValue()); // system clock is not _technically_ monotonic but in practice it's very unlikely to see a discontinuity here assertThat( traceStartTimeRef.get().toEpochMilli(), allOf(greaterThanOrEqualTo(systemTimeBeforeRequest), lessThanOrEqualTo(systemTimeAfterRequest)) ); transport.dispatchRequest(null, null, new Exception()); // headers are "null" here, aka not present, because the thread context changes containing them is to be confined to the request assertThat(threadPool.getThreadContext().getHeader(Task.TRACE_ID), nullValue()); assertThat(threadPool.getThreadContext().getHeader(Task.TRACE_PARENT_HTTP_HEADER), nullValue()); assertThat(threadPool.getThreadContext().getTransient(Task.PARENT_TRACE_PARENT_HEADER), nullValue()); } } public void testHandlingCompatibleVersionParsingErrors() { // a compatible version exception (v8 on accept and v9 on content-type) should be handled gracefully final ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); try ( AbstractHttpServerTransport transport = failureAssertingtHttpServerTransport(clusterSettings, Set.of("Accept", "Content-Type")) ) { Map<String, List<String>> headers = new HashMap<>(); headers.put("Accept", Collections.singletonList("aaa/bbb;compatible-with=8")); headers.put("Content-Type", Collections.singletonList("aaa/bbb;compatible-with=9")); FakeRestRequest.FakeHttpRequest fakeHttpRequest = new FakeRestRequest.FakeHttpRequest( RestRequest.Method.GET, "/", new BytesArray(randomByteArrayOfLength(between(1, 20))), headers ); transport.incomingRequest(fakeHttpRequest, new TestHttpChannel()); } } public void testIncorrectHeaderHandling() { final ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); try (AbstractHttpServerTransport transport = failureAssertingtHttpServerTransport(clusterSettings, Set.of("Accept"))) { Map<String, List<String>> headers = new HashMap<>(); headers.put("Accept", List.of("incorrectHeader")); if (randomBoolean()) { headers.put("Content-Type", List.of("alsoIncorrectHeader")); } FakeRestRequest.FakeHttpRequest fakeHttpRequest = new FakeRestRequest.FakeHttpRequest( RestRequest.Method.GET, "/", null, headers ); transport.incomingRequest(fakeHttpRequest, new TestHttpChannel()); } try (AbstractHttpServerTransport transport = failureAssertingtHttpServerTransport(clusterSettings, Set.of("Content-Type"))) { Map<String, List<String>> headers = new HashMap<>(); if (randomBoolean()) { headers.put("Accept", List.of("application/json")); } headers.put("Content-Type", List.of("incorrectHeader")); FakeRestRequest.FakeHttpRequest fakeHttpRequest = new FakeRestRequest.FakeHttpRequest( RestRequest.Method.GET, "/", null, headers ); transport.incomingRequest(fakeHttpRequest, new TestHttpChannel()); } } private AbstractHttpServerTransport failureAssertingtHttpServerTransport( ClusterSettings clusterSettings, final Set<String> failedHeaderNames ) { return new AbstractHttpServerTransport( Settings.EMPTY, networkService, recycler, threadPool, xContentRegistry(), new HttpServerTransport.Dispatcher() { @Override public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) { Assert.fail(); } @Override public void dispatchBadRequest(RestChannel channel, ThreadContext threadContext, Throwable cause) { assertThat(cause, instanceOf(RestRequest.MediaTypeHeaderException.class)); RestRequest.MediaTypeHeaderException mediaTypeHeaderException = (RestRequest.MediaTypeHeaderException) cause; assertThat(mediaTypeHeaderException.getFailedHeaderNames(), equalTo(failedHeaderNames)); assertThat(mediaTypeHeaderException.getMessage(), equalTo("Invalid media-type value on headers " + failedHeaderNames)); } }, clusterSettings, TelemetryProvider.NOOP ) { @Override protected HttpServerChannel bind(InetSocketAddress hostAddress) { return null; } @Override protected void startInternal() {} @Override protected void stopInternal() {} @Override public HttpStats stats() { return null; } }; } @TestLogging(value = "org.elasticsearch.http.HttpTracer:trace", reason = "to ensure we log REST requests on TRACE level") public void testTracerLog() throws Exception { final String includeSettings; final String excludeSettings; if (randomBoolean()) { includeSettings = randomBoolean() ? "*" : ""; } else { includeSettings = "/internal/test"; } excludeSettings = "/internal/testNotSeen"; final ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); try ( AbstractHttpServerTransport transport = new AbstractHttpServerTransport( Settings.EMPTY, networkService, recycler, threadPool, xContentRegistry(), new HttpServerTransport.Dispatcher() { @Override public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) { channel.sendResponse(emptyResponse(RestStatus.OK)); } @Override public void dispatchBadRequest(RestChannel channel, ThreadContext threadContext, Throwable cause) { channel.sendResponse(emptyResponse(RestStatus.BAD_REQUEST)); } }, clusterSettings, TelemetryProvider.NOOP ) { @Override protected HttpServerChannel bind(InetSocketAddress hostAddress) { return null; } @Override protected void startInternal() {} @Override protected void stopInternal() { } @Override public HttpStats stats() { return null; } } ) { clusterSettings.applySettings( Settings.builder() .put(HttpTransportSettings.SETTING_HTTP_TRACE_LOG_INCLUDE.getKey(), includeSettings) .put(HttpTransportSettings.SETTING_HTTP_TRACE_LOG_EXCLUDE.getKey(), excludeSettings) .build() ); try (var mockLog = MockLog.capture(HttpTracer.class)) { final String opaqueId = UUIDs.randomBase64UUID(random()); mockLog.addExpectation( new MockLog.PatternSeenEventExpectation( "received request", HttpTracerTests.HTTP_TRACER_LOGGER, Level.TRACE, "\\[\\d+\\]\\[" + opaqueId + "\\]\\[OPTIONS\\]\\[/internal/test\\] received request from \\[.*" ) ); final boolean badRequest = randomBoolean(); mockLog.addExpectation( new MockLog.PatternSeenEventExpectation( "sent response", HttpTracerTests.HTTP_TRACER_LOGGER, Level.TRACE, "\\[\\d+\\]\\[" + opaqueId + "\\]\\[" + (badRequest ? "BAD_REQUEST" : "OK") + "\\]\\[" + RestResponse.TEXT_CONTENT_TYPE + "\\]\\[0\\] sent response to \\[.*" ) ); mockLog.addExpectation( new MockLog.UnseenEventExpectation( "received other request", HttpTracerTests.HTTP_TRACER_LOGGER, Level.TRACE, "\\[\\d+\\]\\[" + opaqueId + "\\]\\[OPTIONS\\]\\[/internal/testNotSeen\\] received request from \\[.*" ) ); final Exception inboundException; if (badRequest) { inboundException = new RuntimeException(); } else { inboundException = null; } final FakeRestRequest fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withMethod( RestRequest.Method.OPTIONS ) .withPath("/internal/test") .withHeaders(Collections.singletonMap(Task.X_OPAQUE_ID_HTTP_HEADER, Collections.singletonList(opaqueId))) .withInboundException(inboundException) .build(); try (var httpChannel = fakeRestRequest.getHttpChannel()) { transport.serverAcceptedChannel(httpChannel); transport.incomingRequest(fakeRestRequest.getHttpRequest(), httpChannel); } final Exception inboundExceptionExcludedPath; if (randomBoolean()) { inboundExceptionExcludedPath = new RuntimeException(); } else { inboundExceptionExcludedPath = null; } final FakeRestRequest fakeRestRequestExcludedPath = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withMethod( RestRequest.Method.OPTIONS ) .withPath("/internal/testNotSeen") .withHeaders(Collections.singletonMap(Task.X_OPAQUE_ID_HTTP_HEADER, Collections.singletonList(opaqueId))) .withInboundException(inboundExceptionExcludedPath) .build(); try (var httpChannel = fakeRestRequestExcludedPath.getHttpChannel()) { transport.incomingRequest(fakeRestRequestExcludedPath.getHttpRequest(), httpChannel); } mockLog.assertAllExpectationsMatched(); } } } public void testLogsSlowInboundProcessing() throws Exception { final String opaqueId = UUIDs.randomBase64UUID(random()); final String path = "/internal/test"; final RestRequest.Method method = randomFrom(RestRequest.Method.values()); final ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); final Settings settings = Settings.builder() .put(TransportSettings.SLOW_OPERATION_THRESHOLD_SETTING.getKey(), TimeValue.timeValueMillis(5)) .build(); try ( var mockLog = MockLog.capture(AbstractHttpServerTransport.class); AbstractHttpServerTransport transport = new AbstractHttpServerTransport( settings, networkService, recycler, threadPool, xContentRegistry(), new HttpServerTransport.Dispatcher() { @Override public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) { try { TimeUnit.SECONDS.sleep(1L); } catch (InterruptedException e) { throw new AssertionError(e); } channel.sendResponse(emptyResponse(RestStatus.OK)); } @Override public void dispatchBadRequest(RestChannel channel, ThreadContext threadContext, Throwable cause) { channel.sendResponse(emptyResponse(RestStatus.BAD_REQUEST)); } }, clusterSettings, TelemetryProvider.NOOP ) { @Override protected HttpServerChannel bind(InetSocketAddress hostAddress) { return null; } @Override protected void startInternal() {} @Override protected void stopInternal() {} @Override public HttpStats stats() { return null; } } ) { mockLog.addExpectation( new MockLog.SeenEventExpectation( "expected message", AbstractHttpServerTransport.class.getCanonicalName(), Level.WARN, "handling request [" + opaqueId + "][" + method + "][" + path + "]" ) ); final FakeRestRequest fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withMethod(method) .withPath(path) .withHeaders(Collections.singletonMap(Task.X_OPAQUE_ID_HTTP_HEADER, Collections.singletonList(opaqueId))) .build(); transport.serverAcceptedChannel(fakeRestRequest.getHttpChannel()); transport.incomingRequest(fakeRestRequest.getHttpRequest(), fakeRestRequest.getHttpChannel()); mockLog.assertAllExpectationsMatched(); } } public void testHttpClientStats() { try ( AbstractHttpServerTransport transport = new AbstractHttpServerTransport( Settings.EMPTY, networkService, recycler, threadPool, xContentRegistry(), new HttpServerTransport.Dispatcher() { @Override public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) { channel.sendResponse(emptyResponse(RestStatus.OK)); } @Override public void dispatchBadRequest(RestChannel channel, ThreadContext threadContext, Throwable cause) { channel.sendResponse(emptyResponse(RestStatus.BAD_REQUEST)); } }, new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS), TelemetryProvider.NOOP ) { @Override protected HttpServerChannel bind(InetSocketAddress hostAddress) { return null; } @Override protected void startInternal() {} @Override protected void stopInternal() {} } ) { InetSocketAddress remoteAddress = new InetSocketAddress(randomIp(randomBoolean()), randomIntBetween(1, 65535)); String opaqueId = UUIDs.randomBase64UUID(random()); FakeRestRequest fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withRemoteAddress(remoteAddress) .withMethod(RestRequest.Method.GET) .withPath("/internal/stats_test") .withHeaders(Map.of(Task.X_OPAQUE_ID_HTTP_HEADER, Collections.singletonList(opaqueId))) .build(); transport.serverAcceptedChannel(fakeRestRequest.getHttpChannel()); transport.incomingRequest(fakeRestRequest.getHttpRequest(), fakeRestRequest.getHttpChannel()); HttpStats httpStats = transport.stats(); assertThat( httpStats.getClientStats(), contains( allOf( transformedMatch(HttpStats.ClientStats::remoteAddress, equalTo(NetworkAddress.format(remoteAddress))), transformedMatch(HttpStats.ClientStats::opaqueId, equalTo(opaqueId)), transformedMatch(HttpStats.ClientStats::lastUri, equalTo("/internal/stats_test")) ) ) ); remoteAddress = new InetSocketAddress(randomIp(randomBoolean()), randomIntBetween(1, 65535)); opaqueId = UUIDs.randomBase64UUID(random()); fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withRemoteAddress(remoteAddress) .withMethod(RestRequest.Method.GET) .withPath("/internal/stats_test2") .withHeaders(Map.of(Task.X_OPAQUE_ID_HTTP_HEADER.toUpperCase(Locale.ROOT), Collections.singletonList(opaqueId))) .build(); transport.serverAcceptedChannel(fakeRestRequest.getHttpChannel()); transport.incomingRequest(fakeRestRequest.getHttpRequest(), fakeRestRequest.getHttpChannel()); httpStats = transport.stats(); assertThat(httpStats.getClientStats().size(), equalTo(2)); // due to non-deterministic ordering in map iteration, the second client may not be the second entry in the list HttpStats.ClientStats secondClientStats = httpStats.getClientStats().get(0).opaqueId().equals(opaqueId) ? httpStats.getClientStats().get(0) : httpStats.getClientStats().get(1); assertThat(secondClientStats.remoteAddress(), equalTo(NetworkAddress.format(remoteAddress))); assertThat(secondClientStats.opaqueId(), equalTo(opaqueId)); assertThat(secondClientStats.lastUri(), equalTo("/internal/stats_test2")); } } public void testDisablingHttpClientStats() { final ClusterSettings clusterSettings = new ClusterSettings(Settings.EMPTY, ClusterSettings.BUILT_IN_CLUSTER_SETTINGS); try ( AbstractHttpServerTransport transport = new AbstractHttpServerTransport( Settings.EMPTY, networkService, recycler, threadPool, xContentRegistry(), new HttpServerTransport.Dispatcher() { @Override public void dispatchRequest(RestRequest request, RestChannel channel, ThreadContext threadContext) { channel.sendResponse(emptyResponse(RestStatus.OK)); } @Override public void dispatchBadRequest(RestChannel channel, ThreadContext threadContext, Throwable cause) { channel.sendResponse(emptyResponse(RestStatus.BAD_REQUEST)); } }, clusterSettings, TelemetryProvider.NOOP ) { @Override protected HttpServerChannel bind(InetSocketAddress hostAddress) { return null; } @Override protected void startInternal() {} @Override protected void stopInternal() {} } ) { InetSocketAddress remoteAddress = new InetSocketAddress(randomIp(randomBoolean()), randomIntBetween(1, 65535)); String opaqueId = UUIDs.randomBase64UUID(random()); FakeRestRequest fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withRemoteAddress(remoteAddress) .withMethod(RestRequest.Method.GET) .withPath("/internal/stats_test") .withHeaders(Map.of(Task.X_OPAQUE_ID_HTTP_HEADER, Collections.singletonList(opaqueId))) .build(); transport.serverAcceptedChannel(fakeRestRequest.getHttpChannel()); transport.incomingRequest(fakeRestRequest.getHttpRequest(), fakeRestRequest.getHttpChannel()); // HTTP client stats should default to enabled HttpStats httpStats = transport.stats(); assertThat(httpStats.getClientStats().size(), equalTo(1)); assertThat(httpStats.getClientStats().get(0).opaqueId(), equalTo(opaqueId)); clusterSettings.applySettings( Settings.builder().put(HttpTransportSettings.SETTING_HTTP_CLIENT_STATS_ENABLED.getKey(), false).build() ); // After disabling, HTTP client stats should be cleared immediately httpStats = transport.stats(); assertThat(httpStats.getClientStats().size(), equalTo(0)); // After disabling, HTTP client stats should not track new clients remoteAddress = new InetSocketAddress(randomIp(randomBoolean()), randomIntBetween(1, 65535)); opaqueId = UUIDs.randomBase64UUID(random()); fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withRemoteAddress(remoteAddress) .withMethod(RestRequest.Method.GET) .withPath("/internal/stats_test") .withHeaders(Map.of(Task.X_OPAQUE_ID_HTTP_HEADER, Collections.singletonList(opaqueId))) .build(); transport.serverAcceptedChannel(fakeRestRequest.getHttpChannel()); transport.incomingRequest(fakeRestRequest.getHttpRequest(), fakeRestRequest.getHttpChannel()); httpStats = transport.stats(); assertThat(httpStats.getClientStats().size(), equalTo(0)); clusterSettings.applySettings( Settings.builder().put(HttpTransportSettings.SETTING_HTTP_CLIENT_STATS_ENABLED.getKey(), true).build() ); // After re-enabling, HTTP client stats should now track new clients remoteAddress = new InetSocketAddress(randomIp(randomBoolean()), randomIntBetween(1, 65535)); opaqueId = UUIDs.randomBase64UUID(random()); fakeRestRequest = new FakeRestRequest.Builder(NamedXContentRegistry.EMPTY).withRemoteAddress(remoteAddress) .withMethod(RestRequest.Method.GET) .withPath("/internal/stats_test") .withHeaders(Map.of(Task.X_OPAQUE_ID_HTTP_HEADER, Collections.singletonList(opaqueId))) .build(); transport.serverAcceptedChannel(fakeRestRequest.getHttpChannel()); transport.incomingRequest(fakeRestRequest.getHttpRequest(), fakeRestRequest.getHttpChannel()); httpStats = transport.stats(); assertThat(httpStats.getClientStats().size(), equalTo(1)); } } public void testStopWaitsIndefinitelyIfGraceIsZero() { try (var wait = LogExpectation.expectWait(); var transport = new TestHttpServerTransport(Settings.EMPTY)) { TestHttpChannel httpChannel = new TestHttpChannel(); transport.serverAcceptedChannel(httpChannel); transport.incomingRequest(testHttpRequest(), httpChannel); transport.doStop(); assertFalse(transport.testHttpServerChannel.isOpen()); assertFalse(httpChannel.isOpen()); wait.assertExpectationsMatched(); } } public void testStopLogsProgress() throws Exception { TestHttpChannel httpChannel = new TestHttpChannel(); var doneWithRequest = new CountDownLatch(1); try (var wait = LogExpectation.expectUpdate(1); var transport = new TestHttpServerTransport(gracePeriod(SHORT_GRACE_PERIOD_MS))) { httpChannel.blockSendResponse(); var inResponse = httpChannel.notifyInSendResponse(); transport.serverAcceptedChannel(httpChannel); new Thread(() -> { transport.incomingRequest(testHttpRequest(), httpChannel); doneWithRequest.countDown(); }, "testStopLogsProgress -> incomingRequest").start(); inResponse.await(); transport.doStop(); assertFalse(transport.testHttpServerChannel.isOpen()); assertFalse(httpChannel.isOpen()); wait.assertExpectationsMatched(); } finally { httpChannel.allowSendResponse(); doneWithRequest.await(); } } public void testStopWorksWithNoOpenRequests() { var grace = SHORT_GRACE_PERIOD_MS; try (var noWait = LogExpectation.unexpectedTimeout(grace); var transport = new TestHttpServerTransport(gracePeriod(grace))) { final TestHttpRequest httpRequest = new TestHttpRequest( HttpRequest.HttpVersion.HTTP_1_1, RestRequest.Method.GET, "/", Map.of(CONNECTION, List.of(CLOSE)) ); TestHttpChannel httpChannel = new TestHttpChannel(); transport.serverAcceptedChannel(httpChannel); transport.incomingRequest(httpRequest, httpChannel); assertFalse(httpChannel.isOpen()); // TestHttpChannel will throw if closed twice, so this ensures close is not called. transport.doStop(); assertFalse(transport.testHttpServerChannel.isOpen()); noWait.assertExpectationsMatched(); } } public void testStopClosesIdleConnectionImmediately() { var grace = SHORT_GRACE_PERIOD_MS; try ( var noTimeout = LogExpectation.unexpectedTimeout(grace); TestHttpServerTransport transport = new TestHttpServerTransport(gracePeriod(grace)) ) { TestHttpChannel httpChannel = new TestHttpChannel(); transport.serverAcceptedChannel(httpChannel); transport.incomingRequest(testHttpRequest(), httpChannel); // channel now idle assertTrue(httpChannel.isOpen()); transport.doStop(); assertFalse(httpChannel.isOpen()); assertFalse(transport.testHttpServerChannel.isOpen()); // ensure we timed out waiting for connections to close naturally noTimeout.assertExpectationsMatched(); } } public void testStopForceClosesConnectionDuringRequest() throws Exception { var grace = SHORT_GRACE_PERIOD_MS; TestHttpChannel httpChannel = new TestHttpChannel(); var doneWithRequest = new CountDownLatch(1); try ( var timeout = LogExpectation.expectTimeout(grace); TestHttpServerTransport transport = new TestHttpServerTransport(gracePeriod(grace)) ) { httpChannel.blockSendResponse(); var inResponse = httpChannel.notifyInSendResponse(); transport.serverAcceptedChannel(httpChannel); new Thread(() -> { transport.incomingRequest(testHttpRequest(), httpChannel); doneWithRequest.countDown(); }, "testStopForceClosesConnectionDuringRequest -> incomingRequest").start(); inResponse.await(); assertTrue(httpChannel.isOpen()); transport.doStop(); assertFalse(httpChannel.isOpen()); assertFalse(transport.testHttpServerChannel.isOpen()); assertTrue(httpChannel.noResponses()); // ensure we timed out waiting for connections to close naturally timeout.assertExpectationsMatched(); } finally { // unblock request thread httpChannel.allowSendResponse(); doneWithRequest.countDown(); } } public void testStopClosesChannelAfterRequest() throws Exception { var grace = LONG_GRACE_PERIOD_MS; try (var noTimeout = LogExpectation.unexpectedTimeout(grace); var transport = new TestHttpServerTransport(gracePeriod(grace))) { TestHttpChannel httpChannel = new TestHttpChannel(); transport.serverAcceptedChannel(httpChannel); transport.incomingRequest(testHttpRequest(), httpChannel); TestHttpChannel idleChannel = new TestHttpChannel(); transport.serverAcceptedChannel(idleChannel); transport.incomingRequest(testHttpRequest(), idleChannel); CountDownLatch stopped = new CountDownLatch(1); var inSendResponse = httpChannel.notifyInSendResponse(); httpChannel.blockSendResponse(); // one last request, should cause httpChannel to close after the request once we start shutting down. new Thread(() -> transport.incomingRequest(testHttpRequest(), httpChannel), "testStopClosesChannelAfterRequest last request") .start(); inSendResponse.await(); new Thread(() -> { transport.doStop(); stopped.countDown(); }, "testStopClosesChannelAfterRequest stopping transport").start(); // wait until we are shutting down assertBusy(() -> assertFalse(transport.isAcceptingConnections())); httpChannel.allowSendResponse(); // wait for channel to close assertBusy(() -> assertFalse(httpChannel.isOpen())); try { assertTrue(stopped.await(10, TimeUnit.SECONDS)); } catch (InterruptedException e) { fail("server never stopped"); } assertFalse(transport.testHttpServerChannel.isOpen()); assertFalse(idleChannel.isOpen()); assertThat(httpChannel.responses, hasSize(2)); // should have closed naturally without having to wait noTimeout.assertExpectationsMatched(); } } public void testForceClosesOpenChannels() throws Exception { var grace = 100; // this test waits for the entire grace, so try to keep it short TestHttpChannel httpChannel = new TestHttpChannel(); var doneWithRequest = new CountDownLatch(1); try (var timeout = LogExpectation.expectTimeout(grace); var transport = new TestHttpServerTransport(gracePeriod(grace))) { transport.serverAcceptedChannel(httpChannel); transport.incomingRequest(testHttpRequest(), httpChannel); CountDownLatch stopped = new CountDownLatch(1); var inResponse = httpChannel.notifyInSendResponse(); httpChannel.blockSendResponse(); new Thread(() -> { transport.incomingRequest(testHttpRequest(), httpChannel); doneWithRequest.countDown(); }).start(); inResponse.await(); new Thread(() -> { transport.doStop(); stopped.countDown(); }).start(); try { assertTrue(stopped.await(2 * LONG_GRACE_PERIOD_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { fail("server never stopped"); } assertFalse(transport.testHttpServerChannel.isOpen()); assertFalse(httpChannel.isOpen()); HttpResponse first = httpChannel.getResponse(); assertTrue(httpChannel.noResponses()); // never sent the second response assertThat(first, instanceOf(TestHttpResponse.class)); timeout.assertExpectationsMatched(); } finally { // cleanup thread httpChannel.allowSendResponse(); doneWithRequest.await(); } } private static RestResponse emptyResponse(RestStatus status) { return new RestResponse(status, RestResponse.TEXT_CONTENT_TYPE, BytesArray.EMPTY); } private TransportAddress address(String host, int port) throws UnknownHostException { return new TransportAddress(getByName(host), port); } private TransportAddress randomAddress() throws UnknownHostException { return address("127.0.0." + randomIntBetween(1, 100), randomIntBetween(9200, 9300)); } private List<TransportAddress> randomAddresses() throws UnknownHostException { List<TransportAddress> addresses = new ArrayList<>(); for (int i = 0; i < randomIntBetween(1, 5); i++) { addresses.add(randomAddress()); } return addresses; } private ActionModule getFakeActionModule(Set<RestHeaderDefinition> headersToCopy) { SettingsModule settings = new SettingsModule(Settings.EMPTY); ActionPlugin copyHeadersPlugin = new ActionPlugin() { @Override public Collection<RestHeaderDefinition> getRestHeaders() { return headersToCopy; } }; return new ActionModule( settings.getSettings(), TestIndexNameExpressionResolver.newInstance(threadPool.getThreadContext()), null, settings.getIndexScopedSettings(), settings.getClusterSettings(), settings.getSettingsFilter(), threadPool, List.of(copyHeadersPlugin), null, null, new UsageService(), null, TelemetryProvider.NOOP, mock(ClusterService.class), null, List.of(), List.of(), RestExtension.allowAll(), new IncrementalBulkService(null, null, MeterRegistry.NOOP), TestProjectResolvers.alwaysThrow() ); } private
AbstractHttpServerTransportTests
java
dropwizard__dropwizard
dropwizard-client/src/test/java/io/dropwizard/client/JerseyIgnoreRequestUserAgentHeaderFilterTest.java
{ "start": 808, "end": 3268 }
class ____ { public static final DropwizardAppExtension<Configuration> APP_RULE = new DropwizardAppExtension<>(TestApplication.class, JerseyIgnoreRequestUserAgentHeaderFilterTest.class.getResource("/yaml/jerseyIgnoreRequestUserAgentHeaderFilterTest.yml").getPath()); private final URI testUri = URI.create("http://localhost:" + APP_RULE.getLocalPort()); private JerseyClientBuilder clientBuilder; private JerseyClientConfiguration clientConfiguration; @BeforeEach void setup() { clientConfiguration = new JerseyClientConfiguration(); clientConfiguration.setConnectionTimeout(Duration.milliseconds(1000L)); clientConfiguration.setTimeout(Duration.milliseconds(2500L)); clientBuilder = new JerseyClientBuilder(new MetricRegistry()) .using(clientConfiguration) .using(Executors.newSingleThreadExecutor(), Jackson.newObjectMapper()); } @Test void clientIsSetRequestIsNotSet() { clientConfiguration.setUserAgent(Optional.of("ClientUserAgentHeaderValue")); assertThat( clientBuilder.using(clientConfiguration). build("ClientName").target(testUri + "/user_agent") .request() .get(String.class) ).isEqualTo("ClientUserAgentHeaderValue"); } @Test void clientIsNotSetRequestIsSet() { assertThat( clientBuilder.build("ClientName").target(testUri + "/user_agent") .request().header("User-Agent", "RequestUserAgentHeaderValue") .get(String.class) ).isEqualTo("RequestUserAgentHeaderValue"); } @Test void clientIsNotSetRequestIsNotSet() { assertThat( clientBuilder.build("ClientName").target(testUri + "/user_agent") .request() .get(String.class) ).isEqualTo("ClientName"); } @Test void clientIsSetRequestIsSet() { clientConfiguration.setUserAgent(Optional.of("ClientUserAgentHeaderValue")); assertThat( clientBuilder.build("ClientName").target(testUri + "/user_agent") .request().header("User-Agent", "RequestUserAgentHeaderValue") .get(String.class) ).isEqualTo("RequestUserAgentHeaderValue"); } @Path("/") public static
JerseyIgnoreRequestUserAgentHeaderFilterTest
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/commons/util/ReflectionUtilsTests.java
{ "start": 84862, "end": 84981 }
class ____ extends AbstractOuterClass { } // sibling of OuterClass due to common super type
StaticNestedSiblingClass
java
spring-projects__spring-boot
module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/EmbeddedDatabaseConnection.java
{ "start": 5334, "end": 5995 }
class ____ used to check for classes * @return an {@link EmbeddedDatabaseConnection} or {@link #NONE}. */ public static EmbeddedDatabaseConnection get(@Nullable ClassLoader classLoader) { for (EmbeddedDatabaseConnection candidate : EmbeddedDatabaseConnection.values()) { if (candidate == NONE) { continue; } String driverClassName = candidate.getDriverClassName(); Assert.state(driverClassName != null, "'driverClassName' must not be null"); if (ClassUtils.isPresent(driverClassName, classLoader)) { return candidate; } } return NONE; } /** * Determine if a {@link Connection} is embedded. */ private static final
loader
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/antora/GenerateAntoraPlaybook.java
{ "start": 8297, "end": 9789 }
class ____ { private final Provider<List<String>> locations; @Inject public ZipContentsCollector(Project project, Path root) { this.locations = configureZipContentCollectorLocations(project, root); } private Provider<List<String>> configureZipContentCollectorLocations(Project project, Path root) { ListProperty<String> locations = project.getObjects().listProperty(String.class); Path relativeProjectPath = relativize(root, project.getProjectDir().toPath()); String locationName = project.getName() + "-${version}-${name}-${classifier}.zip"; locations.add(project .provider(() -> relativeProjectPath.resolve(GENERATED_DOCS + "antora-content/" + locationName) .toString())); locations.addAll(getDependencies().map((dependencies) -> dependencies.stream() .map((dependency) -> relativeProjectPath .resolve(GENERATED_DOCS + "antora-dependencies-content/" + dependency + "/" + locationName)) .map(Path::toString) .toList())); return locations; } private static Path relativize(Path root, Path subPath) { return toRealPath(root).relativize(toRealPath(subPath)).normalize(); } @Input @Optional public abstract ListProperty<AlwaysInclude> getAlwaysInclude(); @Input @Optional public Provider<List<String>> getLocations() { return this.locations; } @Input @Optional public abstract SetProperty<String> getDependencies(); } } public abstract static
ZipContentsCollector
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/DelegatingMapper.java
{ "start": 1349, "end": 2047 }
class ____<K1, V1, K2, V2> extends Mapper<K1, V1, K2, V2> { private Mapper<K1, V1, K2, V2> mapper; @SuppressWarnings("unchecked") protected void setup(Context context) throws IOException, InterruptedException { // Find the Mapper from the TaggedInputSplit. TaggedInputSplit inputSplit = (TaggedInputSplit) context.getInputSplit(); mapper = (Mapper<K1, V1, K2, V2>) ReflectionUtils.newInstance(inputSplit .getMapperClass(), context.getConfiguration()); } @SuppressWarnings("unchecked") public void run(Context context) throws IOException, InterruptedException { setup(context); mapper.run(context); cleanup(context); } }
DelegatingMapper
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/logging/LoggingApplicationListenerIntegrationTests.java
{ "start": 2237, "end": 3830 }
class ____ { @Test void loggingSystemRegisteredInTheContext() { try (ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleService.class) .web(WebApplicationType.NONE) .run()) { SampleService service = context.getBean(SampleService.class); assertThat(service.loggingSystem).isNotNull(); } } @Test void logFileRegisteredInTheContextWhenApplicable(@TempDir File tempDir) { String logFile = new File(tempDir, "test.log").getAbsolutePath(); try (ConfigurableApplicationContext context = new SpringApplicationBuilder(SampleService.class) .web(WebApplicationType.NONE) .properties("logging.file.name=" + logFile) .run()) { SampleService service = context.getBean(SampleService.class); assertThat(service.logFile).isNotNull(); assertThat(service.logFile).hasToString(logFile); } finally { System.clearProperty(LoggingSystemProperty.LOG_FILE.getEnvironmentVariableName()); } } @Test void loggingPerformedDuringChildApplicationStartIsNotLost(CapturedOutput output) { new SpringApplicationBuilder(Config.class).web(WebApplicationType.NONE) .child(Config.class) .web(WebApplicationType.NONE) .listeners(new ApplicationListener<ApplicationStartingEvent>() { private final Logger logger = LoggerFactory.getLogger(getClass()); @Override public void onApplicationEvent(ApplicationStartingEvent event) { this.logger.info("Child application starting"); } }) .run(); assertThat(output).contains("Child application starting"); } @Component static
LoggingApplicationListenerIntegrationTests
java
apache__maven
impl/maven-core/src/main/java/org/apache/maven/artifact/resolver/filter/ExcludesArtifactFilter.java
{ "start": 1070, "end": 1334 }
class ____ extends IncludesArtifactFilter { public ExcludesArtifactFilter(List<String> patterns) { super(patterns); } @Override public boolean include(Artifact artifact) { return !super.include(artifact); } }
ExcludesArtifactFilter
java
apache__camel
components/camel-ignite/src/main/java/org/apache/camel/component/ignite/events/IgniteEventsConsumer.java
{ "start": 1318, "end": 3373 }
class ____ extends DefaultConsumer { private static final Logger LOG = LoggerFactory.getLogger(IgniteEventsConsumer.class); private IgniteEventsEndpoint endpoint; private IgniteEvents events; private int[] eventTypes = new int[0]; private IgnitePredicate<Event> predicate = new IgnitePredicate<Event>() { private static final long serialVersionUID = 6738594728074592726L; @Override public boolean apply(Event event) { Exchange exchange = createExchange(true); Message in = exchange.getIn(); in.setBody(event); try { if (LOG.isTraceEnabled()) { LOG.trace("Processing Ignite Event: {}.", event); } // use default consumer callback AsyncCallback cb = defaultConsumerCallback(exchange, true); getAsyncProcessor().process(exchange, cb); } catch (Exception e) { LOG.error(String.format("Exception while processing Ignite Event: %s.", event), e); } return true; } }; public IgniteEventsConsumer(IgniteEventsEndpoint endpoint, Processor processor, IgniteEvents events) { super(endpoint, processor); this.endpoint = endpoint; this.events = events; } @Override protected void doStart() throws Exception { super.doStart(); List<Integer> ids = endpoint.getEventsAsIds(); eventTypes = new int[ids.size()]; int counter = 0; for (Integer i : ids) { eventTypes[counter++] = i; } events.localListen(predicate, eventTypes); LOG.info("Started local Ignite Events consumer for events: {}.", Arrays.asList(eventTypes)); } @Override protected void doStop() throws Exception { super.doStop(); events.stopLocalListen(predicate, eventTypes); LOG.info("Stopped local Ignite Events consumer for events: {}.", Arrays.asList(eventTypes)); } }
IgniteEventsConsumer
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SchematronEndpointBuilderFactory.java
{ "start": 7904, "end": 8792 }
class ____ or * location in the file system. * This option can also be loaded from an existing file, by prefixing * with file: or classpath: followed by the location of the file. * * @param path path * @return the dsl builder */ default SchematronEndpointBuilder schematron(String path) { return SchematronEndpointBuilderFactory.endpointBuilder("schematron", path); } /** * Schematron (camel-schematron) * Validate XML payload using the Schematron Library. * * Category: validation * Since: 2.15 * Maven coordinates: org.apache.camel:camel-schematron * * Syntax: <code>schematron:path</code> * * Path parameter: path (required) * The path to the schematron rules file. Can either be in
path
java
apache__kafka
shell/src/main/java/org/apache/kafka/shell/glob/GlobVisitor.java
{ "start": 1578, "end": 5482 }
class ____ { private final String[] path; private final MetadataNode node; MetadataNodeInfo(String[] path, MetadataNode node) { this.path = path; this.node = node; } public MetadataNode node() { return node; } public String lastPathComponent() { if (path.length == 0) { return "/"; } else { return path[path.length - 1]; } } public String absolutePath() { return "/" + String.join("/", path); } @Override public int hashCode() { return Objects.hash(Arrays.hashCode(path), node); } @Override public boolean equals(Object o) { if (!(o instanceof MetadataNodeInfo other)) return false; if (!Arrays.equals(path, other.path)) return false; return node.equals(other.node); } @Override public String toString() { StringBuilder bld = new StringBuilder("MetadataNodeInfo(path="); for (String s : path) { bld.append("/"); bld.append(s); } bld.append(", node=").append(node).append(")"); return bld.toString(); } } @Override public void accept(MetadataShellState state) { String fullGlob = glob.startsWith("/") ? glob : state.workingDirectory() + "/" + glob; List<String> globComponents = CommandUtils.stripDotPathComponents(CommandUtils.splitPath(fullGlob)); MetadataNode root = state.root(); if (root == null) { throw new RuntimeException("Invalid null root"); } if (!accept(globComponents, 0, root, new String[0])) { handler.accept(Optional.empty()); } } private boolean accept( List<String> globComponents, int componentIndex, MetadataNode node, String[] path ) { if (componentIndex >= globComponents.size()) { handler.accept(Optional.of(new MetadataNodeInfo(path, node))); return true; } String globComponentString = globComponents.get(componentIndex); GlobComponent globComponent = new GlobComponent(globComponentString); if (globComponent.literal()) { if (!node.isDirectory()) { return false; } MetadataNode child = node.child(globComponent.component()); if (child == null) { return false; } String[] newPath = new String[path.length + 1]; System.arraycopy(path, 0, newPath, 0, path.length); newPath[path.length] = globComponent.component(); return accept(globComponents, componentIndex + 1, child, newPath); } if (!node.isDirectory()) { return false; } boolean matchedAny = false; ArrayList<String> nodeChildNames = new ArrayList<>(node.childNames()); nodeChildNames.sort(String::compareTo); for (String nodeName : nodeChildNames) { if (globComponent.matches(nodeName)) { String[] newPath = new String[path.length + 1]; System.arraycopy(path, 0, newPath, 0, path.length); newPath[path.length] = nodeName; MetadataNode child = node.child(nodeName); if (child == null) { throw new RuntimeException("Expected " + nodeName + " to be a valid child of " + node.getClass() + ", but it was not."); } if (accept(globComponents, componentIndex + 1, child, newPath)) { matchedAny = true; } } } return matchedAny; } }
MetadataNodeInfo
java
spring-projects__spring-boot
module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/endpoint/invoke/OperationParameter.java
{ "start": 1375, "end": 1563 }
class ____ the annotation * @return annotation value * @param <T> type of the annotation * @since 2.7.8 */ <T extends Annotation> @Nullable T getAnnotation(Class<T> annotation); }
of
java
spring-projects__spring-boot
module/spring-boot-web-server/src/test/java/org/springframework/boot/web/server/SpringApplicationWebServerTests.java
{ "start": 7579, "end": 7840 }
class ____ { @Bean MockReactiveWebServerFactory webServerFactory() { return new MockReactiveWebServerFactory(); } @Bean HttpHandler httpHandler() { return (serverHttpRequest, serverHttpResponse) -> Mono.empty(); } } }
ExampleReactiveWebConfig
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/LargerThanDefaultFormAttributeMultipartFormInputTest.java
{ "start": 945, "end": 2437 }
class ____ { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(Resource.class, Data.class) .addAsResource(new StringAsset( "quarkus.http.limits.max-form-attribute-size=120K"), "application.properties"); } }); private final File FILE = new File("./src/test/resources/larger-than-default-form-attribute.txt"); @Test public void test() throws IOException { String fileContents = Files.readString(FILE.toPath()); StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; ++i) { sb.append(fileContents); } fileContents = sb.toString(); Assertions.assertTrue(fileContents.length() > HttpServerOptions.DEFAULT_MAX_FORM_ATTRIBUTE_SIZE); given() .multiPart("text", fileContents) .accept("text/plain") .when() .post("/test") .then() .statusCode(200) .contentType(ContentType.TEXT) .body(equalTo(fileContents)); } @Path("/test") public static
LargerThanDefaultFormAttributeMultipartFormInputTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/sampler/random/RandomSamplingQuery.java
{ "start": 1339, "end": 4323 }
class ____ extends Query { private final double p; private final int seed; private final int hash; /** * @param p The sampling probability e.g. 0.05 == 5% probability a document will match * @param seed The seed from the builder * @param hash A unique hash so that if the same seed is used between multiple queries, unique random number streams * can be generated */ public RandomSamplingQuery(double p, int seed, int hash) { checkProbabilityRange(p); this.p = p; this.seed = seed; this.hash = hash; } /** * Verifies that the probability is within the (0.0, 1.0) range. * @throws IllegalArgumentException in case of an invalid probability. */ public static void checkProbabilityRange(double p) throws IllegalArgumentException { if (p <= 0.0 || p >= 1.0) { throw new IllegalArgumentException("RandomSampling probability must be strictly between 0.0 and 1.0, was [" + p + "]"); } } public double probability() { return p; } public int seed() { return seed; } public int hash() { return hash; } @Override public String toString(String field) { return "RandomSamplingQuery{" + "p=" + p + ", seed=" + seed + ", hash=" + hash + '}'; } @Override public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException { return new Weight(this) { @Override public boolean isCacheable(LeafReaderContext ctx) { return true; } @Override public Explanation explain(LeafReaderContext context, int doc) throws IOException { final Scorer s = scorer(context); final boolean exists = s.iterator().advance(doc) == doc; if (exists) { return Explanation.match(boost, getQuery().toString()); } else { return Explanation.noMatch(getQuery().toString() + " doesn't match id " + doc); } } @Override public ScorerSupplier scorerSupplier(LeafReaderContext context) throws IOException { final SplittableRandom random = new SplittableRandom(BitMixer.mix(hash ^ seed)); int maxDoc = context.reader().maxDoc(); Scorer scorer = new ConstantScoreScorer( boost, ScoreMode.COMPLETE_NO_SCORES, new RandomSamplingIterator(maxDoc, p, random::nextInt) ); return new DefaultScorerSupplier(scorer); } }; } @Override public void visit(QueryVisitor visitor) { visitor.visitLeaf(this); } /** * A DocIDSetIter that skips a geometrically random number of documents */ public static
RandomSamplingQuery
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/aggfunctions/LastValueAggFunctionWithoutOrderTest.java
{ "start": 10112, "end": 10789 }
class ____<T> extends LastValueAggFunctionWithoutOrderTestBase<T> { protected abstract T getValue(String v); @Override protected List<List<T>> getInputValueSets() { return Arrays.asList( Arrays.asList(getValue("1"), null, getValue("-99"), getValue("3"), null), Arrays.asList(null, null, null, null), Arrays.asList(null, getValue("10"), null, getValue("3"))); } @Override protected List<T> getExpectedResults() { return Arrays.asList(getValue("3"), null, getValue("3")); } } }
NumberLastValueAggFunctionWithoutOrderTestBase
java
alibaba__nacos
config/src/test/java/com/alibaba/nacos/config/server/manager/TaskManagerTest.java
{ "start": 1616, "end": 4820 }
class ____ { private TaskManager taskManager; @Mock private NacosTaskProcessor taskProcessor; @Mock private NacosTaskProcessor testTaskProcessor; private AbstractDelayTask abstractTask; @BeforeEach void setUp() { taskManager = new TaskManager(TaskManagerTest.class.getName()); taskManager.setDefaultTaskProcessor(taskProcessor); abstractTask = new AbstractDelayTask() { @Override public void merge(AbstractDelayTask task) { } }; } @AfterEach void tearDown() { taskManager.close(); } @Test void testSize() { assertEquals(0, taskManager.size()); taskManager.addTask("test", abstractTask); assertEquals(1, taskManager.size()); taskManager.removeTask("test"); assertEquals(0, taskManager.size()); } @Test void testIsEmpty() { assertTrue(taskManager.isEmpty()); taskManager.addTask("test", abstractTask); assertFalse(taskManager.isEmpty()); taskManager.removeTask("test"); assertTrue(taskManager.isEmpty()); } @Test void testAddProcessor() throws InterruptedException { when(testTaskProcessor.process(abstractTask)).thenReturn(true); taskManager.addProcessor("test", testTaskProcessor); taskManager.addTask("test", abstractTask); TimeUnit.MILLISECONDS.sleep(200); verify(testTaskProcessor).process(abstractTask); verify(taskProcessor, never()).process(abstractTask); } @Test void testRemoveProcessor() throws InterruptedException { when(taskProcessor.process(abstractTask)).thenReturn(true); taskManager.addProcessor("test", testTaskProcessor); taskManager.removeProcessor("test"); taskManager.addTask("test", abstractTask); TimeUnit.MILLISECONDS.sleep(200); verify(testTaskProcessor, never()).process(abstractTask); verify(taskProcessor).process(abstractTask); } @Test void testRetryTaskAfterFail() throws InterruptedException { when(taskProcessor.process(abstractTask)).thenReturn(false, true); taskManager.addTask("test", abstractTask); TimeUnit.MILLISECONDS.sleep(300); verify(taskProcessor, new Times(2)).process(abstractTask); } @Test void testGetTaskInfos() throws InterruptedException { taskManager.addProcessor("test", testTaskProcessor); when(testTaskProcessor.process(abstractTask)).thenReturn(true); taskManager.addTask("test", abstractTask); assertEquals("test:" + new Date(0) + Constants.NACOS_LINE_SEPARATOR, taskManager.getTaskInfos()); TimeUnit.MILLISECONDS.sleep(150); assertEquals("test:finished" + Constants.NACOS_LINE_SEPARATOR, taskManager.getTaskInfos()); } @Test void testInit() throws Exception { taskManager.init(); ObjectName oName = new ObjectName(TaskManagerTest.class.getName() + ":type=" + TaskManager.class.getSimpleName()); assertTrue(ManagementFactory.getPlatformMBeanServer().isRegistered(oName)); } }
TaskManagerTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/protocol/impl/pb/NamenodeHeartbeatResponsePBImpl.java
{ "start": 1477, "end": 2603 }
class ____ extends NamenodeHeartbeatResponse implements PBRecord { private FederationProtocolPBTranslator<NamenodeHeartbeatResponseProto, NamenodeHeartbeatResponseProto.Builder, NamenodeHeartbeatResponseProtoOrBuilder> translator = new FederationProtocolPBTranslator<NamenodeHeartbeatResponseProto, NamenodeHeartbeatResponseProto.Builder, NamenodeHeartbeatResponseProtoOrBuilder>( NamenodeHeartbeatResponseProto.class); public NamenodeHeartbeatResponsePBImpl() { } @Override public NamenodeHeartbeatResponseProto getProto() { return this.translator.build(); } @Override public void setProto(Message proto) { this.translator.setProto(proto); } @Override public void readInstance(String base64String) throws IOException { this.translator.readInstance(base64String); } @Override public boolean getResult() { return this.translator.getProtoOrBuilder().getStatus(); } @Override public void setResult(boolean result) { this.translator.getBuilder().setStatus(result); } }
NamenodeHeartbeatResponsePBImpl
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/LambdaFunctionalInterfaceTest.java
{ "start": 12397, "end": 13259 }
class ____ { private static <T extends Number> List<T> numToTFunction(DoubleFunction<T> converter) { List<T> namedNumberIntervals = new ArrayList<>(); T min = converter.apply(2.9); T max = converter.apply(5.6); namedNumberIntervals.add(min); namedNumberIntervals.add(max); return namedNumberIntervals; } public List<Integer> getIntList() { List<Integer> result = numToTFunction(num -> 2); return result; } public List<Double> getDoubleList() { List<Double> result = numToTFunction(num -> 3.2); return result; } } """) .setFixChooser(FixChoosers.FIRST) .doTest(); } @Test public void refactoringGenericToPrimitive() { refactoringHelper .addInputLines( "in/NumbertoT.java", """ import java.util.function.Function; public
NumbertoT
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bootstrap/binding/annotations/plural/orderby/compliance/OrderByMappingComplianceTest.java
{ "start": 2463, "end": 2585 }
class ____ { @Id private Integer id; private String sku; @Column( name = "qty" ) private int quantity; } }
LineItem
java
google__dagger
javatests/dagger/internal/codegen/IgnoreProvisionKeyWildcardsTest.java
{ "start": 16206, "end": 16396 }
interface ____ {", " fun mapExtends(): Map<String, Foo<out Bar>>", " fun map(): Map<String, Foo<Bar>>", "}", "@Module", "
MyComponent
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/ssl/ServerSslConfiguration.java
{ "start": 996, "end": 4248 }
class ____ extends SslConfiguration { /** * The prefix used to resolve this configuration. */ public static final String PREFIX = "micronaut.server.ssl"; /** * Overrides the default constructor and sets {@link #isEnabled()} to true. * * @param defaultSslConfiguration The default SSL config * @param defaultKeyConfiguration The default key config * @param defaultKeyStoreConfiguration The default keystore config * @param defaultTrustStoreConfiguration The Default truststore config */ @Inject public ServerSslConfiguration( DefaultSslConfiguration defaultSslConfiguration, DefaultSslConfiguration.DefaultKeyConfiguration defaultKeyConfiguration, DefaultSslConfiguration.DefaultKeyStoreConfiguration defaultKeyStoreConfiguration, SslConfiguration.TrustStoreConfiguration defaultTrustStoreConfiguration) { readExisting(defaultSslConfiguration, defaultKeyConfiguration, defaultKeyStoreConfiguration, defaultTrustStoreConfiguration); } /** * Constructs the default server SSL configuration. */ public ServerSslConfiguration() { } /** * Sets the key configuration. * * @param keyConfiguration The key configuration. */ @Inject void setKey(@Nullable DefaultKeyConfiguration keyConfiguration) { if (keyConfiguration != null) { super.setKey(keyConfiguration); } } /** * Sets the key store. * * @param keyStoreConfiguration The key store configuration */ @Inject @SuppressWarnings("unused") void setKeyStore(@Nullable DefaultKeyStoreConfiguration keyStoreConfiguration) { if (keyStoreConfiguration != null) { super.setKeyStore(keyStoreConfiguration); } } /** * Sets trust store configuration. * * @param trustStore The trust store configuration */ @Inject @SuppressWarnings("unused") void setTrustStore(@Nullable DefaultTrustStoreConfiguration trustStore) { if (trustStore != null) { super.setTrustStore(trustStore); } } /** * Sets the SSL port. Default value ({@value SslConfiguration#DEFAULT_PORT}). * * @param port The port * @deprecated Please use {@code micronaut.server.ssl.port} instead ({@link ServerSslConfiguration#setPort(int)}). */ @Override @Deprecated @SuppressWarnings("deprecation") public void setPort(int port) { this.port = port; } /** * Sets whether to build a self-signed certificate. Default value ({@value SslConfiguration#DEFAULT_BUILDSELFSIGNED}). * * @param buildSelfSigned True if a certificate should be built */ @Override @SuppressWarnings("deprecation") public void setBuildSelfSigned(boolean buildSelfSigned) { this.buildSelfSigned = buildSelfSigned; } /** * The default {@link io.micronaut.http.ssl.SslConfiguration.KeyConfiguration}. */ @SuppressWarnings("WeakerAccess") @ConfigurationProperties(KeyConfiguration.PREFIX) @Requires(property = ServerSslConfiguration.PREFIX + "." + KeyConfiguration.PREFIX) public static
ServerSslConfiguration
java
apache__camel
core/camel-main/src/test/java/org/apache/camel/main/MainBeansTest.java
{ "start": 1576, "end": 2612 }
class ____.addProperty("camel.beans.foo", "#class:org.apache.camel.main.MySedaBlockingQueueFactory"); main.addProperty("camel.beans.foo.counter", "123"); // lookup by type main.addProperty("camel.beans.myfoo", "#type:org.apache.camel.main.MyFoo"); main.addProperty("camel.beans.myfoo.name", "Donkey"); main.start(); CamelContext camelContext = main.getCamelContext(); assertNotNull(camelContext); Object foo = camelContext.getRegistry().lookupByName("foo"); assertNotNull(foo); MySedaBlockingQueueFactory myBQF = camelContext.getRegistry().findByType(MySedaBlockingQueueFactory.class).iterator().next(); assertSame(foo, myBQF); assertEquals(123, myBQF.getCounter()); assertEquals("Donkey", myFoo.getName()); main.stop(); } @Test public void testBindBeansMap() { Main main = new Main(); main.configure().addRoutesBuilder(new MyRouteBuilder()); // create by
main
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/various/OneOneGeneratedValueTest.java
{ "start": 1438, "end": 1820 }
class ____ { @Id private Long id; private String name; @OneToOne(mappedBy = "a") private EntityB b; public EntityA() { } public EntityA(Long id) { this.id = id; } public Long getId() { return id; } public EntityB getB() { return b; } } @Entity(name = "EntityB") @Subselect("SELECT 5 as b, a.id AS AId FROM TABLE_A a") public static
EntityA
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/testutils/SystemExitTrackingSecurityManager.java
{ "start": 1168, "end": 1988 }
class ____ extends SecurityManager { private final CompletableFuture<Integer> systemExitFuture = new CompletableFuture<>(); @Override public void checkPermission(final Permission perm) {} @Override public void checkPermission(final Permission perm, final Object context) {} @Override public synchronized void checkExit(final int status) { systemExitFuture.complete(status); throw new SecurityException( "SystemExitTrackingSecurityManager is installed. JVM will not exit"); } /** * Returns a {@link CompletableFuture} that is completed with the exit code when {@link * System#exit(int)} is called. */ public CompletableFuture<Integer> getSystemExitFuture() { return systemExitFuture; } }
SystemExitTrackingSecurityManager
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/dialect/mysql/ast/clause/MySqlRepeatStatement.java
{ "start": 1008, "end": 1956 }
class ____ extends MySqlStatementImpl { private String labelName; private List<SQLStatement> statements = new ArrayList<SQLStatement>(); private SQLExpr condition; @Override public void accept0(MySqlASTVisitor visitor) { if (visitor.visit(this)) { acceptChild(visitor, statements); acceptChild(visitor, condition); } visitor.endVisit(this); } public List<SQLStatement> getStatements() { return statements; } public void setStatements(List<SQLStatement> statements) { this.statements = statements; } public String getLabelName() { return labelName; } public void setLabelName(String labelName) { this.labelName = labelName; } public SQLExpr getCondition() { return condition; } public void setCondition(SQLExpr condition) { this.condition = condition; } }
MySqlRepeatStatement
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/GooglePubsubLiteComponentBuilderFactory.java
{ "start": 1425, "end": 2008 }
interface ____ { /** * Google PubSub Lite (camel-google-pubsub-lite) * Send and receive messages to/from Google Cloud Platform PubSub Lite * Service. * * Category: cloud,messaging * Since: 4.6 * Maven coordinates: org.apache.camel:camel-google-pubsub-lite * * @return the dsl builder */ static GooglePubsubLiteComponentBuilder googlePubsubLite() { return new GooglePubsubLiteComponentBuilderImpl(); } /** * Builder for the Google PubSub Lite component. */
GooglePubsubLiteComponentBuilderFactory
java
greenrobot__greendao
DaoGenerator/src/org/greenrobot/greendao/generator/ContentProvider.java
{ "start": 902, "end": 2580 }
class ____ { private final List<Entity> entities; private String authority; private String basePath; private String className; private String javaPackage; private boolean readOnly; private Schema schema; public ContentProvider(Schema schema, List<Entity> entities) { this.schema = schema; this.entities = entities; } public String getAuthority() { return authority; } public void setAuthority(String authority) { this.authority = authority; } public String getBasePath() { return basePath; } public void setBasePath(String basePath) { this.basePath = basePath; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getJavaPackage() { return javaPackage; } public void setJavaPackage(String javaPackage) { this.javaPackage = javaPackage; } public boolean isReadOnly() { return readOnly; } public void readOnly() { this.readOnly = true; } public List<Entity> getEntities() { return entities; } public void init2ndPass() { if (authority == null) { authority = schema.getDefaultJavaPackage() + ".provider"; } if (basePath == null) { basePath = ""; } if (className == null) { className = entities.get(0).getClassName() + "ContentProvider"; } if (javaPackage == null) { javaPackage = schema.getDefaultJavaPackage(); } } }
ContentProvider
java
dropwizard__dropwizard
dropwizard-validation/src/test/java/io/dropwizard/validation/DurationValidatorTest.java
{ "start": 522, "end": 4542 }
class ____ { @MaxDuration(value = 30, unit = TimeUnit.SECONDS) private Duration tooBig = Duration.minutes(10); @MaxDuration(value = 30, unit = TimeUnit.SECONDS, inclusive = false) private Duration tooBigExclusive = Duration.seconds(30); @MinDuration(value = 30, unit = TimeUnit.SECONDS) private Duration tooSmall = Duration.milliseconds(100); @MinDuration(value = 30, unit = TimeUnit.SECONDS, inclusive = false) private Duration tooSmallExclusive = Duration.seconds(30); @DurationRange(min = 10, max = 30, unit = TimeUnit.MINUTES) private Duration outOfRange = Duration.minutes(60); @Valid private List<@MaxDuration(value = 30, unit = TimeUnit.SECONDS) Duration> maxDurs = Collections.singletonList(Duration.minutes(10)); @Valid private List<@MinDuration(value = 30, unit = TimeUnit.SECONDS) Duration> minDurs = Collections.singletonList(Duration.milliseconds(100)); @Valid private List<@DurationRange(min = 10, max = 30, unit = TimeUnit.MINUTES) Duration> rangeDurs = Collections.singletonList(Duration.minutes(60)); public void setTooBig(Duration tooBig) { this.tooBig = tooBig; } public void setTooBigExclusive(Duration tooBigExclusive) { this.tooBigExclusive = tooBigExclusive; } public void setTooSmall(Duration tooSmall) { this.tooSmall = tooSmall; } public void setTooSmallExclusive(Duration tooSmallExclusive) { this.tooSmallExclusive = tooSmallExclusive; } public void setOutOfRange(Duration outOfRange) { this.outOfRange = outOfRange; } public void setMaxDurs(List<Duration> maxDurs) { this.maxDurs = maxDurs; } public void setMinDurs(List<Duration> minDurs) { this.minDurs = minDurs; } public void setRangeDurs(List<Duration> rangeDurs) { this.rangeDurs = rangeDurs; } } private final Validator validator = BaseValidator.newValidator(); @Test void returnsASetOfErrorsForAnObject() throws Exception { assumeTrue("en".equals(Locale.getDefault().getLanguage()), "This test executes when the defined language is English ('en'). If not, it is skipped."); final Collection<String> errors = ConstraintViolations.format(validator.validate(new Example())); assertThat(errors) .containsOnly( "outOfRange must be between 10 MINUTES and 30 MINUTES", "tooBig must be less than or equal to 30 SECONDS", "tooBigExclusive must be less than 30 SECONDS", "tooSmall must be greater than or equal to 30 SECONDS", "tooSmallExclusive must be greater than 30 SECONDS", "maxDurs[0].<list element> must be less than or equal to 30 SECONDS", "minDurs[0].<list element> must be greater than or equal to 30 SECONDS", "rangeDurs[0].<list element> must be between 10 MINUTES and 30 MINUTES"); } @Test void returnsAnEmptySetForAValidObject() throws Exception { final Example example = new Example(); example.setTooBig(Duration.seconds(10)); example.setTooBigExclusive(Duration.seconds(29)); example.setTooSmall(Duration.seconds(100)); example.setTooSmallExclusive(Duration.seconds(31)); example.setOutOfRange(Duration.minutes(15)); example.setMaxDurs(Collections.singletonList(Duration.seconds(10))); example.setMinDurs(Collections.singletonList(Duration.seconds(100))); example.setRangeDurs(Collections.singletonList(Duration.minutes(15))); assertThat(validator.validate(example)) .isEmpty(); } }
Example
java
apache__camel
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java
{ "start": 585375, "end": 590858 }
class ____ extends YamlDeserializerBase<LogDefinition> { public LogDefinitionDeserializer() { super(LogDefinition.class); } @Override protected LogDefinition newInstance() { return new LogDefinition(); } @Override protected LogDefinition newInstance(String value) { return new LogDefinition(value); } @Override protected boolean setProperty(LogDefinition target, String propertyKey, String propertyName, Node node) { propertyKey = org.apache.camel.util.StringHelper.dashToCamelCase(propertyKey); switch(propertyKey) { case "disabled": { String val = asText(node); target.setDisabled(val); break; } case "logLanguage": { String val = asText(node); target.setLogLanguage(val); break; } case "logName": { String val = asText(node); target.setLogName(val); break; } case "logger": { String val = asText(node); target.setLogger(val); break; } case "loggingLevel": { String val = asText(node); target.setLoggingLevel(val); break; } case "marker": { String val = asText(node); target.setMarker(val); break; } case "message": { String val = asText(node); target.setMessage(val); break; } case "id": { String val = asText(node); target.setId(val); break; } case "description": { String val = asText(node); target.setDescription(val); break; } case "note": { String val = asText(node); target.setNote(val); break; } default: { return false; } } return true; } } @YamlType( nodes = "loop", types = org.apache.camel.model.LoopDefinition.class, order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1, displayName = "Loop", description = "Processes a message multiple times", deprecated = false, properties = { @YamlProperty(name = "__extends", type = "object:org.apache.camel.model.language.ExpressionDefinition", oneOf = "expression"), @YamlProperty(name = "breakOnShutdown", type = "boolean", defaultValue = "false", description = "If the breakOnShutdown attribute is true, then the loop will not iterate until it reaches the end when Camel is shut down.", displayName = "Break On Shutdown"), @YamlProperty(name = "copy", type = "boolean", defaultValue = "false", description = "If the copy attribute is true, a copy of the input Exchange is used for each iteration. That means each iteration will start from a copy of the same message. By default loop will loop the same exchange all over, so each iteration may have different message content.", displayName = "Copy"), @YamlProperty(name = "description", type = "string", description = "Sets the description of this node", displayName = "Description"), @YamlProperty(name = "disabled", type = "boolean", defaultValue = "false", description = "Disables this EIP from the route.", displayName = "Disabled"), @YamlProperty(name = "doWhile", type = "boolean", defaultValue = "false", description = "Enables the while loop that loops until the predicate evaluates to false or null.", displayName = "Do While"), @YamlProperty(name = "expression", type = "object:org.apache.camel.model.language.ExpressionDefinition", description = "Expression to define how many times we should loop. Notice the expression is only evaluated once, and should return a number as how many times to loop. A value of zero or negative means no looping. The loop is like a for-loop fashion, if you want a while loop, then the dynamic router may be a better choice.", displayName = "Expression", oneOf = "expression"), @YamlProperty(name = "id", type = "string", description = "Sets the id of this node", displayName = "Id"), @YamlProperty(name = "note", type = "string", description = "Sets the note of this node", displayName = "Note"), @YamlProperty(name = "onPrepare", type = "string", description = "Uses the Processor when preparing the org.apache.camel.Exchange for each loop iteration. This can be used to deep-clone messages, or any custom logic needed before the looping executes.", displayName = "On Prepare"), @YamlProperty(name = "steps", type = "array:org.apache.camel.model.ProcessorDefinition") } ) public static
LogDefinitionDeserializer
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/ResponseType.java
{ "start": 279, "end": 1630 }
enum ____ { /** * Returns DTOs directly. */ PLAIN(true, "plain"), /** * Returns {@link Multi} with DTOs. */ // TODO: enable when https://github.com/quarkusio/quarkus/issues/40447 gets fixed //MULTI(true, "multi"), /** * Returns {@link Uni} with DTOs. */ UNI(true, "uni"), /** * Returns {@link Object} that is either DTO with a {@link SecureField} or not. */ OBJECT(false, "object"), // we must always assume it can contain SecureField /** * Returns {@link Response} that is either DTO with a {@link SecureField} or not. */ RESPONSE(false, "response"), // we must always assume it can contain SecureField /** * Returns {@link RestResponse} with DTOs. */ REST_RESPONSE(true, "rest-response"), /** * Returns {@link RestResponse} with DTOs. */ COLLECTION(true, "collection"); private final boolean secureFieldDetectable; private final String resourceSubPath; ResponseType(boolean secureFieldDetectable, String resourceSubPath) { this.secureFieldDetectable = secureFieldDetectable; this.resourceSubPath = resourceSubPath; } boolean isSecureFieldDetectable() { return secureFieldDetectable; } String getResourceSubPath() { return resourceSubPath; } }
ResponseType
java
junit-team__junit5
junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/execution/InvocationInterceptorChain.java
{ "start": 3056, "end": 3542 }
interface ____ { void apply(InvocationInterceptor interceptor, Invocation<@Nullable Void> invocation) throws Throwable; } private record InterceptedInvocation<T>(Invocation<T> invocation, InterceptorCall<T> call, InvocationInterceptor interceptor) implements Invocation<T> { @Override public T proceed() throws Throwable { return call.apply(interceptor, invocation); } @Override public void skip() { invocation.skip(); } } private static
VoidInterceptorCall
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/gateway/GatewayService.java
{ "start": 2057, "end": 6610 }
class ____ extends AbstractLifecycleComponent implements ClusterStateListener { private static final Logger logger = LogManager.getLogger(GatewayService.class); public static final Setting<Integer> EXPECTED_DATA_NODES_SETTING = Setting.intSetting( "gateway.expected_data_nodes", -1, -1, Property.NodeScope ); public static final Setting<TimeValue> RECOVER_AFTER_TIME_SETTING = Setting.positiveTimeSetting( "gateway.recover_after_time", TimeValue.timeValueMillis(0), Property.NodeScope ); public static final Setting<Integer> RECOVER_AFTER_DATA_NODES_SETTING = Setting.intSetting( "gateway.recover_after_data_nodes", -1, -1, Property.NodeScope ); public static final ClusterBlock STATE_NOT_RECOVERED_BLOCK = new ClusterBlock( 1, "state not recovered / initialized", true, true, false, RestStatus.SERVICE_UNAVAILABLE, ClusterBlockLevel.ALL ); static final TimeValue DEFAULT_RECOVER_AFTER_TIME_IF_EXPECTED_NODES_IS_SET = TimeValue.timeValueMinutes(5); private final ShardRoutingRoleStrategy shardRoutingRoleStrategy; private final ThreadPool threadPool; private final RerouteService rerouteService; private final ClusterService clusterService; private final TimeValue recoverAfterTime; private final int recoverAfterDataNodes; private final int expectedDataNodes; volatile PendingStateRecovery currentPendingStateRecovery; @Inject public GatewayService( final Settings settings, final RerouteService rerouteService, final ClusterService clusterService, final ShardRoutingRoleStrategy shardRoutingRoleStrategy, final ThreadPool threadPool ) { this.rerouteService = rerouteService; this.clusterService = clusterService; this.shardRoutingRoleStrategy = shardRoutingRoleStrategy; this.threadPool = threadPool; this.expectedDataNodes = EXPECTED_DATA_NODES_SETTING.get(settings); if (RECOVER_AFTER_TIME_SETTING.exists(settings)) { recoverAfterTime = RECOVER_AFTER_TIME_SETTING.get(settings); } else if (expectedDataNodes >= 0) { recoverAfterTime = DEFAULT_RECOVER_AFTER_TIME_IF_EXPECTED_NODES_IS_SET; } else { recoverAfterTime = null; } this.recoverAfterDataNodes = RECOVER_AFTER_DATA_NODES_SETTING.get(settings); } @Override protected void doStart() { if (DiscoveryNode.isMasterNode(clusterService.getSettings())) { // use post applied so that the state will be visible to the background recovery thread we spawn in performStateRecovery clusterService.addListener(this); } } @Override protected void doStop() { clusterService.removeListener(this); } @Override protected void doClose() {} @Override public void clusterChanged(final ClusterChangedEvent event) { if (lifecycle.stoppedOrClosed()) { return; } final ClusterState state = event.state(); final DiscoveryNodes nodes = state.nodes(); if (nodes.isLocalNodeElectedMaster() == false) { // not our job to recover return; } if (state.blocks().hasGlobalBlock(STATE_NOT_RECOVERED_BLOCK) == false) { // already recovered return; } // At this point, we know the state is not recovered and this node is qualified for state recovery // But we still need to check whether a previous one is running already final long currentTerm = state.term(); final PendingStateRecovery existingPendingStateRecovery = currentPendingStateRecovery; // Always start a new state recovery if the master term changes // If there is a previous one still waiting, both will probably run but at most one of them will // actually make changes to cluster state because either: // 1. The previous recovers the cluster state and the current one will be skipped // 2. The previous one sees a new cluster term and skips its own execution if (existingPendingStateRecovery == null || existingPendingStateRecovery.expectedTerm < currentTerm) { currentPendingStateRecovery = new PendingStateRecovery(currentTerm); } currentPendingStateRecovery.onDataNodeSize(nodes.getDataNodes().size()); } /** * This
GatewayService
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/filesystem/AbstractFileStateBackend.java
{ "start": 3401, "end": 9978 }
class ____ extends AbstractStateBackend implements CheckpointStorage { private static final long serialVersionUID = 1L; // ------------------------------------------------------------------------ // State Backend Properties // ------------------------------------------------------------------------ /** The path where checkpoints will be stored, or null, if none has been configured. */ @Nullable private final Path baseCheckpointPath; /** The path where savepoints will be stored, or null, if none has been configured. */ @Nullable private final Path baseSavepointPath; /** * Creates a backend with the given optional checkpoint- and savepoint base directories. * * @param baseCheckpointPath The base directory for checkpoints, or null, if none is configured. * @param baseSavepointPath The default directory for savepoints, or null, if none is set. */ protected AbstractFileStateBackend( @Nullable URI baseCheckpointPath, @Nullable URI baseSavepointPath) { this( baseCheckpointPath == null ? null : new Path(baseCheckpointPath), baseSavepointPath == null ? null : new Path(baseSavepointPath)); } /** * Creates a backend with the given optional checkpoint- and savepoint base directories. * * @param baseCheckpointPath The base directory for checkpoints, or null, if none is configured. * @param baseSavepointPath The default directory for savepoints, or null, if none is set. */ protected AbstractFileStateBackend( @Nullable Path baseCheckpointPath, @Nullable Path baseSavepointPath) { this.baseCheckpointPath = baseCheckpointPath == null ? null : validatePath(baseCheckpointPath); this.baseSavepointPath = baseSavepointPath == null ? null : validatePath(baseSavepointPath); } /** * Creates a new backend using the given checkpoint-/savepoint directories, or the values * defined in the given configuration. If a checkpoint-/savepoint parameter is not null, that * value takes precedence over the value in the configuration. If the configuration does not * specify a value, it is possible that the checkpoint-/savepoint directories in the backend * will be null. * * <p>This constructor can be used to create a backend that is based partially on a given * backend and partially on a configuration. * * @param baseCheckpointPath The checkpoint base directory to use (or null). * @param baseSavepointPath The default savepoint directory to use (or null). * @param configuration The configuration to read values from. */ protected AbstractFileStateBackend( @Nullable Path baseCheckpointPath, @Nullable Path baseSavepointPath, ReadableConfig configuration) { this( parameterOrConfigured( baseCheckpointPath, configuration, CheckpointingOptions.CHECKPOINTS_DIRECTORY), parameterOrConfigured( baseSavepointPath, configuration, CheckpointingOptions.SAVEPOINT_DIRECTORY)); } // ------------------------------------------------------------------------ /** * Gets the checkpoint base directory. Jobs will create job-specific subdirectories for * checkpoints within this directory. May be null, if not configured. * * @return The checkpoint base directory */ @Nullable public Path getCheckpointPath() { return baseCheckpointPath; } /** * Gets the directory where savepoints are stored by default (when no custom path is given to * the savepoint trigger command). * * @return The default directory for savepoints, or null, if no default directory has been * configured. */ @Nullable public Path getSavepointPath() { return baseSavepointPath; } // ------------------------------------------------------------------------ // Initialization and metadata storage // ------------------------------------------------------------------------ @Override public CompletedCheckpointStorageLocation resolveCheckpoint(String pointer) throws IOException { return AbstractFsCheckpointStorageAccess.resolveCheckpointPointer(pointer); } // ------------------------------------------------------------------------ // Utilities // ------------------------------------------------------------------------ /** * Checks the validity of the path's scheme and path. * * @param path The path to check. * @return The URI as a Path. * @throws IllegalArgumentException Thrown, if the URI misses scheme or path. */ private static Path validatePath(Path path) { final URI uri = path.toUri(); final String scheme = uri.getScheme(); final String pathPart = uri.getPath(); // some validity checks if (scheme == null) { throw new IllegalArgumentException( "The scheme (hdfs://, file://, etc) is null. " + "Please specify the file system scheme explicitly in the URI."); } if (pathPart == null) { throw new IllegalArgumentException( "The path to store the checkpoint data in is null. " + "Please specify a directory path for the checkpoint data."); } if (pathPart.length() == 0 || pathPart.equals("/")) { throw new IllegalArgumentException("Cannot use the root directory for checkpoints."); } return path; } @Nullable private static Path parameterOrConfigured( @Nullable Path path, ReadableConfig config, ConfigOption<String> option) { if (path != null) { return path; } else { String configValue = config.get(option); try { return configValue == null ? null : new Path(configValue); } catch (IllegalArgumentException e) { throw new IllegalConfigurationException( "Cannot parse value for " + option.key() + " : " + configValue + " . Not a valid path."); } } } }
AbstractFileStateBackend
java
spring-projects__spring-boot
core/spring-boot/src/main/java/org/springframework/boot/context/config/ConfigDataEnvironmentContributor.java
{ "start": 2328, "end": 20254 }
class ____ implements Iterable<ConfigDataEnvironmentContributor> { private static final ConfigData.Options EMPTY_LOCATION_OPTIONS = ConfigData.Options .of(ConfigData.Option.IGNORE_IMPORTS); private final @Nullable ConfigDataLocation location; private final @Nullable ConfigDataResource resource; private final boolean fromProfileSpecificImport; private final @Nullable PropertySource<?> propertySource; private final @Nullable ConfigurationPropertySource configurationPropertySource; private final @Nullable ConfigDataProperties properties; private final ConfigData.Options configDataOptions; private final Map<ImportPhase, List<ConfigDataEnvironmentContributor>> children; private final Kind kind; private final ConversionService conversionService; /** * Create a new {@link ConfigDataEnvironmentContributor} instance. * @param kind the contributor kind * @param location the location of this contributor * @param resource the resource that contributed the data or {@code null} * @param fromProfileSpecificImport if the contributor is from a profile specific * import * @param propertySource the property source for the data or {@code null} * @param configurationPropertySource the configuration property source for the data * or {@code null} * @param properties the config data properties or {@code null} * @param configDataOptions any config data options that should apply * @param children the children of this contributor at each {@link ImportPhase} * @param conversionService the conversion service to use */ ConfigDataEnvironmentContributor(Kind kind, @Nullable ConfigDataLocation location, @Nullable ConfigDataResource resource, boolean fromProfileSpecificImport, @Nullable PropertySource<?> propertySource, @Nullable ConfigurationPropertySource configurationPropertySource, @Nullable ConfigDataProperties properties, ConfigData.@Nullable Options configDataOptions, @Nullable Map<ImportPhase, List<ConfigDataEnvironmentContributor>> children, ConversionService conversionService) { this.kind = kind; this.location = location; this.resource = resource; this.fromProfileSpecificImport = fromProfileSpecificImport; this.properties = properties; this.propertySource = propertySource; this.configurationPropertySource = configurationPropertySource; this.configDataOptions = (configDataOptions != null) ? configDataOptions : ConfigData.Options.NONE; this.children = (children != null) ? children : Collections.emptyMap(); this.conversionService = conversionService; } /** * Return the contributor kind. * @return the kind of contributor */ Kind getKind() { return this.kind; } @Nullable ConfigDataLocation getLocation() { return this.location; } /** * Return if this contributor is currently active. * @param activationContext the activation context * @return if the contributor is active */ boolean isActive(@Nullable ConfigDataActivationContext activationContext) { if (this.kind == Kind.UNBOUND_IMPORT) { return false; } return this.properties == null || this.properties.isActive(activationContext); } /** * Return the resource that contributed this instance. * @return the resource or {@code null} */ @Nullable ConfigDataResource getResource() { return this.resource; } /** * Return if the contributor is from a profile specific import. * @return if the contributor is profile specific */ boolean isFromProfileSpecificImport() { return this.fromProfileSpecificImport; } /** * Return the property source for this contributor. * @return the property source or {@code null} */ @Nullable PropertySource<?> getPropertySource() { return this.propertySource; } /** * Return the configuration property source for this contributor. * @return the configuration property source or {@code null} */ @Nullable ConfigurationPropertySource getConfigurationPropertySource() { return this.configurationPropertySource; } /** * Return if the contributor has a specific config data option. * @param option the option to check * @return {@code true} if the option is present */ boolean hasConfigDataOption(ConfigData.Option option) { return this.configDataOptions.contains(option); } ConfigDataEnvironmentContributor withoutConfigDataOption(ConfigData.Option option) { return new ConfigDataEnvironmentContributor(this.kind, this.location, this.resource, this.fromProfileSpecificImport, this.propertySource, this.configurationPropertySource, this.properties, this.configDataOptions.without(option), this.children, this.conversionService); } /** * Return any imports requested by this contributor. * @return the imports */ List<ConfigDataLocation> getImports() { return (this.properties != null) ? this.properties.getImports() : Collections.emptyList(); } /** * Return true if this contributor has imports that have not yet been processed in the * given phase. * @param importPhase the import phase * @return if there are unprocessed imports */ boolean hasUnprocessedImports(ImportPhase importPhase) { if (getImports().isEmpty()) { return false; } return !this.children.containsKey(importPhase); } /** * Return children of this contributor for the given phase. * @param importPhase the import phase * @return a list of children */ List<ConfigDataEnvironmentContributor> getChildren(ImportPhase importPhase) { return this.children.getOrDefault(importPhase, Collections.emptyList()); } /** * Returns a {@link Stream} that traverses this contributor and all its children in * priority order. * @return the stream */ Stream<ConfigDataEnvironmentContributor> stream() { return StreamSupport.stream(spliterator(), false); } /** * Returns an {@link Iterator} that traverses this contributor and all its children in * priority order. * @return the iterator * @see java.lang.Iterable#iterator() */ @Override public Iterator<ConfigDataEnvironmentContributor> iterator() { return new ContributorIterator(); } /** * Create a new {@link ConfigDataEnvironmentContributor} with bound * {@link ConfigDataProperties}. * @param contributors the contributors used for binding * @param activationContext the activation context * @return a new contributor instance */ ConfigDataEnvironmentContributor withBoundProperties(Iterable<ConfigDataEnvironmentContributor> contributors, @Nullable ConfigDataActivationContext activationContext) { ConfigurationPropertySource configurationPropertySource = getConfigurationPropertySource(); Assert.state(configurationPropertySource != null, "'configurationPropertySource' must not be null"); Iterable<ConfigurationPropertySource> sources = Collections.singleton(configurationPropertySource); PlaceholdersResolver placeholdersResolver = new ConfigDataEnvironmentContributorPlaceholdersResolver( contributors, activationContext, this, true, this.conversionService); Binder binder = new Binder(sources, placeholdersResolver, null, null, null); ConfigDataProperties properties = ConfigDataProperties.get(binder); if (properties != null && this.configDataOptions.contains(ConfigData.Option.IGNORE_IMPORTS)) { properties = properties.withoutImports(); } return new ConfigDataEnvironmentContributor(Kind.BOUND_IMPORT, this.location, this.resource, this.fromProfileSpecificImport, this.propertySource, this.configurationPropertySource, properties, this.configDataOptions, null, this.conversionService); } /** * Create a new {@link ConfigDataEnvironmentContributor} instance with a new set of * children for the given phase. * @param importPhase the import phase * @param children the new children * @return a new contributor instance */ ConfigDataEnvironmentContributor withChildren(ImportPhase importPhase, List<ConfigDataEnvironmentContributor> children) { Map<ImportPhase, List<ConfigDataEnvironmentContributor>> updatedChildren = new LinkedHashMap<>(this.children); updatedChildren.put(importPhase, children); if (importPhase == ImportPhase.AFTER_PROFILE_ACTIVATION) { moveProfileSpecific(updatedChildren); } return new ConfigDataEnvironmentContributor(this.kind, this.location, this.resource, this.fromProfileSpecificImport, this.propertySource, this.configurationPropertySource, this.properties, this.configDataOptions, updatedChildren, this.conversionService); } private void moveProfileSpecific(Map<ImportPhase, List<ConfigDataEnvironmentContributor>> children) { List<ConfigDataEnvironmentContributor> before = children.get(ImportPhase.BEFORE_PROFILE_ACTIVATION); if (!hasAnyProfileSpecificChildren(before)) { return; } List<ConfigDataEnvironmentContributor> updatedBefore = new ArrayList<>(before.size()); List<ConfigDataEnvironmentContributor> updatedAfter = new ArrayList<>(); for (ConfigDataEnvironmentContributor contributor : before) { updatedBefore.add(moveProfileSpecificChildren(contributor, updatedAfter)); } updatedAfter.addAll(children.getOrDefault(ImportPhase.AFTER_PROFILE_ACTIVATION, Collections.emptyList())); children.put(ImportPhase.BEFORE_PROFILE_ACTIVATION, updatedBefore); children.put(ImportPhase.AFTER_PROFILE_ACTIVATION, updatedAfter); } private ConfigDataEnvironmentContributor moveProfileSpecificChildren(ConfigDataEnvironmentContributor contributor, List<ConfigDataEnvironmentContributor> removed) { for (ImportPhase importPhase : ImportPhase.values()) { List<ConfigDataEnvironmentContributor> children = contributor.getChildren(importPhase); List<ConfigDataEnvironmentContributor> updatedChildren = new ArrayList<>(children.size()); for (ConfigDataEnvironmentContributor child : children) { if (child.hasConfigDataOption(ConfigData.Option.PROFILE_SPECIFIC)) { removed.add(child.withoutConfigDataOption(ConfigData.Option.PROFILE_SPECIFIC)); } else { updatedChildren.add(child); } } contributor = contributor.withChildren(importPhase, updatedChildren); } return contributor; } @Contract("null -> false") private boolean hasAnyProfileSpecificChildren(@Nullable List<ConfigDataEnvironmentContributor> contributors) { if (CollectionUtils.isEmpty(contributors)) { return false; } for (ConfigDataEnvironmentContributor contributor : contributors) { for (ImportPhase importPhase : ImportPhase.values()) { if (contributor.getChildren(importPhase) .stream() .anyMatch((child) -> child.hasConfigDataOption(ConfigData.Option.PROFILE_SPECIFIC))) { return true; } } } return false; } /** * Create a new {@link ConfigDataEnvironmentContributor} instance where an existing * child is replaced. * @param existing the existing node that should be replaced * @param replacement the replacement node that should be used instead * @return a new {@link ConfigDataEnvironmentContributor} instance */ ConfigDataEnvironmentContributor withReplacement(ConfigDataEnvironmentContributor existing, ConfigDataEnvironmentContributor replacement) { if (this == existing) { return replacement; } Map<ImportPhase, List<ConfigDataEnvironmentContributor>> updatedChildren = new LinkedHashMap<>( this.children.size()); this.children.forEach((importPhase, contributors) -> { List<ConfigDataEnvironmentContributor> updatedContributors = new ArrayList<>(contributors.size()); for (ConfigDataEnvironmentContributor contributor : contributors) { updatedContributors.add(contributor.withReplacement(existing, replacement)); } updatedChildren.put(importPhase, Collections.unmodifiableList(updatedContributors)); }); return new ConfigDataEnvironmentContributor(this.kind, this.location, this.resource, this.fromProfileSpecificImport, this.propertySource, this.configurationPropertySource, this.properties, this.configDataOptions, updatedChildren, this.conversionService); } @Override public String toString() { StringBuilder builder = new StringBuilder(); buildToString("", builder); return builder.toString(); } private void buildToString(String prefix, StringBuilder builder) { builder.append(prefix); builder.append(this.kind); builder.append(" "); builder.append(this.location); builder.append(" "); builder.append(this.resource); builder.append(" "); builder.append(this.configDataOptions); builder.append("\n"); for (ConfigDataEnvironmentContributor child : this.children.getOrDefault(ImportPhase.BEFORE_PROFILE_ACTIVATION, Collections.emptyList())) { child.buildToString(prefix + " ", builder); } for (ConfigDataEnvironmentContributor child : this.children.getOrDefault(ImportPhase.AFTER_PROFILE_ACTIVATION, Collections.emptyList())) { child.buildToString(prefix + " ", builder); } } /** * Factory method to create a {@link Kind#ROOT root} contributor. * @param contributors the immediate children of the root * @param conversionService the conversion service to use * @return a new {@link ConfigDataEnvironmentContributor} instance */ static ConfigDataEnvironmentContributor of(List<ConfigDataEnvironmentContributor> contributors, ConversionService conversionService) { Map<ImportPhase, List<ConfigDataEnvironmentContributor>> children = new LinkedHashMap<>(); children.put(ImportPhase.BEFORE_PROFILE_ACTIVATION, Collections.unmodifiableList(contributors)); return new ConfigDataEnvironmentContributor(Kind.ROOT, null, null, false, null, null, null, null, children, conversionService); } /** * Factory method to create a {@link Kind#INITIAL_IMPORT initial import} contributor. * This contributor is used to trigger initial imports of additional contributors. It * does not contribute any properties itself. * @param initialImport the initial import location (with placeholders resolved) * @param conversionService the conversion service to use * @return a new {@link ConfigDataEnvironmentContributor} instance */ static ConfigDataEnvironmentContributor ofInitialImport(ConfigDataLocation initialImport, ConversionService conversionService) { List<ConfigDataLocation> imports = Collections.singletonList(initialImport); ConfigDataProperties properties = new ConfigDataProperties(imports, null); return new ConfigDataEnvironmentContributor(Kind.INITIAL_IMPORT, null, null, false, null, null, properties, null, null, conversionService); } /** * Factory method to create a contributor that wraps an {@link Kind#EXISTING existing} * property source. The contributor provides access to existing properties, but * doesn't actively import any additional contributors. * @param propertySource the property source to wrap * @param conversionService the conversion service to use * @return a new {@link ConfigDataEnvironmentContributor} instance */ static ConfigDataEnvironmentContributor ofExisting(PropertySource<?> propertySource, ConversionService conversionService) { return new ConfigDataEnvironmentContributor(Kind.EXISTING, null, null, false, propertySource, asConfigurationPropertySource(propertySource), null, null, null, conversionService); } /** * Factory method to create an {@link Kind#UNBOUND_IMPORT unbound import} contributor. * This contributor has been actively imported from another contributor and may itself * import further contributors later. * @param location the location of this contributor * @param resource the config data resource * @param profileSpecific if the contributor is from a profile specific import * @param configData the config data * @param propertySourceIndex the index of the property source that should be used * @param conversionService the conversion service to use * @param environmentUpdateListener the environment update listener * @return a new {@link ConfigDataEnvironmentContributor} instance */ static ConfigDataEnvironmentContributor ofUnboundImport(@Nullable ConfigDataLocation location, @Nullable ConfigDataResource resource, boolean profileSpecific, ConfigData configData, int propertySourceIndex, ConversionService conversionService, ConfigDataEnvironmentUpdateListener environmentUpdateListener) { PropertySource<?> propertySource = configData.getPropertySources().get(propertySourceIndex); ConfigData.Options options = configData.getOptions(propertySource); options = environmentUpdateListener.onConfigDataOptions(configData, propertySource, options); return new ConfigDataEnvironmentContributor(Kind.UNBOUND_IMPORT, location, resource, profileSpecific, propertySource, asConfigurationPropertySource(propertySource), null, options, null, conversionService); } private static @Nullable ConfigurationPropertySource asConfigurationPropertySource( PropertySource<?> propertySource) { ConfigurationPropertySource configurationPropertySource = ConfigurationPropertySource.from(propertySource); if (configurationPropertySource != null && propertySource instanceof PropertySourceInfo propertySourceInfo) { configurationPropertySource = configurationPropertySource.withPrefix(propertySourceInfo.getPrefix()); } return configurationPropertySource; } /** * Factory method to create an {@link Kind#EMPTY_LOCATION empty location} contributor. * @param location the location of this contributor * @param profileSpecific if the contributor is from a profile specific import * @param conversionService the conversion service to use * @return a new {@link ConfigDataEnvironmentContributor} instance */ static ConfigDataEnvironmentContributor ofEmptyLocation(ConfigDataLocation location, boolean profileSpecific, ConversionService conversionService) { return new ConfigDataEnvironmentContributor(Kind.EMPTY_LOCATION, location, null, profileSpecific, null, null, null, EMPTY_LOCATION_OPTIONS, null, conversionService); } /** * The various kinds of contributor. */
ConfigDataEnvironmentContributor
java
spring-projects__spring-framework
spring-websocket/src/main/java/org/springframework/web/socket/handler/WebSocketHandlerDecoratorFactory.java
{ "start": 1111, "end": 1422 }
interface ____ { /** * Decorate the given WebSocketHandler. * @param handler the handler to be decorated. * @return the same handler or the handler wrapped with a subclass of * {@code WebSocketHandlerDecorator} */ WebSocketHandler decorate(WebSocketHandler handler); }
WebSocketHandlerDecoratorFactory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/converted/converter/ExplicitJavaTypeDescriptorTest.java
{ "start": 8004, "end": 8469 }
class ____ implements AttributeConverter<PseudoMutableState,String> { @Override public String convertToDatabaseColumn(PseudoMutableState attribute) { pseudoMutableToDatabaseCallCount++; return attribute == null ? null : attribute.getState(); } @Override public PseudoMutableState convertToEntityAttribute(String dbData) { pseudoMutableToDomainCallCount++; return new PseudoMutableState( dbData ); } } public static
PseudoMutableConverterImpl
java
apache__flink
flink-examples/flink-examples-streaming/src/main/java/org/apache/flink/streaming/examples/datagen/DataGeneratorPerCheckpoint.java
{ "start": 1447, "end": 2522 }
class ____ { public static void main(String[] args) throws Exception { final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.enableCheckpointing(3000); env.setParallelism(1); final String[] elements = new String[] {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}; final int size = elements.length; final GeneratorFunction<Long, String> generatorFunction = index -> elements[(int) (index % size)]; final DataGeneratorSource<String> generatorSource = new DataGeneratorSource<>( generatorFunction, Long.MAX_VALUE, RateLimiterStrategy.perCheckpoint(size), Types.STRING); final DataStreamSource<String> streamSource = env.fromSource(generatorSource, WatermarkStrategy.noWatermarks(), "Data Generator"); streamSource.print(); env.execute("Data Generator Source Example"); } }
DataGeneratorPerCheckpoint
java
spring-projects__spring-boot
module/spring-boot-web-server/src/test/java/org/springframework/boot/web/server/servlet/context/XmlServletWebServerApplicationContextTests.java
{ "start": 1130, "end": 2862 }
class ____ { private static final String PATH = XmlServletWebServerApplicationContextTests.class.getPackage() .getName() .replace('.', '/') + "/"; private static final String FILE = "exampleEmbeddedWebApplicationConfiguration.xml"; private @Nullable XmlServletWebServerApplicationContext context; @Test void createFromResource() { this.context = new XmlServletWebServerApplicationContext(new ClassPathResource(FILE, getClass())); verifyContext(); } @Test void createFromResourceLocation() { this.context = new XmlServletWebServerApplicationContext(PATH + FILE); verifyContext(); } @Test void createFromRelativeResourceLocation() { this.context = new XmlServletWebServerApplicationContext(getClass(), FILE); verifyContext(); } @Test void loadAndRefreshFromResource() { this.context = new XmlServletWebServerApplicationContext(); this.context.load(new ClassPathResource(FILE, getClass())); this.context.refresh(); verifyContext(); } @Test void loadAndRefreshFromResourceLocation() { this.context = new XmlServletWebServerApplicationContext(); this.context.load(PATH + FILE); this.context.refresh(); verifyContext(); } @Test void loadAndRefreshFromRelativeResourceLocation() { this.context = new XmlServletWebServerApplicationContext(); this.context.load(getClass(), FILE); this.context.refresh(); verifyContext(); } private void verifyContext() { assertThat(this.context).isNotNull(); MockServletWebServerFactory factory = this.context.getBean(MockServletWebServerFactory.class); Servlet servlet = this.context.getBean(Servlet.class); then(factory.getServletContext()).should().addServlet("servlet", servlet); } }
XmlServletWebServerApplicationContextTests
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/reactive/EnableWebFluxSecurityTests.java
{ "start": 16064, "end": 16174 }
class ____ { Child() { } } @EnableWebFluxSecurity @Configuration(proxyBeanMethods = false) static
Child
java
apache__camel
components/camel-pqc/src/main/java/org/apache/camel/component/pqc/lifecycle/KeyFormatConverter.java
{ "start": 1116, "end": 1208 }
class ____ converting PQC keys between different formats (PEM, DER, PKCS8, X509). */ public
for
java
quarkusio__quarkus
extensions/grpc/deployment/src/test/java/io/quarkus/grpc/client/ClientWithoutConfigInjectionTest.java
{ "start": 787, "end": 2340 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addClasses(MutinyGreeterGrpc.class, GreeterGrpc.class, MutinyGreeterGrpc.MutinyGreeterStub.class, HelloService.class, HelloRequest.class, HelloReply.class, HelloReplyOrBuilder.class, HelloRequestOrBuilder.class)); private static final Duration TIMEOUT = Duration.ofSeconds(5); @GrpcClient GreeterGrpc.GreeterBlockingStub client; @GrpcClient MutinyGreeterGrpc.MutinyGreeterStub mutinyClient; @Test public void testHelloWithBlockingClient() { HelloReply reply = client.sayHello(HelloRequest.newBuilder().setName("neo").build()); assertThat(reply.getMessage()).isEqualTo("Hello neo"); reply = client.wEIRD(HelloRequest.newBuilder().setName("neo").build()); assertThat(reply.getMessage()).isEqualTo("Hello neo"); } @Test public void testHelloWithMutinyClient() { Uni<HelloReply> reply = mutinyClient .sayHello(HelloRequest.newBuilder().setName("neo").build()); assertThat(reply.await().atMost(TIMEOUT).getMessage()).isEqualTo("Hello neo"); reply = mutinyClient .wEIRD(HelloRequest.newBuilder().setName("neo").build()); assertThat(reply.await().atMost(TIMEOUT).getMessage()).isEqualTo("Hello neo"); } }
ClientWithoutConfigInjectionTest
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/annotation/InjectAnnotationBeanPostProcessorTests.java
{ "start": 38702, "end": 39072 }
class ____ { private Provider<?> testBeanFactory; @Inject @Named("testBean") public void setTestBeanFactory(Provider<?> testBeanFactory) { this.testBeanFactory = testBeanFactory; } public TestBean getTestBean() { return (TestBean) this.testBeanFactory.get(); } } @SuppressWarnings("serial") public static
ObjectFactoryQualifierMethodInjectionBean
java
elastic__elasticsearch
x-pack/plugin/searchable-snapshots/src/test/java/org/elasticsearch/xpack/searchablesnapshots/cache/common/TestUtils.java
{ "start": 3077, "end": 8477 }
class ____ { private TestUtils() {} public static SortedSet<ByteRange> randomPopulateAndReads(final CacheFile cacheFile) { return randomPopulateAndReads(cacheFile, (fileChannel, aLong, aLong2) -> {}); } public static SortedSet<ByteRange> randomPopulateAndReads(CacheFile cacheFile, TriConsumer<FileChannel, Long, Long> consumer) { final SortedSet<ByteRange> ranges = synchronizedNavigableSet(new TreeSet<>()); final List<Future<Integer>> futures = new ArrayList<>(); final DeterministicTaskQueue deterministicTaskQueue = new DeterministicTaskQueue(); for (int i = 0; i < between(0, 10); i++) { final long start = randomLongBetween(0L, Math.max(0L, cacheFile.getLength() - 1L)); final long end = randomLongBetween(Math.min(start + 1L, cacheFile.getLength()), cacheFile.getLength()); final ByteRange range = ByteRange.of(start, end); futures.add( cacheFile.populateAndRead(range, range, channel -> Math.toIntExact(end - start), (channel, from, to, progressUpdater) -> { consumer.apply(channel, from, to); ranges.add(ByteRange.of(from, to)); progressUpdater.accept(to); }, deterministicTaskQueue.getThreadPool().generic()) ); } deterministicTaskQueue.runAllRunnableTasks(); assertTrue(futures.stream().allMatch(Future::isDone)); return mergeContiguousRanges(ranges); } public static void assertCacheFileEquals(CacheFile expected, CacheFile actual) { MatcherAssert.assertThat(actual.getLength(), equalTo(expected.getLength())); MatcherAssert.assertThat(actual.getFile(), equalTo(expected.getFile())); MatcherAssert.assertThat(actual.getCacheKey(), equalTo(expected.getCacheKey())); MatcherAssert.assertThat(actual.getCompletedRanges(), equalTo(expected.getCompletedRanges())); } public static long sumOfCompletedRangesLengths(CacheFile cacheFile) { return cacheFile.getCompletedRanges().stream().mapToLong(ByteRange::length).sum(); } public static void assertCounter(IndexInputStats.Counter counter, long total, long count, long min, long max) { assertThat(counter.total(), equalTo(total)); assertThat(counter.count(), equalTo(count)); assertThat(counter.min(), equalTo(min)); assertThat(counter.max(), equalTo(max)); } /** * A {@link BlobContainer} that can read a single in-memory blob. * Any attempt to read a different blob will throw a {@link FileNotFoundException} */ public static BlobContainer singleBlobContainer(final String blobName, final byte[] blobContent) { return new MostlyUnimplementedFakeBlobContainer() { @Override public InputStream readBlob(OperationPurpose purpose, String name, long position, long length) throws IOException { if (blobName.equals(name) == false) { throw new FileNotFoundException("Blob not found: " + name); } return Streams.limitStream( new ByteArrayInputStream(blobContent, toIntBytes(position), blobContent.length - toIntBytes(position)), length ); } }; } public static BlobContainer singleSplitBlobContainer(final String blobName, final byte[] blobContent, final int partSize) { if (partSize >= blobContent.length) { return singleBlobContainer(blobName, blobContent); } else { final String prefix = blobName + ".part"; return new MostlyUnimplementedFakeBlobContainer() { @Override public InputStream readBlob(OperationPurpose purpose, String name, long position, long length) throws IOException { if (name.startsWith(prefix) == false) { throw new FileNotFoundException("Blob not found: " + name); } assert position + length <= partSize : "cannot read [" + position + "-" + (position + length) + "] from array part of length [" + partSize + "]"; final int partNumber = Integer.parseInt(name.substring(prefix.length())); final int positionInBlob = toIntBytes(position) + partSize * partNumber; assert positionInBlob + length <= blobContent.length : "cannot read [" + positionInBlob + "-" + (positionInBlob + length) + "] from array of length [" + blobContent.length + "]"; return Streams.limitStream( new ByteArrayInputStream(blobContent, positionInBlob, blobContent.length - positionInBlob), length ); } }; } } public static ByteSizeValue pageAligned(ByteSizeValue val) { final long remainder = val.getBytes() % SharedBytes.PAGE_SIZE; if (remainder != 0L) { return ByteSizeValue.ofBytes(val.getBytes() + SharedBytes.PAGE_SIZE - remainder); } return val; } private static
TestUtils
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/TestContainer.java
{ "start": 6417, "end": 43698 }
class ____ { final NodeManagerMetrics metrics = NodeManagerMetrics.create(); final Configuration conf = new YarnConfiguration(); final String FAKE_LOCALIZATION_ERROR = "Fake localization error"; /** * Verify correct container request events sent to localizer. */ @Test public void testLocalizationRequest() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(7, 314159265358979L, 4344, "yak"); assertEquals(ContainerState.NEW, wc.c.getContainerState()); wc.initContainer(); // Verify request for public/private resources to localizer ResourcesRequestedMatcher matchesReq = new ResourcesRequestedMatcher(wc.localResources, EnumSet.of( LocalResourceVisibility.PUBLIC, LocalResourceVisibility.PRIVATE, LocalResourceVisibility.APPLICATION)); verify(wc.localizerBus).handle(argThat(matchesReq)); assertEquals(ContainerState.LOCALIZING, wc.c.getContainerState()); } finally { if (wc != null) { wc.finished(); } } } /** * Verify container launch when all resources already cached. */ @Test public void testLocalizationLaunch() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(8, 314159265358979L, 4344, "yak"); assertEquals(ContainerState.NEW, wc.c.getContainerState()); wc.initContainer(); Map<Path, List<String>> localPaths = wc.localizeResources(); // all resources should be localized assertEquals(ContainerState.SCHEDULED, wc.c.getContainerState()); assertNotNull(wc.c.getLocalizedResources()); for (Entry<Path, List<String>> loc : wc.c.getLocalizedResources() .entrySet()) { assertEquals(localPaths.remove(loc.getKey()), loc.getValue()); } assertTrue(localPaths.isEmpty()); final WrappedContainer wcf = wc; // verify container launch ArgumentMatcher<ContainersLauncherEvent> matchesContainerLaunch = event -> wcf.c == event.getContainer(); verify(wc.launcherBus).handle(argThat(matchesContainerLaunch)); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testExternalKill() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(13, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); int running = metrics.getRunningContainers(); wc.launchContainer(); assertEquals(running + 1, metrics.getRunningContainers()); reset(wc.localizerBus); wc.containerKilledOnRequest(); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); int failed = metrics.getFailedContainers(); wc.containerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(failed + 1, metrics.getFailedContainers()); assertEquals(running, metrics.getRunningContainers()); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testDockerContainerExternalKill() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(13, 314159265358979L, 4344, "yak"); wc.setupDockerContainerEnv(); wc.initContainer(); wc.localizeResources(); int running = metrics.getRunningContainers(); wc.launchContainer(); assertEquals(running + 1, metrics.getRunningContainers()); reset(wc.localizerBus); wc.containerKilledOnRequest(); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); int failed = metrics.getFailedContainers(); wc.dockerContainerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(failed + 1, metrics.getFailedContainers()); assertEquals(running, metrics.getRunningContainers()); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testContainerPauseAndResume() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(13, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); int running = metrics.getRunningContainers(); int paused = metrics.getPausedContainers(); wc.launchContainer(); assertEquals(running + 1, metrics.getRunningContainers()); reset(wc.localizerBus); wc.pauseContainer(); assertEquals(ContainerState.PAUSED, wc.c.getContainerState()); assertEquals(paused + 1, metrics.getPausedContainers()); wc.resumeContainer(); assertEquals(paused, metrics.getPausedContainers()); assertEquals(ContainerState.RUNNING, wc.c.getContainerState()); wc.containerKilledOnRequest(); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); int failed = metrics.getFailedContainers(); wc.containerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(failed + 1, metrics.getFailedContainers()); assertEquals(running, metrics.getRunningContainers()); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testCleanupOnFailure() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(10, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); wc.launchContainer(); reset(wc.localizerBus); wc.containerFailed(ExitCode.FORCE_KILLED.getExitCode()); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testDockerContainerCleanupOnFailure() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(10, 314159265358979L, 4344, "yak"); wc.setupDockerContainerEnv(); wc.initContainer(); wc.localizeResources(); wc.launchContainer(); reset(wc.localizerBus); wc.containerFailed(ExitCode.FORCE_KILLED.getExitCode()); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); wc.dockerContainerResourcesCleanup(); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testCleanupOnSuccess() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(11, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); int running = metrics.getRunningContainers(); wc.launchContainer(); assertEquals(running + 1, metrics.getRunningContainers()); reset(wc.localizerBus); wc.containerSuccessful(); assertEquals(ContainerState.EXITED_WITH_SUCCESS, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); int completed = metrics.getCompletedContainers(); wc.containerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(completed + 1, metrics.getCompletedContainers()); assertEquals(running, metrics.getRunningContainers()); ContainerEventType e1 = wc.initStateToEvent.get(ContainerState.NEW); ContainerState s2 = wc.eventToFinalState.get(e1); ContainerEventType e2 = wc.initStateToEvent.get(s2); ContainerState s3 = wc.eventToFinalState.get(e2); ContainerEventType e3 = wc.initStateToEvent.get(s3); ContainerState s4 = wc.eventToFinalState.get(e3); ContainerEventType e4 = wc.initStateToEvent.get(s4); ContainerState s5 = wc.eventToFinalState.get(e4); ContainerEventType e5 = wc.initStateToEvent.get(s5); ContainerState s6 = wc.eventToFinalState.get(e5); assertEquals(ContainerState.LOCALIZING, s2); assertEquals(ContainerState.SCHEDULED, s3); assertEquals(ContainerState.RUNNING, s4); assertEquals(ContainerState.EXITED_WITH_SUCCESS, s5); assertEquals(ContainerState.DONE, s6); assertEquals(ContainerEventType.INIT_CONTAINER, e1); assertEquals(ContainerEventType.RESOURCE_LOCALIZED, e2); assertEquals(ContainerEventType.CONTAINER_LAUNCHED, e3); assertEquals(ContainerEventType.CONTAINER_EXITED_WITH_SUCCESS, e4); assertEquals(ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP, e5); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testDockerContainerCleanupOnSuccess() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(11, 314159265358979L, 4344, "yak"); wc.setupDockerContainerEnv(); wc.initContainer(); wc.localizeResources(); int running = metrics.getRunningContainers(); wc.launchContainer(); assertEquals(running + 1, metrics.getRunningContainers()); reset(wc.localizerBus); wc.containerSuccessful(); assertEquals(ContainerState.EXITED_WITH_SUCCESS, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); int completed = metrics.getCompletedContainers(); wc.dockerContainerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(completed + 1, metrics.getCompletedContainers()); assertEquals(running, metrics.getRunningContainers()); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testInitWhileDone() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(6, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); wc.launchContainer(); reset(wc.localizerBus); wc.containerSuccessful(); wc.containerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); verifyOutofBandHeartBeat(wc); assertNull(wc.c.getLocalizedResources()); // Now in DONE, issue INIT wc.initContainer(); // Verify still in DONE assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testDockerContainerInitWhileDone() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(6, 314159265358979L, 4344, "yak"); wc.setupDockerContainerEnv(); wc.initContainer(); wc.localizeResources(); wc.launchContainer(); reset(wc.localizerBus); wc.containerSuccessful(); wc.dockerContainerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); verifyOutofBandHeartBeat(wc); assertNull(wc.c.getLocalizedResources()); // Now in DONE, issue INIT wc.initContainer(); // Verify still in DONE assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testLocalizationFailureAtDone() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(6, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); wc.launchContainer(); reset(wc.localizerBus); wc.containerSuccessful(); wc.containerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); verifyOutofBandHeartBeat(wc); assertNull(wc.c.getLocalizedResources()); // Now in DONE, issue RESOURCE_FAILED as done by LocalizeRunner wc.resourceFailedContainer(); // Verify still in DONE assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testDockerContainerLocalizationFailureAtDone() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(6, 314159265358979L, 4344, "yak"); wc.setupDockerContainerEnv(); wc.initContainer(); wc.localizeResources(); wc.launchContainer(); reset(wc.localizerBus); wc.containerSuccessful(); wc.dockerContainerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); verifyOutofBandHeartBeat(wc); assertNull(wc.c.getLocalizedResources()); // Now in DONE, issue RESOURCE_FAILED as done by LocalizeRunner wc.resourceFailedContainer(); // Verify still in DONE assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") public void testLocalizationFailureWhileRunning() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(6, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); wc.launchContainer(); reset(wc.localizerBus); assertEquals(ContainerState.RUNNING, wc.c.getContainerState()); // Now in RUNNING, handle ContainerResourceFailedEvent, cause NPE before wc.handleContainerResourceFailedEvent(); } finally { if (wc != null) { wc.finished(); } } } @Test @SuppressWarnings("unchecked") // mocked generic public void testCleanupOnKillRequest() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(12, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); wc.launchContainer(); reset(wc.localizerBus); wc.killContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); wc.containerKilledOnRequest(); verifyCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test public void testKillOnNew() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(13, 314159265358979L, 4344, "yak"); assertEquals(ContainerState.NEW, wc.c.getContainerState()); int killed = metrics.getKilledContainers(); wc.killContainer(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); verifyOutofBandHeartBeat(wc); assertEquals(ContainerExitStatus.KILLED_BY_RESOURCEMANAGER, wc.c.cloneAndGetContainerStatus().getExitStatus()); assertTrue(wc.c.cloneAndGetContainerStatus().getDiagnostics() .contains("KillRequest")); assertEquals(killed + 1, metrics.getKilledContainers()); // check container metrics is generated. ContainerMetrics containerMetrics = ContainerMetrics.forContainer(wc.cId, 1, 5000); assertEquals(ContainerExitStatus.KILLED_BY_RESOURCEMANAGER, containerMetrics.exitCode.value()); assertTrue(containerMetrics.startTime.value() > 0); assertTrue(containerMetrics.finishTime.value() >= containerMetrics.startTime.value()); assertEquals(ContainerEventType.KILL_CONTAINER, wc.initStateToEvent.get(ContainerState.NEW)); assertEquals(ContainerState.DONE, wc.eventToFinalState.get(ContainerEventType.KILL_CONTAINER)); } finally { if (wc != null) { wc.finished(); } } } @Test public void testKillOnLocalizing() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(14, 314159265358979L, 4344, "yak"); wc.initContainer(); assertEquals(ContainerState.LOCALIZING, wc.c.getContainerState()); wc.killContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); assertEquals(ContainerExitStatus.KILLED_BY_RESOURCEMANAGER, wc.c.cloneAndGetContainerStatus().getExitStatus()); assertTrue(wc.c.cloneAndGetContainerStatus().getDiagnostics() .contains("KillRequest")); int killed = metrics.getKilledContainers(); wc.containerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(killed + 1, metrics.getKilledContainers()); } finally { if (wc != null) { wc.finished(); } } } @Test public void testKillOnLocalizationFailed() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(15, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.failLocalizeResources(wc.getLocalResourceCount()); assertEquals(ContainerState.LOCALIZATION_FAILED, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); wc.killContainer(); assertEquals(ContainerState.LOCALIZATION_FAILED, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); int failed = metrics.getFailedContainers(); wc.containerResourcesCleanup(); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(failed + 1, metrics.getFailedContainers()); } finally { if (wc != null) { wc.finished(); } } } @Test public void testKillOnLocalizedWhenContainerNotLaunchedContainerKilled() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(17, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); assertEquals(ContainerState.SCHEDULED, wc.c.getContainerState()); ContainerLaunch launcher = wc.launcher.running.get(wc.c.getContainerId()); wc.killContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); // check that container cleanup hasn't started at this point. LocalizationCleanupMatcher cleanupResources = new LocalizationCleanupMatcher(wc.c); verify(wc.localizerBus, times(0)).handle(argThat(cleanupResources)); // check if containerlauncher cleans up the container launch. verify(wc.launcherBus) .handle(refEq(new ContainersLauncherEvent(wc.c, ContainersLauncherEventType.CLEANUP_CONTAINER), "timestamp")); launcher.call(); wc.drainDispatcherEvents(); assertEquals(ContainerState.CONTAINER_CLEANEDUP_AFTER_KILL, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); int killed = metrics.getKilledContainers(); wc.c.handle(new ContainerEvent(wc.c.getContainerId(), ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP)); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(killed + 1, metrics.getKilledContainers()); assertEquals(0, metrics.getRunningContainers()); assertEquals(0, wc.launcher.running.size()); } finally { if (wc != null) { wc.finished(); } } } @Test public void testDockerKillOnLocalizedWhenContainerNotLaunchedContainerKilled() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(17, 314159265358979L, 4344, "yak"); wc.setupDockerContainerEnv(); wc.initContainer(); wc.localizeResources(); assertEquals(ContainerState.SCHEDULED, wc.c.getContainerState()); ContainerLaunch launcher = wc.launcher.running.get(wc.c.getContainerId()); wc.killContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); launcher.call(); wc.drainDispatcherEvents(); assertEquals(ContainerState.CONTAINER_CLEANEDUP_AFTER_KILL, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyDockerContainerCleanupCall(wc); int killed = metrics.getKilledContainers(); wc.c.handle(new ContainerEvent(wc.c.getContainerId(), ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP)); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(killed + 1, metrics.getKilledContainers()); assertEquals(0, metrics.getRunningContainers()); } finally { if (wc != null) { wc.finished(); } } } @Test public void testKillOnLocalizedWhenContainerNotLaunchedContainerSuccess() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(17, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); assertEquals(ContainerState.SCHEDULED, wc.c.getContainerState()); wc.killContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); wc.containerSuccessful(); wc.drainDispatcherEvents(); assertEquals(ContainerState.EXITED_WITH_SUCCESS, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); wc.c.handle(new ContainerEvent(wc.c.getContainerId(), ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP)); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(0, metrics.getRunningContainers()); } finally { if (wc != null) { wc.finished(); } } } @Test public void testKillOnLocalizedWhenContainerNotLaunchedContainerFailure() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(17, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); assertEquals(ContainerState.SCHEDULED, wc.c.getContainerState()); wc.killContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); wc.containerFailed(ExitCode.FORCE_KILLED.getExitCode()); wc.drainDispatcherEvents(); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); wc.c.handle(new ContainerEvent(wc.c.getContainerId(), ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP)); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(0, metrics.getRunningContainers()); } finally { if (wc != null) { wc.finished(); } } } @Test public void testDockerKillOnLocalizedContainerNotLaunchedContainerFailure() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(17, 314159265358979L, 4344, "yak"); wc.setupDockerContainerEnv(); wc.initContainer(); wc.localizeResources(); assertEquals(ContainerState.SCHEDULED, wc.c.getContainerState()); wc.killContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); wc.containerFailed(ExitCode.FORCE_KILLED.getExitCode()); wc.drainDispatcherEvents(); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyDockerContainerCleanupCall(wc); wc.c.handle(new ContainerEvent(wc.c.getContainerId(), ContainerEventType.CONTAINER_RESOURCES_CLEANEDUP)); assertEquals(ContainerState.DONE, wc.c.getContainerState()); assertEquals(0, metrics.getRunningContainers()); } finally { if (wc != null) { wc.finished(); } } } @Test public void testKillOnLocalizedWhenContainerLaunched() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(17, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); assertEquals(ContainerState.SCHEDULED, wc.c.getContainerState()); ContainerLaunch launcher = wc.launcher.running.get(wc.c.getContainerId()); launcher.call(); wc.drainDispatcherEvents(); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); wc.killContainer(); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test public void testDockerKillOnLocalizedWhenContainerLaunched() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(17, 314159265358979L, 4344, "yak"); wc.setupDockerContainerEnv(); wc.initContainer(); wc.localizeResources(); assertEquals(ContainerState.SCHEDULED, wc.c.getContainerState()); ContainerLaunch launcher = wc.launcher.running.get(wc.c.getContainerId()); launcher.call(); wc.drainDispatcherEvents(); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); wc.killContainer(); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyDockerContainerCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test public void testResourceLocalizedOnLocalizationFailed() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(16, 314159265358979L, 4344, "yak"); wc.initContainer(); int failCount = wc.getLocalResourceCount()/2; if (failCount == 0) { failCount = 1; } wc.failLocalizeResources(failCount); assertEquals(ContainerState.LOCALIZATION_FAILED, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); wc.localizeResourcesFromInvalidState(failCount); assertEquals(ContainerState.LOCALIZATION_FAILED, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); assertTrue(wc.getDiagnostics().contains(FAKE_LOCALIZATION_ERROR)); } finally { if (wc != null) { wc.finished(); } } } @Test public void testResourceFailedOnLocalizationFailed() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(16, 314159265358979L, 4344, "yak"); wc.initContainer(); Iterator<String> lRsrcKeys = wc.localResources.keySet().iterator(); String key1 = lRsrcKeys.next(); String key2 = lRsrcKeys.next(); wc.failLocalizeSpecificResource(key1); assertEquals(ContainerState.LOCALIZATION_FAILED, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); wc.failLocalizeSpecificResource(key2); assertEquals(ContainerState.LOCALIZATION_FAILED, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test public void testResourceFailedOnKilling() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(16, 314159265358979L, 4344, "yak"); wc.initContainer(); Iterator<String> lRsrcKeys = wc.localResources.keySet().iterator(); String key1 = lRsrcKeys.next(); wc.killContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); wc.failLocalizeSpecificResource(key1); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); verifyCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } /** * Verify serviceData correctly sent. */ @Test public void testServiceData() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(9, 314159265358979L, 4344, "yak", false, true); assertEquals(ContainerState.NEW, wc.c.getContainerState()); wc.initContainer(); for (final Map.Entry<String,ByteBuffer> e : wc.serviceData.entrySet()) { ArgumentMatcher<AuxServicesEvent> matchesServiceReq = evt -> e.getKey().equals(evt.getServiceID()) && 0 == e.getValue().compareTo(evt.getServiceData()); verify(wc.auxBus).handle(argThat(matchesServiceReq)); } final WrappedContainer wcf = wc; // verify launch on empty resource request ArgumentMatcher<ContainersLauncherEvent> matchesLaunchReq = evt -> evt.getType() == ContainersLauncherEventType.LAUNCH_CONTAINER && wcf.cId.equals(evt.getContainer().getContainerId()); verify(wc.launcherBus).handle(argThat(matchesLaunchReq)); } finally { if (wc != null) { wc.finished(); } } } @Test public void testLaunchAfterKillRequest() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(14, 314159265358979L, 4344, "yak"); wc.initContainer(); wc.localizeResources(); wc.killContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); wc.launchContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); wc.containerKilledOnRequest(); verifyCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test public void testDockerContainerLaunchAfterKillRequest() throws Exception { WrappedContainer wc = null; try { wc = new WrappedContainer(14, 314159265358979L, 4344, "yak"); wc.setupDockerContainerEnv(); wc.initContainer(); wc.localizeResources(); wc.killContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); wc.launchContainer(); assertEquals(ContainerState.KILLING, wc.c.getContainerState()); assertNull(wc.c.getLocalizedResources()); wc.containerKilledOnRequest(); verifyDockerContainerCleanupCall(wc); } finally { if (wc != null) { wc.finished(); } } } @Test public void testContainerRetry() throws Exception{ ContainerRetryContext containerRetryContext1 = ContainerRetryContext .newInstance(ContainerRetryPolicy.NEVER_RETRY, null, 3, 0); testContainerRetry(containerRetryContext1, 2, 0); ContainerRetryContext containerRetryContext2 = ContainerRetryContext .newInstance(ContainerRetryPolicy.RETRY_ON_ALL_ERRORS, null, 3, 0); testContainerRetry(containerRetryContext2, 2, 3); ContainerRetryContext containerRetryContext3 = ContainerRetryContext .newInstance(ContainerRetryPolicy.RETRY_ON_ALL_ERRORS, null, 3, 0); // If exit code is 0, it will not retry testContainerRetry(containerRetryContext3, 0, 0); ContainerRetryContext containerRetryContext4 = ContainerRetryContext .newInstance( ContainerRetryPolicy.RETRY_ON_SPECIFIC_ERROR_CODES, null, 3, 0); testContainerRetry(containerRetryContext4, 2, 0); HashSet<Integer> errorCodes = new HashSet<>(); errorCodes.add(2); errorCodes.add(6); ContainerRetryContext containerRetryContext5 = ContainerRetryContext .newInstance(ContainerRetryPolicy.RETRY_ON_SPECIFIC_ERROR_CODES, errorCodes, 3, 0); testContainerRetry(containerRetryContext5, 2, 3); HashSet<Integer> errorCodes2 = new HashSet<>(); errorCodes.add(143); ContainerRetryContext containerRetryContext6 = ContainerRetryContext .newInstance(ContainerRetryPolicy.RETRY_ON_SPECIFIC_ERROR_CODES, errorCodes2, 3, 0); // If exit code is 143(SIGTERM), it will not retry even it is in errorCodes. testContainerRetry(containerRetryContext6, 143, 0); } private void testContainerRetry(ContainerRetryContext containerRetryContext, int exitCode, int expectedRetries) throws Exception{ WrappedContainer wc = null; try { int retryTimes = 0; wc = new WrappedContainer(24, 314159265358979L, 4344, "yak", containerRetryContext); wc.initContainer(); wc.localizeResources(); wc.launchContainer(); while (true) { wc.containerFailed(exitCode); if (wc.c.getContainerState() == ContainerState.RUNNING) { retryTimes ++; } else { break; } } assertEquals(expectedRetries, retryTimes); } finally { if (wc != null) { wc.finished(); } } } @Test public void testContainerRestartInterval() throws IOException { conf.setInt(YarnConfiguration.NM_CONTAINER_RETRY_MINIMUM_INTERVAL_MS, 2000); ContainerRetryContext containerRetryContext1 = ContainerRetryContext .newInstance(ContainerRetryPolicy.NEVER_RETRY, null, 3, 0); testContainerRestartInterval(containerRetryContext1, 0); ContainerRetryContext containerRetryContext2 = ContainerRetryContext .newInstance(ContainerRetryPolicy.RETRY_ON_ALL_ERRORS, null, 3, 0); testContainerRestartInterval(containerRetryContext2, 2000); ContainerRetryContext containerRetryContext3 = ContainerRetryContext .newInstance(ContainerRetryPolicy.RETRY_ON_ALL_ERRORS, null, 3, 4000); testContainerRestartInterval(containerRetryContext3, 4000); } private void testContainerRestartInterval( ContainerRetryContext containerRetryContext, int expectedRestartInterval) throws IOException { WrappedContainer wc = null; try { wc = new WrappedContainer(25, 314159265358980L, 4345, "yak", containerRetryContext); assertEquals( ((ContainerImpl)wc.c).getContainerRetryContext().getRetryInterval(), expectedRestartInterval); } finally { if (wc != null) { wc.finished(); } } } @Test public void testContainerRetryFailureValidityInterval() throws Exception { ContainerRetryContext containerRetryContext = ContainerRetryContext .newInstance(ContainerRetryPolicy.RETRY_ON_ALL_ERRORS, null, 1, 0, 10); WrappedContainer wc = null; try { wc = new WrappedContainer(25, 314159265358980L, 4200, "test", containerRetryContext); ControlledClock clock = new ControlledClock(); wc.getRetryPolicy().setClock(clock); wc.initContainer(); wc.localizeResources(); wc.launchContainer(); wc.containerFailed(12); assertEquals(ContainerState.RUNNING, wc.c.getContainerState()); clock.setTime(20); wc.containerFailed(12); assertEquals(ContainerState.RUNNING, wc.c.getContainerState()); clock.setTime(40); wc.containerFailed(12); assertEquals(ContainerState.RUNNING, wc.c.getContainerState()); clock.setTime(45); wc.containerFailed(12); assertEquals(ContainerState.EXITED_WITH_FAILURE, wc.c.getContainerState()); } finally { if (wc != null) { wc.finished(); } } } private void verifyCleanupCall(WrappedContainer wc) throws Exception { ResourcesReleasedMatcher matchesReq = new ResourcesReleasedMatcher(wc.localResources, EnumSet.of( LocalResourceVisibility.PUBLIC, LocalResourceVisibility.PRIVATE, LocalResourceVisibility.APPLICATION), wc.c); verify(wc.localizerBus, atLeastOnce()).handle(argThat(matchesReq)); } private void verifyOutofBandHeartBeat(WrappedContainer wc) { verify(wc.context.getNodeStatusUpdater()).sendOutofBandHeartBeat(); } private void verifyDockerContainerCleanupCall(WrappedContainer wc) throws Exception { // check if containerlauncher cleans up the container launch. verify(wc.launcherBus) .handle(refEq(new ContainersLauncherEvent(wc.c, ContainersLauncherEventType.CLEANUP_CONTAINER), "timestamp")); } // Argument matcher for matching container localization cleanup event. private static
TestContainer
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resteasy/async/filters/AsyncResponseFilter1.java
{ "start": 176, "end": 312 }
class ____ extends AsyncResponseFilter { public AsyncResponseFilter1() { super("ResponseFilter1"); } }
AsyncResponseFilter1
java
spring-projects__spring-boot
core/spring-boot-docker-compose/src/main/java/org/springframework/boot/docker/compose/core/DockerCliCommand.java
{ "start": 6279, "end": 6763 }
class ____ extends DockerCliCommand<None> { ComposeStart(LogLevel logLevel, List<String> arguments) { super(Type.DOCKER_COMPOSE, logLevel, None.class, false, getCommand(arguments)); } private static String[] getCommand(List<String> arguments) { List<String> command = new ArrayList<>(); command.add("start"); command.addAll(arguments); return command.toArray(String[]::new); } } /** * The {@code docker compose stop} command. */ static final
ComposeStart
java
quarkusio__quarkus
extensions/security/deployment/src/test/java/io/quarkus/security/test/cdi/CDIAccessDenyUnannotatedTest.java
{ "start": 1299, "end": 4140 }
class ____ { @Inject @Named(BeanWithSecurityAnnotations.NAME) BeanWithSecurityAnnotations beanWithSecurityAnnotations; @Inject BeanWithSecurityAnnotationsSubBean securityAnnoSubBean; @Inject PermitAllSubBean permitAllSubBean; @Inject PermitAllBean permitAllBean; @Inject BeanWithNoSecurityAnnotations noAnnoBean; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(BeanWithNoSecurityAnnotations.class, BeanWithSecurityAnnotations.class, BeanWithSecurityAnnotationsSubBean.class, PermitAllBean.class, PermitAllSubBean.class, SecurityTestUtils.class, IdentityMock.class) .addAsResource("application-deny-unannotated.properties", "application.properties")); @Test public void shouldDenyUnannotated() { assertFailureFor(() -> beanWithSecurityAnnotations.unannotated(), UnauthorizedException.class, ANONYMOUS); assertFailureFor(() -> beanWithSecurityAnnotations.unannotated(), ForbiddenException.class, USER, ADMIN); } @Test public void shouldAllowPermitAll() { assertSuccess(() -> beanWithSecurityAnnotations.allowed(), "allowed", ANONYMOUS, USER, ADMIN); } @Test public void shouldRestrict() { assertFailureFor(() -> beanWithSecurityAnnotations.restricted(), UnauthorizedException.class, ANONYMOUS); assertFailureFor(() -> beanWithSecurityAnnotations.restricted(), ForbiddenException.class, USER); assertSuccess(() -> beanWithSecurityAnnotations.restricted(), "accessibleForAdminOnly", ADMIN); } @Test public void shouldNotInheritPermitAll() { assertFailureFor(() -> permitAllSubBean.unannotatedInSubclass(), UnauthorizedException.class, ANONYMOUS); assertFailureFor(() -> permitAllSubBean.unannotatedInSubclass(), ForbiddenException.class, USER, ADMIN); } @Test public void shouldAllowUnannotatedOnBeanWithNoSecurityAnnotations() { assertSuccess(() -> noAnnoBean.unannotated(), "unannotatedOnBeanWithNoAnno", ANONYMOUS, USER, ADMIN); } @Test public void shouldDenyMethodInheritedFromBeanDeniedByDefault() { assertFailureFor(() -> securityAnnoSubBean.unannotated(), UnauthorizedException.class, ANONYMOUS); assertFailureFor(() -> securityAnnoSubBean.unannotated(), ForbiddenException.class, USER, ADMIN); } @Test public void shouldAllowClassLevelPermitAll() { assertSuccess(() -> permitAllBean.unannotated(), "unannotated", ANONYMOUS, USER, ADMIN); } }
CDIAccessDenyUnannotatedTest
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/SinkEmptyMulticastTest.java
{ "start": 1201, "end": 5758 }
class ____ { @Test void currentSubscriberCount() { Sinks.Empty<Integer> sink = new SinkEmptyMulticast<>(); assertThat(sink.currentSubscriberCount()).isZero(); sink.asMono().subscribe(); assertThat(sink.currentSubscriberCount()).isOne(); sink.asMono().subscribe(); assertThat(sink.currentSubscriberCount()).isEqualTo(2); } @Test void currentSubscriberCountReflectsCancellation() { SinkEmptyMulticast<Void> mp = new SinkEmptyMulticast<>(); //this one tests immediate cancellation, potentially short-circuiting add() StepVerifier.create(mp) .thenCancel() .verify(); assertThat(mp.currentSubscriberCount()).as("cancelled during add").isZero(); //this one tests deferred cancellation when the subscriber has 100% been add()ed Disposable disposable = mp.subscribe(); assertThat(mp.currentSubscriberCount()).as("effective add").isOne(); disposable.dispose(); assertThat(mp.currentSubscriberCount()).as("disposing effective subscriber").isZero(); } @Test void blockReturnsNullOnTryEmitEmpty() { SinkEmptyMulticast<Void> mp = new SinkEmptyMulticast<>(); Schedulers.parallel().schedule(() -> mp.tryEmitEmpty(), 50L, TimeUnit.MILLISECONDS); assertThat(mp.block(Duration.ofSeconds(1))).isNull(); } @Test void blockThrowsOnTryEmitError() { SinkEmptyMulticast<Void> mp = new SinkEmptyMulticast<>(); Schedulers.parallel().schedule(() -> mp.tryEmitError(new IllegalStateException("boom")), 50L, TimeUnit.MILLISECONDS); assertThatIllegalStateException().isThrownBy(() -> mp.block(Duration.ofSeconds(1))).withMessage("boom"); } @Test void blockTimeoutsOnUnusedSink() { SinkEmptyMulticast<Void> mp = new SinkEmptyMulticast<>(); assertThatIllegalStateException().isThrownBy(() -> mp.block(Duration.ofMillis(1))) .withMessageStartingWith("Timeout"); } @Test void tryEmitEmpty(){ SinkEmptyMulticast<Void> mp = new SinkEmptyMulticast<>(); AtomicBoolean completed = new AtomicBoolean(); mp.subscribe(c ->{}, ec -> {}, () -> completed.set(true)); mp.tryEmitEmpty().orThrow(); assertThat(completed).isTrue(); assertThat(mp.scan(Scannable.Attr.ERROR)).isNull(); assertThat(mp.scan(Scannable.Attr.TERMINATED)).isTrue(); } @Test void tryEmitError() { SinkEmptyMulticast<Void> mp = new SinkEmptyMulticast<>(); AtomicReference<Throwable> ref = new AtomicReference<>(); mp.doOnError(ref::set).subscribe(v -> { }, e -> { }); mp.tryEmitError(new Exception("test")).orThrow(); assertThat(ref.get()).hasMessage("test"); assertThat(mp.scan(Scannable.Attr.ERROR)).isSameAs(ref.get()); assertThat(mp.scan(Scannable.Attr.TERMINATED)).isTrue(); } @Test void cantSubscribeWithNullSubscriber() { SinkEmptyMulticast<Void> mp = new SinkEmptyMulticast<>(); assertThatNullPointerException().isThrownBy(() -> mp.subscribe((Subscriber<Void>) null)); } @Test void doubleError() { SinkEmptyMulticast<Void> mp = new SinkEmptyMulticast<>(); mp.tryEmitError(new Exception("test")).orThrow(); assertThat(mp.tryEmitError(new Exception("test"))).isEqualTo(Sinks.EmitResult.FAIL_TERMINATED); } @Test void doubleSignal() { SinkEmptyMulticast<Void> mp = new SinkEmptyMulticast<>(); mp.tryEmitEmpty().orThrow(); assertThat(mp.tryEmitError(new Exception("test"))).isEqualTo(Sinks.EmitResult.FAIL_TERMINATED); } @Test void scanOperator() { Sinks.Empty<Integer> sinkTerminated = new SinkEmptyMulticast<>(); assertThat(sinkTerminated.scan(Scannable.Attr.TERMINATED)).as("not yet terminated").isFalse(); assertThat(sinkTerminated.scan(Scannable.Attr.RUN_STYLE)).as("run_style").isSameAs(Scannable.Attr.RunStyle.SYNC); sinkTerminated.tryEmitError(new IllegalStateException("boom")).orThrow(); assertThat(sinkTerminated.scan(Scannable.Attr.TERMINATED)).as("terminated with error").isTrue(); assertThat(sinkTerminated.scan(Scannable.Attr.ERROR)).as("error").hasMessage("boom"); } @Test void inners() { Sinks.Empty<Integer> sink = new SinkEmptyMulticast<>(); CoreSubscriber<Integer> notScannable = new BaseSubscriber<Integer>() { }; InnerConsumer<Integer> scannable = new LambdaSubscriber<>(null, null, null, null); assertThat(sink.inners()).as("before subscriptions").isEmpty(); sink.asMono().subscribe(notScannable); sink.asMono().subscribe(scannable); assertThat(sink.inners()) .asInstanceOf(InstanceOfAssertFactories.LIST) .as("after subscriptions") .hasSize(2) .extracting(l -> (Object) ((SinkEmptyMulticast.VoidInner<?>) l).actual) .containsExactly(notScannable, scannable); } }
SinkEmptyMulticastTest
java
netty__netty
common/src/main/java/io/netty/util/internal/logging/Slf4JLoggerFactory.java
{ "start": 924, "end": 2043 }
class ____ extends InternalLoggerFactory { @SuppressWarnings("deprecation") public static final InternalLoggerFactory INSTANCE = new Slf4JLoggerFactory(); /** * @deprecated Use {@link #INSTANCE} instead. */ @Deprecated public Slf4JLoggerFactory() { } Slf4JLoggerFactory(boolean failIfNOP) { assert failIfNOP; // Should be always called with true. if (LoggerFactory.getILoggerFactory() instanceof NOPLoggerFactory) { throw new NoClassDefFoundError("NOPLoggerFactory not supported"); } } @Override public InternalLogger newInstance(String name) { return wrapLogger(LoggerFactory.getLogger(name)); } // package-private for testing. static InternalLogger wrapLogger(Logger logger) { return logger instanceof LocationAwareLogger ? new LocationAwareSlf4JLogger((LocationAwareLogger) logger) : new Slf4JLogger(logger); } static InternalLoggerFactory getInstanceWithNopCheck() { return NopInstanceHolder.INSTANCE_WITH_NOP_CHECK; } private static final
Slf4JLoggerFactory
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DockerEndpointBuilderFactory.java
{ "start": 29420, "end": 36762 }
class ____ of the DockerCmdExecFactory * implementation to use. * * The option is a: <code>java.lang.String</code> type. * * Default: com.github.dockerjava.netty.NettyDockerCmdExecFactory * Group: advanced * * @param cmdExecFactory the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder cmdExecFactory(String cmdExecFactory) { doSetProperty("cmdExecFactory", cmdExecFactory); return this; } /** * Whether to follow redirect filter. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param followRedirectFilter the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder followRedirectFilter(boolean followRedirectFilter) { doSetProperty("followRedirectFilter", followRedirectFilter); return this; } /** * Whether to follow redirect filter. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param followRedirectFilter the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder followRedirectFilter(String followRedirectFilter) { doSetProperty("followRedirectFilter", followRedirectFilter); return this; } /** * Whether to use logging filter. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param loggingFilter the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder loggingFilter(boolean loggingFilter) { doSetProperty("loggingFilter", loggingFilter); return this; } /** * Whether to use logging filter. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param loggingFilter the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder loggingFilter(String loggingFilter) { doSetProperty("loggingFilter", loggingFilter); return this; } /** * Maximum route connections. * * The option is a: <code>java.lang.Integer</code> type. * * Default: 100 * Group: advanced * * @param maxPerRouteConnections the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder maxPerRouteConnections(Integer maxPerRouteConnections) { doSetProperty("maxPerRouteConnections", maxPerRouteConnections); return this; } /** * Maximum route connections. * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Default: 100 * Group: advanced * * @param maxPerRouteConnections the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder maxPerRouteConnections(String maxPerRouteConnections) { doSetProperty("maxPerRouteConnections", maxPerRouteConnections); return this; } /** * Maximum total connections. * * The option is a: <code>java.lang.Integer</code> type. * * Default: 100 * Group: advanced * * @param maxTotalConnections the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder maxTotalConnections(Integer maxTotalConnections) { doSetProperty("maxTotalConnections", maxTotalConnections); return this; } /** * Maximum total connections. * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Default: 100 * Group: advanced * * @param maxTotalConnections the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder maxTotalConnections(String maxTotalConnections) { doSetProperty("maxTotalConnections", maxTotalConnections); return this; } /** * Additional configuration parameters as key/value pairs. * * The option is a: <code>java.util.Map&lt;java.lang.String, * java.lang.Object&gt;</code> type. * * Group: advanced * * @param parameters the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder parameters(Map<java.lang.String, java.lang.Object> parameters) { doSetProperty("parameters", parameters); return this; } /** * Additional configuration parameters as key/value pairs. * * The option will be converted to a * <code>java.util.Map&lt;java.lang.String, java.lang.Object&gt;</code> * type. * * Group: advanced * * @param parameters the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder parameters(String parameters) { doSetProperty("parameters", parameters); return this; } /** * Server address for docker registry. * * The option is a: <code>java.lang.String</code> type. * * Default: https://index.docker.io/v1/ * Group: advanced * * @param serverAddress the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder serverAddress(String serverAddress) { doSetProperty("serverAddress", serverAddress); return this; } /** * Socket connection mode. * * The option is a: <code>boolean</code> type. * * Default: true * Group: advanced * * @param socket the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder socket(boolean socket) { doSetProperty("socket", socket); return this; } /** * Socket connection mode. * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: advanced * * @param socket the value to set * @return the dsl builder */ default AdvancedDockerEndpointProducerBuilder socket(String socket) { doSetProperty("socket", socket); return this; } } /** * Builder for endpoint for the Docker component. */ public
name
java
alibaba__druid
core/src/main/java/com/alibaba/druid/mock/MockResultSetMetaData.java
{ "start": 751, "end": 886 }
class ____ extends ResultSetMetaDataBase implements ResultSetMetaData { public MockResultSetMetaData() { } }
MockResultSetMetaData
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/dialect/lock/LockingStrategyException.java
{ "start": 304, "end": 1056 }
class ____ extends HibernateException { private final Object entity; /** * Constructs a LockingStrategyException * * @param entity The entity we were trying to lock * @param message Message explaining the condition */ public LockingStrategyException(Object entity, String message) { super( message ); this.entity = entity; } /** * Constructs a LockingStrategyException * * @param entity The entity we were trying to lock * @param message Message explaining the condition * @param cause The underlying cause */ public LockingStrategyException(Object entity, String message, Throwable cause) { super( message, cause ); this.entity = entity; } public Object getEntity() { return entity; } }
LockingStrategyException
java
dropwizard__dropwizard
dropwizard-servlets/src/main/java/io/dropwizard/servlets/tasks/TaskServlet.java
{ "start": 8283, "end": 8777 }
class ____ { private final Task task; private TaskExecutor(Task task) { this.task = task; } public void executeTask(Map<String, List<String>> params, String body, PrintWriter output) throws Exception { if (task instanceof PostBodyTask postBodyTask) { postBodyTask.execute(params, body, output); } else { task.execute(params, output); } } } private static
TaskExecutor
java
processing__processing4
app/src/processing/app/contrib/Contribution.java
{ "start": 9559, "end": 9627 }
interface ____ { boolean matches(Contribution contrib); } }
Filter
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/DoNotCallCheckerTest.java
{ "start": 22444, "end": 22965 }
class ____ { void f(LockInfo l, MonitorInfo m) { // BUG: Diagnostic contains: getClassName l.getClass(); // BUG: Diagnostic contains: getClassName m.getClass(); } } """) .doTest(); } @Test public void positive_parameterizedTypeGetClass() { testHelper .addSourceLines( "Test.java", """ import java.lang.reflect.ParameterizedType;
Test
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/BoundedBlockingSubpartitionWriteReadTest.java
{ "start": 11446, "end": 12340 }
class ____ extends CheckedThread { private final ResultSubpartitionView reader; private final long numLongs; private final int numBuffers; private final boolean compressionEnabled; private final BufferDecompressor decompressor; LongReader( ResultSubpartitionView reader, long numLongs, int numBuffers, boolean compressionEnabled) { this.reader = reader; this.numLongs = numLongs; this.numBuffers = numBuffers; this.compressionEnabled = compressionEnabled; this.decompressor = new BufferDecompressor(BUFFER_SIZE, COMPRESSION_CODEC); } @Override public void go() throws Exception { readLongs(reader, numLongs, numBuffers, compressionEnabled, decompressor); } } }
LongReader
java
playframework__playframework
dev-mode/play-run-support/src/main/java/play/runsupport/CompileResult.java
{ "start": 417, "end": 915 }
class ____ implements CompileResult { private final Map<String, Source> sources; private final List<File> classpath; public CompileSuccess(Map<String, Source> sources, List<File> classpath) { this.sources = requireNonNullElse(sources, Map.of()); this.classpath = requireNonNullElse(classpath, List.of()); } public Map<String, Source> getSources() { return sources; } public List<File> getClasspath() { return classpath; } }
CompileSuccess
java
dropwizard__dropwizard
dropwizard-logging/src/test/java/io/dropwizard/logging/common/SyslogAppenderFactoryTest.java
{ "start": 725, "end": 3975 }
class ____ { static { BootstrapLogging.bootstrap(); } @Test void isDiscoverable() { assertThat(new DiscoverableSubtypeResolver().getDiscoveredSubtypes()) .contains(SyslogAppenderFactory.class); } @Test void defaultIncludesAppName() { assertThat(new SyslogAppenderFactory().getLogFormat()) .contains("%app"); } @Test void defaultIncludesPid() { assertThat(new SyslogAppenderFactory().getLogFormat()) .contains("%pid"); } @Test void patternIncludesAppNameAndPid() { assertThat(new SyslogAppenderFactory() .build(new LoggerContext(), "MyApplication", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory())) .isInstanceOfSatisfying(AsyncAppender.class, asyncAppender -> assertThat(asyncAppender.getAppender("syslog-appender")) .isInstanceOfSatisfying(SyslogAppender.class, syslogAppender -> assertThat(syslogAppender.getSuffixPattern()).matches("^MyApplication\\[\\d+\\].+"))); } @Test void stackTracePatternCanBeSet() { final SyslogAppenderFactory syslogAppenderFactory = new SyslogAppenderFactory(); syslogAppenderFactory.setStackTracePrefix("--->"); assertThat(syslogAppenderFactory .build(new LoggerContext(), "MyApplication", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory())) .isInstanceOfSatisfying(AsyncAppender.class, asyncAppender -> assertThat(asyncAppender.getAppender("syslog-appender")) .isInstanceOfSatisfying(SyslogAppender.class, syslogAppender -> assertThat(syslogAppender.getStackTracePattern()).isEqualTo("--->"))); } @Test void appenderContextIsSet() { final Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); final SyslogAppenderFactory appenderFactory = new SyslogAppenderFactory(); final Appender<ILoggingEvent> appender = appenderFactory.build(root.getLoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory()); assertThat(appender.getContext()).isEqualTo(root.getLoggerContext()); } @Test void appenderNameIsSet() { final Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); final SyslogAppenderFactory appenderFactory = new SyslogAppenderFactory(); final Appender<ILoggingEvent> appender = appenderFactory.build(root.getLoggerContext(), "test", new DropwizardLayoutFactory(), new NullLevelFilterFactory<>(), new AsyncLoggingEventAppenderFactory()); assertThat(appender.getName()).isEqualTo("async-syslog-appender"); } @Test void syslogFacilityTest() { for (SyslogAppenderFactory.Facility facility : SyslogAppenderFactory.Facility.values()) { assertThat(SyslogAppender.facilityStringToint(facility.toString().toLowerCase(Locale.ENGLISH))) .isNotNegative(); } } }
SyslogAppenderFactoryTest
java
apache__camel
components/camel-google/camel-google-calendar/src/generated/java/org/apache/camel/component/google/calendar/CalendarEventsEndpointConfiguration.java
{ "start": 3049, "end": 23812 }
class ____ extends GoogleCalendarConfiguration { @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "get", description="Deprecated and ignored"), @ApiMethod(methodName = "instances", description="Deprecated and ignored"), @ApiMethod(methodName = "list", description="Deprecated and ignored"), @ApiMethod(methodName = "patch", description="Deprecated and ignored"), @ApiMethod(methodName = "update", description="Deprecated and ignored"), @ApiMethod(methodName = "watch", description="Deprecated and ignored")}) private java.lang.Boolean alwaysIncludeEmail; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "calendarImport", description="Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the primary keyword."), @ApiMethod(methodName = "delete", description="Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the primary keyword."), @ApiMethod(methodName = "get", description="Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the primary keyword."), @ApiMethod(methodName = "insert", description="Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the primary keyword."), @ApiMethod(methodName = "instances", description="Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the primary keyword."), @ApiMethod(methodName = "list", description="Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the primary keyword."), @ApiMethod(methodName = "move", description="Calendar identifier of the source calendar where the event currently is on"), @ApiMethod(methodName = "patch", description="Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the primary keyword."), @ApiMethod(methodName = "quickAdd", description="Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the primary keyword."), @ApiMethod(methodName = "update", description="Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the primary keyword."), @ApiMethod(methodName = "watch", description="Calendar identifier. To retrieve calendar IDs call the calendarList.list method. If you want to access the primary calendar of the currently logged in user, use the primary keyword.")}) private String calendarId; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "calendarImport", description="Version number of conference data supported by the API client"), @ApiMethod(methodName = "insert", description="Version number of conference data supported by the API client"), @ApiMethod(methodName = "patch", description="Version number of conference data supported by the API client"), @ApiMethod(methodName = "update", description="Version number of conference data supported by the API client")}) private java.lang.Integer conferenceDataVersion; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "calendarImport", description="The com.google.api.services.calendar.model.Event"), @ApiMethod(methodName = "insert", description="The com.google.api.services.calendar.model.Event"), @ApiMethod(methodName = "patch", description="The com.google.api.services.calendar.model.Event"), @ApiMethod(methodName = "update", description="The com.google.api.services.calendar.model.Event")}) private com.google.api.services.calendar.model.Event content; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "watch", description="The com.google.api.services.calendar.model.Channel")}) private com.google.api.services.calendar.model.Channel contentChannel; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "move", description="Calendar identifier of the target calendar where the event is to be moved to")}) private String destination; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "delete", description="Event identifier"), @ApiMethod(methodName = "get", description="Event identifier"), @ApiMethod(methodName = "instances", description="Recurring event identifier"), @ApiMethod(methodName = "move", description="Event identifier"), @ApiMethod(methodName = "patch", description="Event identifier"), @ApiMethod(methodName = "update", description="Event identifier")}) private String eventId; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Event types to return"), @ApiMethod(methodName = "watch", description="Event types to return")}) private java.util.List eventTypes; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Specifies an event ID in the iCalendar format to be provided in the response"), @ApiMethod(methodName = "watch", description="Specifies an event ID in the iCalendar format to be provided in the response")}) private java.lang.String iCalUID; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "get", description="The maximum number of attendees to include in the response"), @ApiMethod(methodName = "insert", description="The maximum number of attendees to include in the response"), @ApiMethod(methodName = "instances", description="The maximum number of attendees to include in the response"), @ApiMethod(methodName = "list", description="The maximum number of attendees to include in the response"), @ApiMethod(methodName = "patch", description="The maximum number of attendees to include in the response"), @ApiMethod(methodName = "update", description="The maximum number of attendees to include in the response"), @ApiMethod(methodName = "watch", description="The maximum number of attendees to include in the response")}) private java.lang.Integer maxAttendees; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "instances", description="Maximum number of events returned on one result page"), @ApiMethod(methodName = "list", description="Maximum number of events returned on one result page"), @ApiMethod(methodName = "watch", description="Maximum number of events returned on one result page")}) private java.lang.Integer maxResults; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="The order of the events returned in the result"), @ApiMethod(methodName = "watch", description="The order of the events returned in the result")}) private java.lang.String orderBy; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "instances", description="The original start time of the instance in the result")}) private java.lang.String originalStart; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "instances", description="Token specifying which result page to return"), @ApiMethod(methodName = "list", description="Token specifying which result page to return"), @ApiMethod(methodName = "watch", description="Token specifying which result page to return")}) private java.lang.String pageToken; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Extended properties constraint specified as propertyName=value"), @ApiMethod(methodName = "watch", description="Extended properties constraint specified as propertyName=value")}) private java.util.List privateExtendedProperty; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Free text search terms to find events that match these terms in the following fields: - summary - description - location - attendee's displayName - attendee's email - organizer's displayName - organizer's email - workingLocationProperties"), @ApiMethod(methodName = "watch", description="Free text search terms to find events that match these terms in the following fields: - summary - description - location - attendee's displayName - attendee's email - organizer's displayName - organizer's email - workingLocationProperties")}) private java.lang.String q; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "delete", description="Deprecated"), @ApiMethod(methodName = "insert", description="Deprecated"), @ApiMethod(methodName = "move", description="Deprecated"), @ApiMethod(methodName = "patch", description="Deprecated"), @ApiMethod(methodName = "quickAdd", description="Deprecated"), @ApiMethod(methodName = "update", description="Deprecated")}) private java.lang.Boolean sendNotifications; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "delete", description="Guests who should receive notifications about the deletion of the event"), @ApiMethod(methodName = "insert", description="Whether to send notifications about the creation of the new event"), @ApiMethod(methodName = "move", description="Guests who should receive notifications about the change of the event's organizer"), @ApiMethod(methodName = "patch", description="Guests who should receive notifications about the event update (for example, title changes, etc"), @ApiMethod(methodName = "quickAdd", description="Guests who should receive notifications about the creation of the new event"), @ApiMethod(methodName = "update", description="Guests who should receive notifications about the event update (for example, title changes, etc")}) private java.lang.String sendUpdates; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Extended properties constraint specified as propertyName=value"), @ApiMethod(methodName = "watch", description="Extended properties constraint specified as propertyName=value")}) private java.util.List sharedExtendedProperty; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "instances", description="Whether to include deleted events (with status equals cancelled) in the result"), @ApiMethod(methodName = "list", description="Whether to include deleted events (with status equals cancelled) in the result"), @ApiMethod(methodName = "watch", description="Whether to include deleted events (with status equals cancelled) in the result")}) private java.lang.Boolean showDeleted; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Whether to include hidden invitations in the result"), @ApiMethod(methodName = "watch", description="Whether to include hidden invitations in the result")}) private java.lang.Boolean showHiddenInvitations; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Whether to expand recurring events into instances and only return single one-off events and instances of recurring events, but not the underlying recurring events themselves"), @ApiMethod(methodName = "watch", description="Whether to expand recurring events into instances and only return single one-off events and instances of recurring events, but not the underlying recurring events themselves")}) private java.lang.Boolean singleEvents; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "calendarImport", description="Whether API client performing operation supports event attachments"), @ApiMethod(methodName = "insert", description="Whether API client performing operation supports event attachments"), @ApiMethod(methodName = "patch", description="Whether API client performing operation supports event attachments"), @ApiMethod(methodName = "update", description="Whether API client performing operation supports event attachments")}) private java.lang.Boolean supportsAttachments; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Token obtained from the nextSyncToken field returned on the last page of results from the previous list request"), @ApiMethod(methodName = "watch", description="Token obtained from the nextSyncToken field returned on the last page of results from the previous list request")}) private java.lang.String syncToken; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "quickAdd", description="The text describing the event to be created")}) private String text; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "instances", description="Upper bound (exclusive) for an event's start time to filter by"), @ApiMethod(methodName = "list", description="Upper bound (exclusive) for an event's start time to filter by"), @ApiMethod(methodName = "watch", description="Upper bound (exclusive) for an event's start time to filter by")}) private com.google.api.client.util.DateTime timeMax; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "instances", description="Lower bound (inclusive) for an event's end time to filter by"), @ApiMethod(methodName = "list", description="Lower bound (exclusive) for an event's end time to filter by"), @ApiMethod(methodName = "watch", description="Lower bound (exclusive) for an event's end time to filter by")}) private com.google.api.client.util.DateTime timeMin; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "get", description="Time zone used in the response"), @ApiMethod(methodName = "instances", description="Time zone used in the response"), @ApiMethod(methodName = "list", description="Time zone used in the response"), @ApiMethod(methodName = "watch", description="Time zone used in the response")}) private java.lang.String timeZone; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "list", description="Lower bound for an event's last modification time (as a RFC3339 timestamp) to filter by"), @ApiMethod(methodName = "watch", description="Lower bound for an event's last modification time (as a RFC3339 timestamp) to filter by")}) private com.google.api.client.util.DateTime updatedMin; public java.lang.Boolean getAlwaysIncludeEmail() { return alwaysIncludeEmail; } public void setAlwaysIncludeEmail(java.lang.Boolean alwaysIncludeEmail) { this.alwaysIncludeEmail = alwaysIncludeEmail; } public String getCalendarId() { return calendarId; } public void setCalendarId(String calendarId) { this.calendarId = calendarId; } public java.lang.Integer getConferenceDataVersion() { return conferenceDataVersion; } public void setConferenceDataVersion(java.lang.Integer conferenceDataVersion) { this.conferenceDataVersion = conferenceDataVersion; } public com.google.api.services.calendar.model.Event getContent() { return content; } public void setContent(com.google.api.services.calendar.model.Event content) { this.content = content; } public com.google.api.services.calendar.model.Channel getContentChannel() { return contentChannel; } public void setContentChannel(com.google.api.services.calendar.model.Channel contentChannel) { this.contentChannel = contentChannel; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public String getEventId() { return eventId; } public void setEventId(String eventId) { this.eventId = eventId; } public java.util.List getEventTypes() { return eventTypes; } public void setEventTypes(java.util.List eventTypes) { this.eventTypes = eventTypes; } public java.lang.String getICalUID() { return iCalUID; } public void setICalUID(java.lang.String iCalUID) { this.iCalUID = iCalUID; } public java.lang.Integer getMaxAttendees() { return maxAttendees; } public void setMaxAttendees(java.lang.Integer maxAttendees) { this.maxAttendees = maxAttendees; } public java.lang.Integer getMaxResults() { return maxResults; } public void setMaxResults(java.lang.Integer maxResults) { this.maxResults = maxResults; } public java.lang.String getOrderBy() { return orderBy; } public void setOrderBy(java.lang.String orderBy) { this.orderBy = orderBy; } public java.lang.String getOriginalStart() { return originalStart; } public void setOriginalStart(java.lang.String originalStart) { this.originalStart = originalStart; } public java.lang.String getPageToken() { return pageToken; } public void setPageToken(java.lang.String pageToken) { this.pageToken = pageToken; } public java.util.List getPrivateExtendedProperty() { return privateExtendedProperty; } public void setPrivateExtendedProperty(java.util.List privateExtendedProperty) { this.privateExtendedProperty = privateExtendedProperty; } public java.lang.String getQ() { return q; } public void setQ(java.lang.String q) { this.q = q; } public java.lang.Boolean getSendNotifications() { return sendNotifications; } public void setSendNotifications(java.lang.Boolean sendNotifications) { this.sendNotifications = sendNotifications; } public java.lang.String getSendUpdates() { return sendUpdates; } public void setSendUpdates(java.lang.String sendUpdates) { this.sendUpdates = sendUpdates; } public java.util.List getSharedExtendedProperty() { return sharedExtendedProperty; } public void setSharedExtendedProperty(java.util.List sharedExtendedProperty) { this.sharedExtendedProperty = sharedExtendedProperty; } public java.lang.Boolean getShowDeleted() { return showDeleted; } public void setShowDeleted(java.lang.Boolean showDeleted) { this.showDeleted = showDeleted; } public java.lang.Boolean getShowHiddenInvitations() { return showHiddenInvitations; } public void setShowHiddenInvitations(java.lang.Boolean showHiddenInvitations) { this.showHiddenInvitations = showHiddenInvitations; } public java.lang.Boolean getSingleEvents() { return singleEvents; } public void setSingleEvents(java.lang.Boolean singleEvents) { this.singleEvents = singleEvents; } public java.lang.Boolean getSupportsAttachments() { return supportsAttachments; } public void setSupportsAttachments(java.lang.Boolean supportsAttachments) { this.supportsAttachments = supportsAttachments; } public java.lang.String getSyncToken() { return syncToken; } public void setSyncToken(java.lang.String syncToken) { this.syncToken = syncToken; } public String getText() { return text; } public void setText(String text) { this.text = text; } public com.google.api.client.util.DateTime getTimeMax() { return timeMax; } public void setTimeMax(com.google.api.client.util.DateTime timeMax) { this.timeMax = timeMax; } public com.google.api.client.util.DateTime getTimeMin() { return timeMin; } public void setTimeMin(com.google.api.client.util.DateTime timeMin) { this.timeMin = timeMin; } public java.lang.String getTimeZone() { return timeZone; } public void setTimeZone(java.lang.String timeZone) { this.timeZone = timeZone; } public com.google.api.client.util.DateTime getUpdatedMin() { return updatedMin; } public void setUpdatedMin(com.google.api.client.util.DateTime updatedMin) { this.updatedMin = updatedMin; } }
CalendarEventsEndpointConfiguration
java
apache__camel
components/camel-metrics/src/main/java/org/apache/camel/component/metrics/MeterProducer.java
{ "start": 1088, "end": 1720 }
class ____ extends AbstractMetricsProducer { public MeterProducer(MetricsEndpoint endpoint) { super(endpoint); } @Override protected void doProcess(Exchange exchange, MetricsEndpoint endpoint, MetricRegistry registry, String metricsName) throws Exception { Message in = exchange.getIn(); Meter meter = registry.meter(metricsName); Long mark = endpoint.getMark(); Long finalMark = getLongHeader(in, HEADER_METER_MARK, mark); if (finalMark == null) { meter.mark(); } else { meter.mark(finalMark); } } }
MeterProducer
java
junit-team__junit5
junit-jupiter-params/src/main/java/org/junit/jupiter/params/ArgumentCountValidator.java
{ "start": 803, "end": 5280 }
class ____ { private static final Logger logger = LoggerFactory.getLogger(ArgumentCountValidator.class); static final String ARGUMENT_COUNT_VALIDATION_KEY = "junit.jupiter.params.argumentCountValidation"; private static final Namespace NAMESPACE = Namespace.create(ArgumentCountValidator.class); private final ParameterizedDeclarationContext<?> declarationContext; private final EvaluatedArgumentSet arguments; ArgumentCountValidator(ParameterizedDeclarationContext<?> declarationContext, EvaluatedArgumentSet arguments) { this.declarationContext = declarationContext; this.arguments = arguments; } void validate(ExtensionContext extensionContext) { validateRequiredArgumentsArePresent(); ArgumentCountValidationMode argumentCountValidationMode = getArgumentCountValidationMode(extensionContext); switch (argumentCountValidationMode) { case DEFAULT, NONE -> { } case STRICT -> { int consumedCount = this.declarationContext.getResolverFacade().determineConsumedArgumentCount( this.arguments); int totalCount = this.arguments.getTotalLength(); Preconditions.condition(consumedCount == totalCount, () -> wrongNumberOfArgumentsMessages("consumes", consumedCount, null, null)); } default -> throw new ExtensionConfigurationException( "Unsupported argument count validation mode: " + argumentCountValidationMode); } } private void validateRequiredArgumentsArePresent() { var requiredParameterCount = this.declarationContext.getResolverFacade().getRequiredParameterCount(); if (requiredParameterCount != null) { var totalCount = this.arguments.getTotalLength(); Preconditions.condition(requiredParameterCount.value() <= totalCount, () -> wrongNumberOfArgumentsMessages("has", requiredParameterCount.value(), "required", requiredParameterCount.reason())); } } private String wrongNumberOfArgumentsMessages(String verb, int actualCount, @Nullable String parameterAdjective, @Nullable String reason) { int totalCount = this.arguments.getTotalLength(); return "Configuration error: @%s %s %s %s%s%s but there %s %s %s provided.%nNote: the provided arguments were %s".formatted( this.declarationContext.getAnnotationName(), verb, actualCount, parameterAdjective == null ? "" : parameterAdjective + " ", pluralize(actualCount, "parameter", "parameters"), reason == null ? "" : " (due to %s)".formatted(reason), pluralize(totalCount, "was", "were"), totalCount, pluralize(totalCount, "argument", "arguments"), Arrays.toString(this.arguments.getAllPayloads())); } private ArgumentCountValidationMode getArgumentCountValidationMode(ExtensionContext extensionContext) { ArgumentCountValidationMode mode = declarationContext.getArgumentCountValidationMode(); if (mode != ArgumentCountValidationMode.DEFAULT) { return mode; } else { return getArgumentCountValidationModeConfiguration(extensionContext); } } private ArgumentCountValidationMode getArgumentCountValidationModeConfiguration(ExtensionContext extensionContext) { String key = ARGUMENT_COUNT_VALIDATION_KEY; ArgumentCountValidationMode fallback = ArgumentCountValidationMode.NONE; ExtensionContext.Store store = getStore(extensionContext); return store.computeIfAbsent(key, __ -> { Optional<String> optionalConfigValue = extensionContext.getConfigurationParameter(key); if (optionalConfigValue.isPresent()) { String configValue = optionalConfigValue.get(); Optional<ArgumentCountValidationMode> enumValue = Arrays.stream( ArgumentCountValidationMode.values()).filter( mode -> mode.name().equalsIgnoreCase(configValue)).findFirst(); if (enumValue.isPresent()) { logger.config( () -> "Using ArgumentCountValidationMode '%s' set via the '%s' configuration parameter.".formatted( enumValue.get().name(), key)); return enumValue.get(); } else { logger.warn(() -> """ Invalid ArgumentCountValidationMode '%s' set via the '%s' configuration parameter. \ Falling back to the %s default value.""".formatted(configValue, key, fallback.name())); return fallback; } } else { return fallback; } }, ArgumentCountValidationMode.class); } private static String pluralize(int count, String singular, String plural) { return count == 1 ? singular : plural; } private ExtensionContext.Store getStore(ExtensionContext context) { return context.getRoot().getStore(NAMESPACE); } }
ArgumentCountValidator
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/jdbc/PropertyPlaceholderSqlScriptsTests.java
{ "start": 1518, "end": 1921 }
class ____ extends AbstractTransactionalTests { @Test @Sql(SCRIPT_LOCATION) void placeholderIsResolvedInScriptLocation() { assertUsers("Dilbert 1"); } } @Nested @ContextConfiguration(classes = PopulatedSchemaDatabaseConfig.class) @TestPropertySource(properties = "vendor = db2") @DirtiesContext @DisabledInAotMode("${vendor} does not get resolved during AOT processing")
DatabaseOneTests
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ValueDeserializer.java
{ "start": 21343, "end": 21451 }
class ____ extends ValueDeserializer<Object> { private None() { } // not to be instantiated } }
None
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/security/oauthbearer/OAuthBearerLoginCallbackHandler.java
{ "start": 6424, "end": 12044 }
class ____ implements AuthenticateCallbackHandler { private static final Logger log = LoggerFactory.getLogger(OAuthBearerLoginCallbackHandler.class); public static final String CLIENT_ID_CONFIG = "clientId"; public static final String CLIENT_SECRET_CONFIG = "clientSecret"; public static final String SCOPE_CONFIG = "scope"; public static final String CLIENT_ID_DOC = "The OAuth/OIDC identity provider-issued " + "client ID to uniquely identify the service account to use for authentication for " + "this client. The value must be paired with a corresponding " + CLIENT_SECRET_CONFIG + " " + "value and is provided to the OAuth provider using the OAuth " + "clientcredentials grant type."; public static final String CLIENT_SECRET_DOC = "The OAuth/OIDC identity provider-issued " + "client secret serves a similar function as a password to the " + CLIENT_ID_CONFIG + " " + "account and identifies the service account to use for authentication for " + "this client. The value must be paired with a corresponding " + CLIENT_ID_CONFIG + " " + "value and is provided to the OAuth provider using the OAuth " + "clientcredentials grant type."; public static final String SCOPE_DOC = "The (optional) HTTP/HTTPS login request to the " + "token endpoint (" + SASL_OAUTHBEARER_TOKEN_ENDPOINT_URL + ") may need to specify an " + "OAuth \"scope\". If so, the " + SCOPE_CONFIG + " is used to provide the value to " + "include with the login request."; private static final String EXTENSION_PREFIX = "extension_"; private Map<String, Object> moduleOptions; private JwtRetriever jwtRetriever; private JwtValidator jwtValidator; @Override public void configure(Map<String, ?> configs, String saslMechanism, List<AppConfigurationEntry> jaasConfigEntries) { moduleOptions = JaasOptionsUtils.getOptions(saslMechanism, jaasConfigEntries); jwtRetriever = getConfiguredInstance( configs, saslMechanism, jaasConfigEntries, SaslConfigs.SASL_OAUTHBEARER_JWT_RETRIEVER_CLASS, JwtRetriever.class ); jwtValidator = getConfiguredInstance( configs, saslMechanism, jaasConfigEntries, SaslConfigs.SASL_OAUTHBEARER_JWT_VALIDATOR_CLASS, JwtValidator.class ); } /* * Package-visible for testing. */ void configure(Map<String, ?> configs, String saslMechanism, List<AppConfigurationEntry> jaasConfigEntries, JwtRetriever jwtRetriever, JwtValidator jwtValidator) { this.moduleOptions = JaasOptionsUtils.getOptions(saslMechanism, jaasConfigEntries); this.jwtRetriever = jwtRetriever; this.jwtRetriever.configure(configs, saslMechanism, jaasConfigEntries); this.jwtValidator = jwtValidator; this.jwtValidator.configure(configs, saslMechanism, jaasConfigEntries); } @Override public void close() { Utils.closeQuietly(jwtRetriever, "JWT retriever"); Utils.closeQuietly(jwtValidator, "JWT validator"); } @Override public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException { checkConfigured(); for (Callback callback : callbacks) { if (callback instanceof OAuthBearerTokenCallback) { handleTokenCallback((OAuthBearerTokenCallback) callback); } else if (callback instanceof SaslExtensionsCallback) { handleExtensionsCallback((SaslExtensionsCallback) callback); } else { throw new UnsupportedCallbackException(callback); } } } private void handleTokenCallback(OAuthBearerTokenCallback callback) throws IOException { checkConfigured(); String accessToken = jwtRetriever.retrieve(); try { OAuthBearerToken token = jwtValidator.validate(accessToken); callback.token(token); } catch (JwtValidatorException e) { log.warn(e.getMessage(), e); callback.error("invalid_token", e.getMessage(), null); } } private void handleExtensionsCallback(SaslExtensionsCallback callback) { checkConfigured(); Map<String, String> extensions = new HashMap<>(); for (Map.Entry<String, Object> configEntry : this.moduleOptions.entrySet()) { String key = configEntry.getKey(); if (!key.startsWith(EXTENSION_PREFIX)) continue; Object valueRaw = configEntry.getValue(); String value; if (valueRaw instanceof String) value = (String) valueRaw; else value = String.valueOf(valueRaw); extensions.put(key.substring(EXTENSION_PREFIX.length()), value); } SaslExtensions saslExtensions = new SaslExtensions(extensions); try { OAuthBearerClientInitialResponse.validateExtensions(saslExtensions); } catch (SaslException e) { throw new ConfigException(e.getMessage()); } callback.extensions(saslExtensions); } private void checkConfigured() { if (moduleOptions == null || jwtRetriever == null || jwtValidator == null) throw new IllegalStateException(String.format("To use %s, first call the configure method", getClass().getSimpleName())); } }
OAuthBearerLoginCallbackHandler
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_197.java
{ "start": 303, "end": 2927 }
class ____ extends MysqlTest { public void test_0() throws Exception { String sql = "select \"\"\"1\"\"\"\"\" as a;"; System.out.println(sql); MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT '\"1\"\"' AS a;", stmt.toString()); assertEquals("select '\"1\"\"' as a;", stmt.toLowerCaseString()); } public void test_1() throws Exception { String sql = "select \"\\\"1\"\"\"\"\" as a;"; System.out.println(sql); MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT '\"1\"\"' AS a;", stmt.toString()); assertEquals("select '\"1\"\"' as a;", stmt.toLowerCaseString()); } public void test_2() throws Exception { String sql = "select \"\"\"1\"\"\\\"\" as a;"; System.out.println(sql); MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT '\"1\"\"' AS a;", stmt.toString()); assertEquals("select '\"1\"\"' as a;", stmt.toLowerCaseString()); } public void test_3() throws Exception { String sql = "select '''1''''' as a;"; System.out.println(sql); MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT '''1''''' AS a;", stmt.toString()); } public void test_4() throws Exception { String sql = "select '\\'1\\'\\'' as a;"; System.out.println(sql); MySqlStatementParser parser = new MySqlStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLSelectStatement stmt = (SQLSelectStatement) statementList.get(0); assertEquals(1, statementList.size()); assertEquals("SELECT '''1''''' AS a;", stmt.toString()); } }
MySqlSelectTest_197
java
quarkusio__quarkus
extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/JKSTrustStoreFromClassPathTest.java
{ "start": 866, "end": 2161 }
class ____ { private static final String configuration = """ quarkus.tls.trust-store.jks.path=/certs/truststore.jks quarkus.tls.trust-store.jks.password=password """; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addAsResource(new File("target/certs/test-formats-truststore.jks"), "/certs/truststore.jks") .add(new StringAsset(configuration), "application.properties")); @Inject TlsConfigurationRegistry certificates; @Test void test() throws KeyStoreException, CertificateParsingException { TlsConfiguration def = certificates.getDefault().orElseThrow(); assertThat(def.getTrustStoreOptions()).isNotNull(); assertThat(def.getTrustStore()).isNotNull(); X509Certificate certificate = (X509Certificate) def.getTrustStore() .getCertificate("test-formats"); assertThat(certificate).isNotNull(); assertThat(certificate.getSubjectAlternativeNames()).anySatisfy(l -> { assertThat(l.get(0)).isEqualTo(2); assertThat(l.get(1)).isEqualTo("localhost"); }); } }
JKSTrustStoreFromClassPathTest
java
grpc__grpc-java
core/src/main/java/io/grpc/internal/TransportTracer.java
{ "start": 854, "end": 1026 }
class ____ gathering statistics about a transport. This is an experimental feature. * Can only be called from the transport thread unless otherwise noted. */ public final
for
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ClassNewInstanceTest.java
{ "start": 12372, "end": 12936 }
class ____ { void f() throws InstantiationException, IllegalAccessException { try { getClass().newInstance(); } catch (InstantiationException e) { getClass().newInstance(); } catch (IllegalAccessException e) { getClass().newInstance(); } } } """) .addOutputLines( "out/Test.java", """ import java.lang.reflect.InvocationTargetException;
Test
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/web/servlet/htmlunit/MockMvcWebClientBuilderTests.java
{ "start": 5321, "end": 5488 }
class ____ { @RequestMapping("/test") String contextPath(HttpServletRequest request) { return "mvc"; } } } @RestController static
ContextPathController
java
quarkusio__quarkus
extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/logs/LoggingFrameworkTest.java
{ "start": 5460, "end": 5911 }
class ____ { // using the logger adapter: https://quarkus.io/guides/logging#add-a-logging-adapter-to-your-application private static final org.apache.logging.log4j.Logger LOG = org.apache.logging.log4j.LogManager .getLogger(Log4j2Bean.class); public String hello(final String message) { LOG.info(message); return "hello"; } } @ApplicationScoped public static
Log4j2Bean
java
mapstruct__mapstruct
processor/src/test/resources/fixtures/org/mapstruct/ap/test/subclassmapping/fixture/SubclassImplementedMapperImpl.java
{ "start": 488, "end": 2277 }
class ____ implements SubclassImplementedMapper { @Override public ImplementedParentTarget map(ImplementedParentSource item) { if ( item == null ) { return null; } if (item instanceof SubSource) { return subSourceToSubTarget( (SubSource) item ); } else if (item instanceof SubSourceOther) { return subSourceOtherToSubTargetOther( (SubSourceOther) item ); } else { ImplementedParentTarget implementedParentTarget = new ImplementedParentTarget(); implementedParentTarget.setParentValue( item.getParentValue() ); implementedParentTarget.setImplementedParentValue( item.getImplementedParentValue() ); return implementedParentTarget; } } protected SubTarget subSourceToSubTarget(SubSource subSource) { if ( subSource == null ) { return null; } SubTarget subTarget = new SubTarget(); subTarget.setParentValue( subSource.getParentValue() ); subTarget.setImplementedParentValue( subSource.getImplementedParentValue() ); subTarget.setValue( subSource.getValue() ); return subTarget; } protected SubTargetOther subSourceOtherToSubTargetOther(SubSourceOther subSourceOther) { if ( subSourceOther == null ) { return null; } String finalValue = null; finalValue = subSourceOther.getFinalValue(); SubTargetOther subTargetOther = new SubTargetOther( finalValue ); subTargetOther.setParentValue( subSourceOther.getParentValue() ); subTargetOther.setImplementedParentValue( subSourceOther.getImplementedParentValue() ); return subTargetOther; } }
SubclassImplementedMapperImpl
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/node/JsonNodeConversionsTest.java
{ "start": 2026, "end": 2308 }
class ____ extends ValueSerializer<Issue467Bean> { @Override public void serialize(Issue467Bean value, JsonGenerator g, SerializationContext provider) { g.writePOJO(new Issue467TmpBean(value.i)); } } static
Issue467Serializer
java
elastic__elasticsearch
x-pack/plugin/analytics/src/main/java/org/elasticsearch/xpack/analytics/multiterms/MultiTermsAggregator.java
{ "start": 21226, "end": 21289 }
class ____ string and ip doc values */ abstract static
for
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/Debug.java
{ "start": 47165, "end": 47385 }
class ____ { int index; String routeId; String nodeId; long elapsed; boolean skipOver; String location; int line; String code; } private static
History
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/AbstractPartitionTracker.java
{ "start": 3845, "end": 4404 }
class ____<K, M> { private final K key; private final M metaInfo; PartitionInfo(K key, M metaInfo) { this.key = key; this.metaInfo = metaInfo; } K getKey() { return key; } M getMetaInfo() { return metaInfo; } } private static <X> Stream<X> asStream(Optional<X> optional) { if (optional.isPresent()) { return Stream.of(optional.get()); } else { return Stream.empty(); } } }
PartitionInfo
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/async/AsyncTask.java
{ "start": 502, "end": 1158 }
interface ____ { /** * Returns all of the request contexts headers */ Map<String, String> getOriginHeaders(); /** * Returns the {@link AsyncExecutionId} of the task */ AsyncExecutionId getExecutionId(); /** * Returns true if the task is cancelled */ boolean isCancelled(); /** * Update the expiration time of the (partial) response. */ void setExpirationTime(long expirationTimeMillis); /** * Performs necessary checks, cancels the task and calls the runnable upon completion */ void cancelTask(TaskManager taskManager, Runnable runnable, String reason); }
AsyncTask
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/loading/multiLoad/MultiLoadSecondLlvCacheTest.java
{ "start": 2657, "end": 2942 }
class ____ { @Id private Integer id; @Basic private String text; public Event() { } public Event(Integer id, String text) { this.id = id; this.text = text; } public Integer getId() { return id; } public String getText() { return text; } } }
Event
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TestInstanceFactoryTests.java
{ "start": 19869, "end": 20117 }
class ____ { @Test void testShouldNotBeCalled() { callSequence.add("testShouldNotBeCalled"); } } @SuppressWarnings("JUnitMalformedDeclaration") @ExtendWith(NullTestInstanceFactory.class) static
MultipleFactoriesRegisteredOnSingleTestCase
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/runtime/ThreadPoolConfig.java
{ "start": 527, "end": 3016 }
interface ____ { /** * The core thread pool size. This number of threads will always be kept alive. */ @WithDefault("1") int coreThreads(); /** * Prefill core thread pool. * The core thread pool will be initialised with the core number of threads at startup */ @WithDefault("true") boolean prefill(); /** * The maximum number of threads. If this is not specified then * it will be automatically sized to the greatest of 8 * the number of available processors and 200. * For example if there are 4 processors the max threads will be 200. * If there are 48 processors it will be 384. */ OptionalInt maxThreads(); /** * The queue size. For most applications this should be unbounded */ OptionalInt queueSize(); /** * The executor growth resistance. * <p> * A resistance factor applied after the core pool is full; values applied here will cause that fraction * of submissions to create new threads when no idle thread is available. A value of {@code 0.0f} implies that * threads beyond the core size should be created as aggressively as threads within it; a value of {@code 1.0f} * implies that threads beyond the core size should never be created. */ @WithDefault("0.0") float growthResistance(); /** * The shutdown timeout. If all pending work has not been completed by this time * then additional threads will be spawned to attempt to finish any pending tasks, and the shutdown process will * continue */ @WithDefault("1M") Duration shutdownTimeout(); /** * The amount of time to wait for thread pool shutdown before tasks should be interrupted. If this value is * greater than or equal to the value for {@link #shutdownTimeout}, then tasks will not be interrupted before * the shutdown timeout occurs. */ @WithDefault("10") Duration shutdownInterrupt(); /** * The frequency at which the status of the thread pool should be checked during shutdown. Information about * waiting tasks and threads will be checked and possibly logged at this interval. Setting this key to an empty * value disables the shutdown check interval. */ @WithDefault("5") Optional<Duration> shutdownCheckInterval(); /** * The amount of time a thread will stay alive with no work. */ @WithDefault("30") Duration keepAliveTime(); }
ThreadPoolConfig
java
alibaba__nacos
core/src/main/java/com/alibaba/nacos/core/remote/tls/RpcServerSslContextRefresherHolder.java
{ "start": 1278, "end": 4737 }
class ____ { /** * The instance of {@link RpcServerSslContextRefresher} for SDK communication. */ private static RpcServerSslContextRefresher sdkInstance; /** * The instance of {@link RpcServerSslContextRefresher} for Cluster communication. */ private static RpcServerSslContextRefresher clusterInstance; static { init(); } /** * Gets the instance of {@link RpcServerSslContextRefresher} for SDK communication. * * @return The instance of {@link RpcServerSslContextRefresher} for SDK communication. */ public static RpcServerSslContextRefresher getSdkInstance() { return sdkInstance; } /** * Gets the instance of {@link RpcServerSslContextRefresher} for Cluster communication. * * @return The instance of {@link RpcServerSslContextRefresher} for Cluster communication. */ public static RpcServerSslContextRefresher getClusterInstance() { return clusterInstance; } /** * Initializes the holder by loading SSL context refreshers and matching them with the configured types (SDK and * Cluster). */ private static void init() { synchronized (RpcServerSslContextRefresherHolder.class) { Properties properties = EnvUtil.getProperties(); RpcServerTlsConfig clusterServerTlsConfig = RpcServerTlsConfigFactory.getInstance().createClusterConfig(properties); RpcServerTlsConfig sdkServerTlsConfig = RpcServerTlsConfigFactory.getInstance().createSdkConfig(properties); Collection<RpcServerSslContextRefresher> refreshers = NacosServiceLoader.load( RpcServerSslContextRefresher.class); sdkInstance = getSslContextRefresher(refreshers, sdkServerTlsConfig); clusterInstance = getSslContextRefresher(refreshers, clusterServerTlsConfig); Loggers.REMOTE.info("RpcServerSslContextRefresher initialization completed."); } } /** * Initializes the SSL context refresher instance based on the specified configuration. * * @param refreshers Collection of SSL context refreshers to choose from. * @param serverTlsConfig Configuration instance for the SSL context refresher. * @return The instance of {@link RpcServerSslContextRefresher}. */ private static RpcServerSslContextRefresher getSslContextRefresher( Collection<RpcServerSslContextRefresher> refreshers, RpcServerTlsConfig serverTlsConfig) { String refresherName = serverTlsConfig.getSslContextRefresher(); RpcServerSslContextRefresher instance = null; if (StringUtils.isNotBlank(refresherName)) { for (RpcServerSslContextRefresher contextRefresher : refreshers) { if (refresherName.equals(contextRefresher.getName())) { instance = contextRefresher; Loggers.REMOTE.info("RpcServerSslContextRefresher initialized using {}.", contextRefresher.getClass().getSimpleName()); break; } } if (instance == null) { Loggers.REMOTE.warn("Failed to find RpcServerSslContextRefresher with name {}.", refresherName); } } else { Loggers.REMOTE.info("Ssl Context auto refresh is not supported."); } return instance; } }
RpcServerSslContextRefresherHolder
java
apache__rocketmq
openmessaging/src/main/java/io/openmessaging/rocketmq/config/ClientConfig.java
{ "start": 950, "end": 5752 }
class ____ implements OMSBuiltinKeys, NonStandardKeys { private String driverImpl; private String accessPoints; private String namespace; private String producerId; private String consumerId; private int operationTimeout = 5000; private String region; private String routingSource; private String routingDestination; private String routingExpression; private String rmqConsumerGroup; private String rmqProducerGroup = "__OMS_PRODUCER_DEFAULT_GROUP"; private int rmqMaxRedeliveryTimes = 16; private int rmqMessageConsumeTimeout = 15; //In minutes private int rmqMaxConsumeThreadNums = 64; private int rmqMinConsumeThreadNums = 20; private String rmqMessageDestination; private int rmqPullMessageBatchNums = 32; private int rmqPullMessageCacheCapacity = 1000; public String getDriverImpl() { return driverImpl; } public void setDriverImpl(final String driverImpl) { this.driverImpl = driverImpl; } public String getAccessPoints() { return accessPoints; } public void setAccessPoints(final String accessPoints) { this.accessPoints = accessPoints; } public String getNamespace() { return namespace; } public void setNamespace(final String namespace) { this.namespace = namespace; } public String getProducerId() { return producerId; } public void setProducerId(final String producerId) { this.producerId = producerId; } public String getConsumerId() { return consumerId; } public void setConsumerId(final String consumerId) { this.consumerId = consumerId; } public int getOperationTimeout() { return operationTimeout; } public void setOperationTimeout(final int operationTimeout) { this.operationTimeout = operationTimeout; } public String getRoutingSource() { return routingSource; } public void setRoutingSource(final String routingSource) { this.routingSource = routingSource; } public String getRmqConsumerGroup() { return rmqConsumerGroup; } public void setRmqConsumerGroup(final String rmqConsumerGroup) { this.rmqConsumerGroup = rmqConsumerGroup; } public String getRmqProducerGroup() { return rmqProducerGroup; } public void setRmqProducerGroup(final String rmqProducerGroup) { this.rmqProducerGroup = rmqProducerGroup; } public int getRmqMaxRedeliveryTimes() { return rmqMaxRedeliveryTimes; } public void setRmqMaxRedeliveryTimes(final int rmqMaxRedeliveryTimes) { this.rmqMaxRedeliveryTimes = rmqMaxRedeliveryTimes; } public int getRmqMessageConsumeTimeout() { return rmqMessageConsumeTimeout; } public void setRmqMessageConsumeTimeout(final int rmqMessageConsumeTimeout) { this.rmqMessageConsumeTimeout = rmqMessageConsumeTimeout; } public int getRmqMaxConsumeThreadNums() { return rmqMaxConsumeThreadNums; } public void setRmqMaxConsumeThreadNums(final int rmqMaxConsumeThreadNums) { this.rmqMaxConsumeThreadNums = rmqMaxConsumeThreadNums; } public int getRmqMinConsumeThreadNums() { return rmqMinConsumeThreadNums; } public void setRmqMinConsumeThreadNums(final int rmqMinConsumeThreadNums) { this.rmqMinConsumeThreadNums = rmqMinConsumeThreadNums; } public String getRmqMessageDestination() { return rmqMessageDestination; } public void setRmqMessageDestination(final String rmqMessageDestination) { this.rmqMessageDestination = rmqMessageDestination; } public int getRmqPullMessageBatchNums() { return rmqPullMessageBatchNums; } public void setRmqPullMessageBatchNums(final int rmqPullMessageBatchNums) { this.rmqPullMessageBatchNums = rmqPullMessageBatchNums; } public int getRmqPullMessageCacheCapacity() { return rmqPullMessageCacheCapacity; } public void setRmqPullMessageCacheCapacity(final int rmqPullMessageCacheCapacity) { this.rmqPullMessageCacheCapacity = rmqPullMessageCacheCapacity; } public String getRegion() { return region; } public void setRegion(String region) { this.region = region; } public String getRoutingDestination() { return routingDestination; } public void setRoutingDestination(String routingDestination) { this.routingDestination = routingDestination; } public String getRoutingExpression() { return routingExpression; } public void setRoutingExpression(String routingExpression) { this.routingExpression = routingExpression; } }
ClientConfig
java
apache__kafka
tools/src/test/java/org/apache/kafka/tools/consumer/group/DeleteOffsetsConsumerGroupCommandIntegrationTest.java
{ "start": 3554, "end": 13992 }
class ____ { public static final String TOPIC_PREFIX = "foo."; public static final String GROUP_PREFIX = "test.group."; private final ClusterInstance clusterInstance; DeleteOffsetsConsumerGroupCommandIntegrationTest(ClusterInstance clusterInstance) { this.clusterInstance = clusterInstance; } @ClusterTest public void testDeleteOffsetsNonExistingGroup() { String group = "missing.group"; String topic = "foo:1"; try (ConsumerGroupCommand.ConsumerGroupService consumerGroupService = consumerGroupService(getArgs(group, topic))) { Entry<Errors, Map<TopicPartition, Throwable>> res = consumerGroupService.deleteOffsets(group, List.of(topic)); assertEquals(Errors.GROUP_ID_NOT_FOUND, res.getKey()); } } @ClusterTest public void testDeleteOffsetsOfStableConsumerGroupWithTopicPartition() { for (GroupProtocol groupProtocol : clusterInstance.supportedGroupProtocols()) { String topic = TOPIC_PREFIX + groupProtocol.name(); String group = GROUP_PREFIX + groupProtocol.name(); createTopic(topic); Runnable validateRunnable = getValidateRunnable(topic, group, 0, 0, Errors.GROUP_SUBSCRIBED_TO_TOPIC); testWithConsumerGroup(topic, group, groupProtocol, true, validateRunnable); removeTopic(topic); } } @ClusterTest public void testDeleteOffsetsOfStableConsumerGroupWithTopicOnly() { for (GroupProtocol groupProtocol : clusterInstance.supportedGroupProtocols()) { String topic = TOPIC_PREFIX + groupProtocol.name(); String group = GROUP_PREFIX + groupProtocol.name(); createTopic(topic); Runnable validateRunnable = getValidateRunnable(topic, group, -1, 0, Errors.GROUP_SUBSCRIBED_TO_TOPIC); testWithConsumerGroup(topic, group, groupProtocol, true, validateRunnable); removeTopic(topic); } } @ClusterTest public void testDeleteOffsetsOfStableConsumerGroupWithUnknownTopicPartition() { for (GroupProtocol groupProtocol : clusterInstance.supportedGroupProtocols()) { String topic = TOPIC_PREFIX + groupProtocol.name(); String group = GROUP_PREFIX + groupProtocol.name(); Runnable validateRunnable = getValidateRunnable("foobar", group, 0, 0, Errors.UNKNOWN_TOPIC_OR_PARTITION); testWithConsumerGroup(topic, group, groupProtocol, true, validateRunnable); } } @ClusterTest public void testDeleteOffsetsOfStableConsumerGroupWithUnknownTopicOnly() { for (GroupProtocol groupProtocol : clusterInstance.supportedGroupProtocols()) { String topic = TOPIC_PREFIX + groupProtocol.name(); String group = GROUP_PREFIX + groupProtocol.name(); Runnable validateRunnable = getValidateRunnable("foobar", group, -1, -1, Errors.UNKNOWN_TOPIC_OR_PARTITION); testWithConsumerGroup(topic, group, groupProtocol, true, validateRunnable); } } @ClusterTest public void testDeleteOffsetsOfEmptyConsumerGroupWithTopicPartition() { for (GroupProtocol groupProtocol : clusterInstance.supportedGroupProtocols()) { String topic = TOPIC_PREFIX + groupProtocol.name(); String group = GROUP_PREFIX + groupProtocol.name(); createTopic(topic); Runnable validateRunnable = getValidateRunnable(topic, group, 0, 0, Errors.NONE); testWithConsumerGroup(topic, group, groupProtocol, false, validateRunnable); removeTopic(topic); } } @ClusterTest public void testDeleteOffsetsOfEmptyConsumerGroupWithTopicOnly() { for (GroupProtocol groupProtocol : clusterInstance.supportedGroupProtocols()) { String topic = TOPIC_PREFIX + groupProtocol.name(); String group = GROUP_PREFIX + groupProtocol.name(); createTopic(topic); Runnable validateRunnable = getValidateRunnable(topic, group, -1, 0, Errors.NONE); testWithConsumerGroup(topic, group, groupProtocol, false, validateRunnable); removeTopic(topic); } } @ClusterTest public void testDeleteOffsetsOfEmptyConsumerGroupWithUnknownTopicPartition() { for (GroupProtocol groupProtocol : clusterInstance.supportedGroupProtocols()) { String topic = TOPIC_PREFIX + groupProtocol.name(); String group = GROUP_PREFIX + groupProtocol.name(); Runnable validateRunnable = getValidateRunnable("foobar", group, 0, 0, Errors.UNKNOWN_TOPIC_OR_PARTITION); testWithConsumerGroup(topic, group, groupProtocol, false, validateRunnable); } } @ClusterTest public void testDeleteOffsetsOfEmptyConsumerGroupWithUnknownTopicOnly() { for (GroupProtocol groupProtocol : clusterInstance.supportedGroupProtocols()) { String topic = TOPIC_PREFIX + groupProtocol.name(); String group = GROUP_PREFIX + groupProtocol.name(); Runnable validateRunnable = getValidateRunnable("foobar", group, -1, -1, Errors.UNKNOWN_TOPIC_OR_PARTITION); testWithConsumerGroup(topic, group, groupProtocol, false, validateRunnable); } } private String[] getArgs(String group, String topic) { return new String[] { "--bootstrap-server", clusterInstance.bootstrapServers(), "--delete-offsets", "--group", group, "--topic", topic }; } private static ConsumerGroupCommand.ConsumerGroupService consumerGroupService(String[] args) { return new ConsumerGroupCommand.ConsumerGroupService( ConsumerGroupCommandOptions.fromArgs(args), Map.of(AdminClientConfig.RETRIES_CONFIG, Integer.toString(Integer.MAX_VALUE)) ); } private Runnable getValidateRunnable(String inputTopic, String inputGroup, int inputPartition, int expectedPartition, Errors expectedError) { return () -> { String topic = inputPartition >= 0 ? inputTopic + ":" + inputPartition : inputTopic; try (ConsumerGroupCommand.ConsumerGroupService consumerGroupService = consumerGroupService(getArgs(inputGroup, topic))) { Entry<Errors, Map<TopicPartition, Throwable>> res = consumerGroupService.deleteOffsets(inputGroup, List.of(topic)); Errors topLevelError = res.getKey(); Map<TopicPartition, Throwable> partitions = res.getValue(); TopicPartition tp = new TopicPartition(inputTopic, expectedPartition); // Partition level error should propagate to top level, unless this is due to a missed partition attempt. if (inputPartition >= 0) { assertEquals(expectedError, topLevelError); } if (expectedError == Errors.NONE) assertNull(partitions.get(tp)); else assertEquals(expectedError.exception(), partitions.get(tp).getCause()); } }; } private void testWithConsumerGroup(String inputTopic, String inputGroup, GroupProtocol groupProtocol, boolean isStable, Runnable validateRunnable) { produceRecord(inputTopic); try (Consumer<byte[], byte[]> consumer = createConsumer(inputGroup, groupProtocol)) { consumer.subscribe(List.of(inputTopic)); ConsumerRecords<byte[], byte[]> records = consumer.poll(Duration.ofMillis(DEFAULT_MAX_WAIT_MS)); Assertions.assertNotEquals(0, records.count()); consumer.commitSync(); if (isStable) { validateRunnable.run(); } } if (!isStable) { validateRunnable.run(); } } private void produceRecord(String topic) { try (Producer<byte[], byte[]> producer = createProducer()) { assertDoesNotThrow(() -> producer.send(new ProducerRecord<>(topic, 0, null, null)).get()); } } private Producer<byte[], byte[]> createProducer() { return clusterInstance.producer(Map.of(ProducerConfig.ACKS_CONFIG, "-1")); } private Consumer<byte[], byte[]> createConsumer(String group, GroupProtocol groupProtocol) { Map<String, Object> consumerConfig = new HashMap<>(); consumerConfig.putIfAbsent(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, clusterInstance.bootstrapServers()); consumerConfig.putIfAbsent(ConsumerConfig.GROUP_PROTOCOL_CONFIG, groupProtocol.name()); consumerConfig.putIfAbsent(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest"); consumerConfig.putIfAbsent(ConsumerConfig.GROUP_ID_CONFIG, group); consumerConfig.putIfAbsent(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); consumerConfig.putIfAbsent(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ByteArrayDeserializer.class.getName()); // Increase timeouts to avoid having a rebalance during the test consumerConfig.putIfAbsent(ConsumerConfig.MAX_POLL_INTERVAL_MS_CONFIG, Integer.toString(Integer.MAX_VALUE)); if (groupProtocol == GroupProtocol.CLASSIC) { consumerConfig.putIfAbsent(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, Integer.toString(GroupCoordinatorConfig.GROUP_MAX_SESSION_TIMEOUT_MS_DEFAULT)); } return new KafkaConsumer<>(consumerConfig); } private void createTopic(String topic) { try (Admin admin = Admin.create(Map.of(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, clusterInstance.bootstrapServers()))) { Assertions.assertDoesNotThrow(() -> admin.createTopics(List.of(new NewTopic(topic, 1, (short) 1))).topicId(topic).get()); } } private void removeTopic(String topic) { try (Admin admin = Admin.create(Map.of(CommonClientConfigs.BOOTSTRAP_SERVERS_CONFIG, clusterInstance.bootstrapServers()))) { Assertions.assertDoesNotThrow(() -> admin.deleteTopics(List.of(topic)).all()); } } }
DeleteOffsetsConsumerGroupCommandIntegrationTest
java
quarkusio__quarkus
independent-projects/tools/analytics-common/src/test/java/io/quarkus/analytics/AnalyticsServiceTest.java
{ "start": 3141, "end": 9292 }
class ____ extends AnalyticsServiceTestBase { private static final int MOCK_SERVER_PORT = 9300; private static final String TEST_CONFIG_URL = "http://localhost:" + MOCK_SERVER_PORT + "/" + "config"; private static final WireMockServer wireMockServer = new WireMockServer(MOCK_SERVER_PORT); private static FileLocations FILE_LOCATIONS; @BeforeAll static void start() throws IOException { FILE_LOCATIONS = new TestFileLocationsImpl(); System.setProperty("quarkus.analytics.uri.base", "http://localhost:" + MOCK_SERVER_PORT + "/"); wireMockServer.start(); wireMockServer.stubFor(post(urlEqualTo("/v1/identify")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\"status\":\"ok\"}"))); wireMockServer.stubFor(post(urlEqualTo("/v1/track")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") .withBody("{\"status\":\"ok\"}"))); wireMockServer.stubFor(get(urlEqualTo("/config")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/json") // .withBody(getObjectMapper().writeValueAsString(createRemoteConfig())))); .withBody( "{\"active\":true,\"deny_anonymous_ids\":[],\"deny_quarkus_versions\":[],\"refresh_interval\":43200.000000000}"))); } @AfterAll static void stop() throws IOException { wireMockServer.stop(); System.clearProperty("quarkus.analytics.uri.base"); ((TestFileLocationsImpl) FILE_LOCATIONS).deleteAll(); } @Test @SuppressWarnings("unchecked") void createContext() throws IOException { AnalyticsService service = new AnalyticsService(FILE_LOCATIONS, MessageWriter.info()); final Map<String, Object> contextMap = service.createContextMap( mockApplicationModel(), Map.of(GRAALVM_VERSION_DISTRIBUTION, "Company name", GRAALVM_VERSION_VERSION, "20.2.0", GRAALVM_VERSION_JAVA, "17.0.0", MAVEN_VERSION, "3.9.0", GRADLE_VERSION, "8.0.1")); assertNotNull(contextMap); final Map app = (Map) contextMap.get(PROP_APP); assertNotNull(app); assertEquals("yRAqgUsoDknuOICn/0zeC14YwZYAxPxcycCw6MgGYfI=", app.get(PROP_NAME)); assertEquals("Uue4h73VUgajaMLTPcYAM4Fo+YAZx4LQ0OEdaBbQTtg=", app.get(PROP_VERSION)); assertMapEntriesNotEmpty(1, (Map) contextMap.get(PROP_KUBERNETES)); assertMapEntriesNotEmpty(1, (Map) contextMap.get(PROP_CI)); final Map java = (Map) contextMap.get(PROP_JAVA); assertNotNull(java); assertNotNull(java.get(PROP_VENDOR)); assertNotNull(java.get(PROP_VERSION)); assertMapEntriesNotEmpty(3, (Map) contextMap.get(PROP_OS)); final Map build = (Map) contextMap.get(PROP_BUILD); assertNotNull(build); // in reality, these are not both set at the same time, but we set them in the test assertEquals("3.9.0", build.get(PROP_MAVEN_VERSION)); assertEquals("8.0.1", build.get(PROP_GRADLE_VERSION)); final Map graalvm = (Map) contextMap.get(PROP_GRAALVM); assertNotNull(graalvm); assertEquals("Company name", graalvm.get(PROP_VENDOR)); assertEquals("20.2.0", graalvm.get(PROP_VERSION)); assertEquals("17.0.0", graalvm.get(PROP_JAVA_VERSION)); assertNotNull(contextMap.get("timezone")); assertMapEntriesNotEmpty(1, (Map) contextMap.get(PROP_QUARKUS)); assertEquals("0.0.0.0", contextMap.get(PROP_IP)); assertNotNull(contextMap.get(PROP_LOCATION)); } @Test void createExtensionsPropertyValue() { AnalyticsService service = new AnalyticsService(FILE_LOCATIONS, MessageWriter.info()); List<TrackProperties.AppExtension> extensionsPropertyValue = service .createExtensionsPropertyValue(mockApplicationModel()); assertNotNull(extensionsPropertyValue); assertEquals(2, extensionsPropertyValue.size()); assertEquals(Set.of("quarkus-openapi", "quarkus-opentelemetry-jaeger"), extensionsPropertyValue.stream() .map(TrackProperties.AppExtension::getArtifactId) .collect(Collectors.toSet())); } @Test void sendAnalyticsTest() throws IOException { AnalyticsService service = new AnalyticsService(FILE_LOCATIONS, MessageWriter.info()); service.sendAnalytics(TrackEventType.BUILD, mockApplicationModel(), Map.of(), new File(FILE_LOCATIONS.getFolder().toUri())); service.close(); await().atMost(5, TimeUnit.SECONDS) .untilAsserted(() -> wireMockServer.verify(1, postRequestedFor(urlEqualTo("/v1/track")))); wireMockServer.verify(postRequestedFor(urlEqualTo("/v1/track")) .withRequestBody(notMatching("null"))); assertTrue(new File(FILE_LOCATIONS.getFolder().toString() + "/" + FILE_LOCATIONS.lastTrackFileName()).exists()); } @Test void nullLogger() { AnalyticsService service = new AnalyticsService(FILE_LOCATIONS, null); assertNotNull(service); service.sendAnalytics(TrackEventType.BUILD, mockApplicationModel(), Map.of(), new File(FILE_LOCATIONS.getFolder().toUri())); } private void assertMapEntriesNotEmpty(int size, Map<String, Object> map) { assertNotNull(map); assertEquals(size, map.size()); map.entrySet().forEach(entry -> { assertNotNull(entry.getValue()); assertFalse(entry.getValue().toString().isEmpty(), entry.toString() + " value is empty"); }); } }
AnalyticsServiceTest
java
apache__hadoop
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/ReduceTaskAttemptInfo.java
{ "start": 1038, "end": 3009 }
class ____ extends TaskAttemptInfo { private long shuffleTime; private long mergeTime; private long reduceTime; public ReduceTaskAttemptInfo(State state, TaskInfo taskInfo, long shuffleTime, long mergeTime, long reduceTime, List<List<Integer>> allSplits) { super(state, taskInfo, allSplits == null ? LoggedTaskAttempt.SplitVectorKind.getNullSplitsVector() : allSplits); this.shuffleTime = shuffleTime; this.mergeTime = mergeTime; this.reduceTime = reduceTime; } /** * * @deprecated please use the constructor with * {@code (state, taskInfo, shuffleTime, mergeTime, reduceTime * List<List<Integer>> allSplits)} * instead. * * see {@link LoggedTaskAttempt} for an explanation of * {@code allSplits}. * * If there are no known splits, use {@code null}. */ @Deprecated public ReduceTaskAttemptInfo(State state, TaskInfo taskInfo, long shuffleTime, long mergeTime, long reduceTime) { this(state, taskInfo, shuffleTime, mergeTime, reduceTime, null); } /** * Get the runtime for the <b>reduce</b> phase of the reduce task-attempt. * * @return the runtime for the <b>reduce</b> phase of the reduce task-attempt */ public long getReduceRuntime() { return reduceTime; } /** * Get the runtime for the <b>shuffle</b> phase of the reduce task-attempt. * * @return the runtime for the <b>shuffle</b> phase of the reduce task-attempt */ public long getShuffleRuntime() { return shuffleTime; } /** * Get the runtime for the <b>merge</b> phase of the reduce task-attempt * * @return the runtime for the <b>merge</b> phase of the reduce task-attempt */ public long getMergeRuntime() { return mergeTime; } @Override public long getRuntime() { return (getShuffleRuntime() + getMergeRuntime() + getReduceRuntime()); } }
ReduceTaskAttemptInfo
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/legacy/factories/TableSinkFactory.java
{ "start": 1882, "end": 3594 }
interface ____<T> extends TableFactory { /** * Creates and configures a {@link TableSink} using the given properties. * * @param properties normalized properties describing a table sink. * @return the configured table sink. * @deprecated {@link Context} contains more information, and already contains table schema too. * Please use {@link #createTableSink(Context)} instead. */ @Deprecated default TableSink<T> createTableSink(Map<String, String> properties) { return null; } /** * Creates and configures a {@link TableSink} based on the given {@link CatalogTable} instance. * * @param tablePath path of the given {@link CatalogTable} * @param table {@link CatalogTable} instance. * @return the configured table sink. * @deprecated {@link Context} contains more information, and already contains table schema too. * Please use {@link #createTableSink(Context)} instead. */ @Deprecated default TableSink<T> createTableSink(ObjectPath tablePath, CatalogTable table) { return createTableSink( ((ResolvedCatalogTable) table).toProperties(DefaultSqlFactory.INSTANCE)); } /** * Creates and configures a {@link TableSink} based on the given {@link Context}. * * @param context context of this table sink. * @return the configured table sink. */ default TableSink<T> createTableSink(Context context) { return createTableSink(context.getObjectIdentifier().toObjectPath(), context.getTable()); } /** Context of table sink creation. Contains table information and environment information. */ @Internal
TableSinkFactory