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__camel
components/camel-iec60870/src/test/java/org/apache/camel/component/iec60870/ConnectionTest.java
{ "start": 1828, "end": 6149 }
class ____ extends CamelTestSupport { private static final Logger LOG = LoggerFactory.getLogger(ConnectionTest.class); private static final String DIRECT_SEND_S_1 = "direct:sendServer1"; private static final String DIRECT_SEND_C_1 = "direct:sendClient1"; private static final String MOCK_CLIENT_1 = "mock:testClient1"; private static final String MOCK_CLIENT_2 = "mock:testClient2"; private static final String MOCK_SERVER_1 = "mock:testServer1"; @Produce(DIRECT_SEND_S_1) protected ProducerTemplate producerServer1; @Produce(DIRECT_SEND_C_1) protected ProducerTemplate producerClient1; @EndpointInject(MOCK_CLIENT_1) protected MockEndpoint testClient1Endpoint; @EndpointInject(MOCK_CLIENT_2) protected MockEndpoint testClient2Endpoint; @EndpointInject(MOCK_SERVER_1) protected MockEndpoint testServer1Endpoint; @Override protected RoutesBuilder createRouteBuilder() { final int port = AvailablePortFinder.getNextAvailable(); return new RouteBuilder() { @Override public void configure() { from(DIRECT_SEND_S_1).toF("iec60870-server:localhost:%s/00-00-00-00-01", port); fromF("iec60870-client:localhost:%s/00-00-00-00-01", port).to(MOCK_CLIENT_1); fromF("iec60870-client:localhost:%s/00-00-00-00-02", port).to(MOCK_CLIENT_2); from(DIRECT_SEND_C_1).toF("iec60870-client:localhost:%s/00-00-00-01-01", port); fromF("iec60870-server:localhost:%s/00-00-00-01-01", port).to(MOCK_SERVER_1); } }; } @Test public void testFloat1() throws InterruptedException { this.producerServer1.sendBody(1.23f); // expect - count this.testClient1Endpoint.setExpectedCount(1); this.testClient2Endpoint.setExpectedCount(0); // expect expectValue(testClient1Endpoint.message(0), assertGoodValue(1.23f)); // assert MockEndpoint.assertIsSatisfied(context, 1_000, TimeUnit.MILLISECONDS); } @Test public void testBoolean1() throws InterruptedException { this.producerServer1.sendBody(true); // expect - count this.testClient1Endpoint.setExpectedCount(1); this.testClient2Endpoint.setExpectedCount(0); // expect expectValue(testClient1Endpoint.message(0), assertGoodValue(true)); // assert MockEndpoint.assertIsSatisfied(context, 1_000, TimeUnit.MILLISECONDS); } @Test public void testCommand1() throws InterruptedException { this.producerClient1.sendBody(true); // expect - count this.testServer1Endpoint.setExpectedCount(1); // expect expectRequest(testServer1Endpoint.message(0), expectRequest(true)); // assert MockEndpoint.assertIsSatisfied(context, 2_000, TimeUnit.MILLISECONDS); LOG.debug("Received body: {}", testServer1Endpoint.getExchanges().get(0).getIn().getBody()); } private <T> void expectValue(AssertionClause message, Consumer<Value<?>> consumer) { message.predicate(exchange -> { final Value<?> body = exchange.getIn().getBody(Value.class); consumer.accept(body); return true; }); } private <T> void expectRequest(AssertionClause message, Consumer<Request<?>> consumer) { message.predicate(exchange -> { final Request<?> body = exchange.getIn().getBody(Request.class); consumer.accept(body); return true; }); } public static Consumer<Value<?>> assertGoodValue(final Object expectedValue) { return value -> { assertNotNull(value); assertEquals(expectedValue, value.getValue()); assertTrue(value.getQualityInformation().isValid()); assertTrue(value.getQualityInformation().isTopical()); assertFalse(value.getQualityInformation().isBlocked()); assertFalse(value.getQualityInformation().isSubstituted()); }; } private Consumer<Request<?>> expectRequest(final Object expectedValue) { return value -> { assertNotNull(value); assertEquals(expectedValue, value.getValue()); }; } }
ConnectionTest
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/decorators/generics/MultipleDecoratorsWithTypeVariablesTest.java
{ "start": 3069, "end": 3348 }
class ____ implements Supplier<String> { @Inject @Delegate Supplier<String> delegate; @Override public String get() { return delegate.get() + "_Foo"; } } @Priority(2) @Decorator static
SupplierDecorator1
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng0848UserPropertyOverridesDefaultValueTest.java
{ "start": 1132, "end": 2123 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Test that execution/system properties take precedence over default value of plugin parameters. * * @throws Exception in case of failure */ @Test public void testitMNG848() throws Exception { File testDir = extractResources("/mng-0848"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.addCliArgument("-Dconfig.aliasDefaultExpressionParam=PASSED"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); Properties configProps = verifier.loadProperties("target/config.properties"); assertEquals("maven-core-it", configProps.getProperty("defaultParam")); assertEquals("PASSED", configProps.getProperty("aliasDefaultExpressionParam")); } }
MavenITmng0848UserPropertyOverridesDefaultValueTest
java
google__error-prone
core/src/test/java/com/google/errorprone/testdata/MultipleTopLevelClassesWithNoErrors.java
{ "start": 851, "end": 878 }
class ____ {} } final
InnerFoo
java
elastic__elasticsearch
x-pack/plugin/ml/qa/native-multi-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/MlInitializationServiceIT.java
{ "start": 1889, "end": 10769 }
class ____ extends MlNativeAutodetectIntegTestCase { private MlInitializationService mlInitializationService; @Before public void setUpMocks() { final var threadPool = mock(ThreadPool.class); when(threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME)).thenReturn(EsExecutors.DIRECT_EXECUTOR_SERVICE); MlDailyMaintenanceService mlDailyMaintenanceService = mock(MlDailyMaintenanceService.class); ClusterService clusterService = mock(ClusterService.class); AdaptiveAllocationsScalerService adaptiveAllocationsScalerService = mock(AdaptiveAllocationsScalerService.class); mlInitializationService = new MlInitializationService( client(), threadPool, mlDailyMaintenanceService, adaptiveAllocationsScalerService, clusterService ); } public void testThatMlIndicesBecomeHiddenWhenTheNodeBecomesMaster() throws Exception { List<String> mlHiddenIndexNames = List.of( ".ml-anomalies-7", ".ml-state-000001", ".ml-stats-000001", ".ml-notifications-000002", ".ml-annotations-000001" ); List<String> otherIndexNames = List.of("some-index-1", "some-other-index-2"); List<String> allIndexNames = Stream.concat(mlHiddenIndexNames.stream(), otherIndexNames.stream()).collect(toList()); for (String indexName : mlHiddenIndexNames) { try { createIndex(indexName, Settings.builder().put(SETTING_INDEX_HIDDEN, randomBoolean()).build()); } catch (ResourceAlreadyExistsException e) { logger.info("Index " + indexName + " already exists: {}", e.getDetailedMessage()); } } for (String indexName : otherIndexNames) { createIndex(indexName, Settings.EMPTY); } Map<String, Settings> indexToSettings = getIndexToSettingsMap(allIndexNames); for (String indexName : mlHiddenIndexNames) { assertThat(indexToSettings.get(indexName), is(notNullValue())); } for (String indexName : otherIndexNames) { Settings settings = indexToSettings.get(indexName); assertThat(settings, is(notNullValue())); assertThat( "Index " + indexName + " expected not to be hidden but was", settings.getAsBoolean(SETTING_INDEX_HIDDEN, false), is(equalTo(false)) ); } assertFalse(mlInitializationService.areMlInternalIndicesHidden()); mlInitializationService.onMaster(); assertBusy(() -> assertTrue(mlInitializationService.areMlInternalIndicesHidden())); indexToSettings = getIndexToSettingsMap(allIndexNames); for (String indexName : mlHiddenIndexNames) { Settings settings = indexToSettings.get(indexName); assertThat(settings, is(notNullValue())); assertThat( "Index " + indexName + " expected to be hidden but wasn't, settings = " + settings, settings.getAsBoolean(SETTING_INDEX_HIDDEN, false), is(equalTo(true)) ); } for (String indexName : otherIndexNames) { Settings settings = indexToSettings.get(indexName); assertThat(settings, is(notNullValue())); assertThat( "Index " + indexName + " expected not to be hidden but was, settings = " + settings, settings.getAsBoolean(SETTING_INDEX_HIDDEN, false), is(equalTo(false)) ); } } public void testThatMlAliasesBecomeHiddenWhenTheNodeBecomesMaster() throws Exception { List<String> mlHiddenIndexNames = List.of( ".ml-anomalies-7", ".ml-state-000001", ".ml-stats-000001", ".ml-notifications-000002", ".ml-annotations-000001" ); for (String indexName : mlHiddenIndexNames) { try { createIndex(indexName, Settings.builder().put(SETTING_INDEX_HIDDEN, randomBoolean()).build()); } catch (ResourceAlreadyExistsException e) { logger.info("Index " + indexName + " already exists: {}", e.getDetailedMessage()); } } IndicesAliasesRequest indicesAliasesRequest = new IndicesAliasesRequest(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT).addAliasAction( IndicesAliasesRequest.AliasActions.add().index(".ml-anomalies-7").alias(".ml-anomalies-write").writeIndex(true) ) .addAliasAction( IndicesAliasesRequest.AliasActions.add() .index(".ml-state-000001") .alias(".ml-state-write") .filter(QueryBuilders.termQuery("a", "b")) ) .addAliasAction( IndicesAliasesRequest.AliasActions.add() .index(".ml-stats-000001") .alias(".ml-stats-write") .indexRouting("some-index-routing") ) .addAliasAction( IndicesAliasesRequest.AliasActions.add() .index(".ml-notifications-000002") .alias(".ml-notifications-write") .searchRouting("some-search-routing") ) .addAliasAction( IndicesAliasesRequest.AliasActions.add() .index(".ml-annotations-000001") .alias(".ml-annotations-write") .writeIndex(true) .filter(QueryBuilders.termQuery("a", "b")) .indexRouting("some-index-routing") .searchRouting("some-search-routing") ); assertAcked(client().admin().indices().aliases(indicesAliasesRequest).get()); assertFalse(mlInitializationService.areMlInternalIndicesHidden()); mlInitializationService.onMaster(); assertBusy(() -> assertTrue(mlInitializationService.areMlInternalIndicesHidden())); Map<String, List<AliasMetadata>> indexToAliasesMap = getIndexToAliasesMap(mlHiddenIndexNames); assertThat("Aliases were: " + indexToAliasesMap, indexToAliasesMap.size(), is(equalTo(5))); assertThat( indexToAliasesMap.get(".ml-anomalies-7"), contains(AliasMetadata.builder(".ml-anomalies-write").isHidden(true).writeIndex(true).build()) ); assertThat( indexToAliasesMap.get(".ml-state-000001"), contains(AliasMetadata.builder(".ml-state-write").isHidden(true).filter(QueryBuilders.termQuery("a", "b").toString()).build()) ); assertThat( indexToAliasesMap.get(".ml-stats-000001"), contains(AliasMetadata.builder(".ml-stats-write").isHidden(true).indexRouting("some-index-routing").build()) ); assertThat( indexToAliasesMap.get(".ml-notifications-000002"), contains(AliasMetadata.builder(".ml-notifications-write").isHidden(true).searchRouting("some-search-routing").build()) ); assertThat( indexToAliasesMap.get(".ml-annotations-000001"), contains( AliasMetadata.builder(".ml-annotations-read").isHidden(true).build(), AliasMetadata.builder(".ml-annotations-write") .isHidden(true) .writeIndex(true) .filter(QueryBuilders.termQuery("a", "b").toString()) .indexRouting("some-index-routing") .searchRouting("some-search-routing") .build() ) ); } private static Map<String, Settings> getIndexToSettingsMap(List<String> indexNames) { GetSettingsResponse getSettingsResponse = indicesAdmin().prepareGetSettings(TEST_REQUEST_TIMEOUT) .setIndices(indexNames.toArray(String[]::new)) .setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN_CLOSED_HIDDEN) .get(); assertThat(getSettingsResponse, is(notNullValue())); return getSettingsResponse.getIndexToSettings(); } private static Map<String, List<AliasMetadata>> getIndexToAliasesMap(List<String> indexNames) { GetAliasesResponse getAliasesResponse = indicesAdmin().prepareGetAliases(TEST_REQUEST_TIMEOUT) .setIndices(indexNames.toArray(String[]::new)) .setIndicesOptions(IndicesOptions.LENIENT_EXPAND_OPEN_CLOSED_HIDDEN) .get(); assertThat(getAliasesResponse, is(notNullValue())); return getAliasesResponse.getAliases(); } @Override public Settings indexSettings() { return Settings.builder().put(super.indexSettings()).put(IndexMetadata.SETTING_DATA_PATH, (String) null).build(); } }
MlInitializationServiceIT
java
spring-projects__spring-boot
module/spring-boot-security/src/test/java/org/springframework/boot/security/autoconfigure/actuate/web/servlet/EndpointRequestTests.java
{ "start": 2536, "end": 15691 }
class ____ { @Test void toAnyEndpointShouldMatchEndpointPath() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher, "/actuator").matches("/actuator/foo"); assertMatcher(matcher, "/actuator").matches("/actuator/foo/zoo/"); assertMatcher(matcher, "/actuator").matches("/actuator/bar"); assertMatcher(matcher, "/actuator").matches("/actuator/bar/baz"); assertMatcher(matcher, "/actuator").matches("/actuator"); } @Test void toAnyEndpointWithHttpMethodShouldRespectRequestMethod() { EndpointRequest.EndpointRequestMatcher matcher = EndpointRequest.toAnyEndpoint() .withHttpMethod(HttpMethod.POST); assertMatcher(matcher, "/actuator").matches(HttpMethod.POST, "/actuator/foo"); assertMatcher(matcher, "/actuator").doesNotMatch(HttpMethod.GET, "/actuator/foo"); } @Test void toAnyEndpointShouldMatchEndpointPathWithTrailingSlash() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher, "/actuator").matches("/actuator/foo/"); assertMatcher(matcher, "/actuator").matches("/actuator/bar/"); assertMatcher(matcher, "/actuator").matches("/actuator/"); } @Test void toAnyEndpointWhenBasePathIsEmptyShouldNotMatchLinks() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); RequestMatcherAssert assertMatcher = assertMatcher(matcher, ""); assertMatcher.doesNotMatch("/"); assertMatcher.matches("/foo"); assertMatcher.matches("/bar"); } @Test void toAnyEndpointShouldNotMatchOtherPath() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher).doesNotMatch("/actuator/baz"); } @Test void toAnyEndpointWhenDispatcherServletPathProviderNotAvailableUsesEmptyPath() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher, "/actuator").matches("/actuator/foo"); assertMatcher(matcher, "/actuator").matches("/actuator/bar"); assertMatcher(matcher, "/actuator").matches("/actuator"); assertMatcher(matcher, "/actuator").doesNotMatch("/actuator/baz"); } @Test void toEndpointClassShouldMatchEndpointPath() { RequestMatcher matcher = EndpointRequest.to(FooEndpoint.class); assertMatcher(matcher).matches("/actuator/foo"); } @Test void toEndpointClassShouldNotMatchOtherPath() { RequestMatcher matcher = EndpointRequest.to(FooEndpoint.class); assertMatcher(matcher).doesNotMatch("/actuator/bar"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test void toEndpointIdShouldMatchEndpointPath() { RequestMatcher matcher = EndpointRequest.to("foo"); assertMatcher(matcher).matches("/actuator/foo"); } @Test void toEndpointIdShouldNotMatchOtherPath() { RequestMatcher matcher = EndpointRequest.to("foo"); assertMatcher(matcher).doesNotMatch("/actuator/bar"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test void toLinksShouldOnlyMatchLinks() { RequestMatcher matcher = EndpointRequest.toLinks(); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator/bar"); assertMatcher(matcher).matches("/actuator"); assertMatcher(matcher).matches("/actuator/"); } @Test void toLinksWhenBasePathEmptyShouldNotMatch() { RequestMatcher matcher = EndpointRequest.toLinks(); RequestMatcherAssert assertMatcher = assertMatcher(matcher, ""); assertMatcher.doesNotMatch("/actuator/foo"); assertMatcher.doesNotMatch("/actuator/bar"); assertMatcher.doesNotMatch("/"); } @Test void excludeByClassShouldNotMatchExcluded() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excluding(FooEndpoint.class, BazServletEndpoint.class); List<ExposableEndpoint<?>> endpoints = new ArrayList<>(); endpoints.add(mockEndpoint(EndpointId.of("foo"), "foo")); endpoints.add(mockEndpoint(EndpointId.of("bar"), "bar")); endpoints.add(mockEndpoint(EndpointId.of("baz"), "baz")); PathMappedEndpoints pathMappedEndpoints = new PathMappedEndpoints("/actuator", () -> endpoints); assertMatcher(matcher, pathMappedEndpoints).doesNotMatch("/actuator/foo"); assertMatcher(matcher, pathMappedEndpoints).doesNotMatch("/actuator/baz"); assertMatcher(matcher).matches("/actuator/bar"); assertMatcher(matcher).matches("/actuator"); } @Test void excludeByClassShouldNotMatchLinksIfExcluded() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks().excluding(FooEndpoint.class); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test void excludeByIdShouldNotMatchExcluded() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excluding("foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).matches("/actuator/bar"); assertMatcher(matcher).matches("/actuator"); } @Test void excludeByIdShouldNotMatchLinksIfExcluded() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks().excluding("foo"); assertMatcher(matcher).doesNotMatch("/actuator/foo"); assertMatcher(matcher).doesNotMatch("/actuator"); } @Test void excludeLinksShouldNotMatchBasePath() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks(); assertMatcher(matcher).doesNotMatch("/actuator"); assertMatcher(matcher).matches("/actuator/foo"); assertMatcher(matcher).matches("/actuator/bar"); } @Test void excludeLinksShouldNotMatchBasePathIfEmptyAndExcluded() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excludingLinks(); RequestMatcherAssert assertMatcher = assertMatcher(matcher, ""); assertMatcher.doesNotMatch("/"); assertMatcher.matches("/foo"); assertMatcher.matches("/bar"); } @Test void endpointRequestMatcherShouldUseCustomRequestMatcherProvider() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); RequestMatcher mockRequestMatcher = (request) -> false; RequestMatcherAssert assertMatcher = assertMatcher(matcher, mockPathMappedEndpoints(""), (pattern, method) -> mockRequestMatcher, null); assertMatcher.doesNotMatch("/foo"); assertMatcher.doesNotMatch("/bar"); } @Test void linksRequestMatcherShouldUseCustomRequestMatcherProvider() { RequestMatcher matcher = EndpointRequest.toLinks(); RequestMatcher mockRequestMatcher = (request) -> false; RequestMatcherAssert assertMatcher = assertMatcher(matcher, mockPathMappedEndpoints("/actuator"), (pattern, method) -> mockRequestMatcher, null); assertMatcher.doesNotMatch("/actuator"); } @Test void noEndpointPathsBeansShouldNeverMatch() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertMatcher(matcher, (PathMappedEndpoints) null).doesNotMatch("/actuator/foo"); assertMatcher(matcher, (PathMappedEndpoints) null).doesNotMatch("/actuator/bar"); } @Test void toStringWhenIncludedEndpoints() { RequestMatcher matcher = EndpointRequest.to("foo", "bar"); assertThat(matcher).hasToString("EndpointRequestMatcher includes=[foo, bar], excludes=[], includeLinks=false"); } @Test void toStringWhenEmptyIncludedEndpoints() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint(); assertThat(matcher).hasToString("EndpointRequestMatcher includes=[*], excludes=[], includeLinks=true"); } @Test void toStringWhenIncludedEndpointsClasses() { RequestMatcher matcher = EndpointRequest.to(FooEndpoint.class).excluding("bar"); assertThat(matcher).hasToString("EndpointRequestMatcher includes=[foo], excludes=[bar], includeLinks=false"); } @Test void toStringWhenIncludedExcludedEndpoints() { RequestMatcher matcher = EndpointRequest.toAnyEndpoint().excluding("bar").excludingLinks(); assertThat(matcher).hasToString("EndpointRequestMatcher includes=[*], excludes=[bar], includeLinks=false"); } @Test void toStringWhenToAdditionalPaths() { RequestMatcher matcher = EndpointRequest.toAdditionalPaths(WebServerNamespace.SERVER, "test"); assertThat(matcher) .hasToString("AdditionalPathsEndpointRequestMatcher endpoints=[test], webServerNamespace=server"); } @Test void toAnyEndpointWhenEndpointPathMappedToRootIsExcludedShouldNotMatchRoot() { EndpointRequestMatcher matcher = EndpointRequest.toAnyEndpoint().excluding("root"); RequestMatcherAssert assertMatcher = assertMatcher(matcher, new PathMappedEndpoints("", () -> List .of(mockEndpoint(EndpointId.of("root"), "/"), mockEndpoint(EndpointId.of("alpha"), "alpha")))); assertMatcher.doesNotMatch("/"); assertMatcher.matches("/alpha"); assertMatcher.matches("/alpha/sub"); } @Test void toEndpointWhenEndpointPathMappedToRootShouldMatchRoot() { EndpointRequestMatcher matcher = EndpointRequest.to("root"); RequestMatcherAssert assertMatcher = assertMatcher(matcher, new PathMappedEndpoints("", () -> List.of(mockEndpoint(EndpointId.of("root"), "/")))); assertMatcher.matches("/"); } @Test void toAdditionalPathsWithEndpointClassShouldMatchAdditionalPath() { AdditionalPathsEndpointRequestMatcher matcher = EndpointRequest.toAdditionalPaths(WebServerNamespace.SERVER, FooEndpoint.class); RequestMatcherAssert assertMatcher = assertMatcher(matcher, new PathMappedEndpoints("", () -> List.of(mockEndpoint(EndpointId.of("foo"), "test", WebServerNamespace.SERVER, "/additional")))); assertMatcher.matches("/additional"); } @Test void toAdditionalPathsWithEndpointIdShouldMatchAdditionalPath() { AdditionalPathsEndpointRequestMatcher matcher = EndpointRequest.toAdditionalPaths(WebServerNamespace.SERVER, "foo"); RequestMatcherAssert assertMatcher = assertMatcher(matcher, new PathMappedEndpoints("", () -> List.of(mockEndpoint(EndpointId.of("foo"), "test", WebServerNamespace.SERVER, "/additional")))); assertMatcher.matches("/additional"); } @Test void toAdditionalPathsWithEndpointClassShouldNotMatchOtherPaths() { AdditionalPathsEndpointRequestMatcher matcher = EndpointRequest.toAdditionalPaths(WebServerNamespace.SERVER, FooEndpoint.class); RequestMatcherAssert assertMatcher = assertMatcher(matcher, new PathMappedEndpoints("", () -> List.of(mockEndpoint(EndpointId.of("foo"), "test", WebServerNamespace.SERVER, "/additional")))); assertMatcher.doesNotMatch("/foo"); assertMatcher.doesNotMatch("/bar"); } @Test void toAdditionalPathsWithEndpointClassShouldNotMatchOtherNamespace() { AdditionalPathsEndpointRequestMatcher matcher = EndpointRequest.toAdditionalPaths(WebServerNamespace.SERVER, FooEndpoint.class); RequestMatcherAssert assertMatcher = assertMatcher(matcher, new PathMappedEndpoints("", () -> List.of(mockEndpoint(EndpointId.of("foo"), "test", WebServerNamespace.SERVER, "/additional"))), null, WebServerNamespace.MANAGEMENT); assertMatcher.doesNotMatch("/additional"); } private RequestMatcherAssert assertMatcher(RequestMatcher matcher) { return assertMatcher(matcher, mockPathMappedEndpoints("/actuator")); } private RequestMatcherAssert assertMatcher(RequestMatcher matcher, String basePath) { return assertMatcher(matcher, mockPathMappedEndpoints(basePath), null, null); } private PathMappedEndpoints mockPathMappedEndpoints(String basePath) { List<ExposableEndpoint<?>> endpoints = new ArrayList<>(); endpoints.add(mockEndpoint(EndpointId.of("foo"), "foo")); endpoints.add(mockEndpoint(EndpointId.of("bar"), "bar")); return new PathMappedEndpoints(basePath, () -> endpoints); } private TestEndpoint mockEndpoint(EndpointId id, String rootPath) { return mockEndpoint(id, rootPath, WebServerNamespace.SERVER); } private TestEndpoint mockEndpoint(EndpointId id, String rootPath, WebServerNamespace webServerNamespace, String... additionalPaths) { TestEndpoint endpoint = mock(TestEndpoint.class); given(endpoint.getEndpointId()).willReturn(id); given(endpoint.getRootPath()).willReturn(rootPath); given(endpoint.getAdditionalPaths(webServerNamespace)).willReturn(Arrays.asList(additionalPaths)); return endpoint; } private RequestMatcherAssert assertMatcher(RequestMatcher matcher, @Nullable PathMappedEndpoints pathMappedEndpoints) { return assertMatcher(matcher, pathMappedEndpoints, null, null); } private RequestMatcherAssert assertMatcher(RequestMatcher matcher, @Nullable PathMappedEndpoints pathMappedEndpoints, @Nullable RequestMatcherProvider matcherProvider, @Nullable WebServerNamespace namespace) { StaticWebApplicationContext context = new StaticWebApplicationContext(); if (namespace != null && !WebServerNamespace.SERVER.equals(namespace)) { NamedStaticWebApplicationContext parentContext = new NamedStaticWebApplicationContext(namespace); context.setParent(parentContext); } context.registerBean(WebEndpointProperties.class); if (pathMappedEndpoints != null) { context.registerBean(PathMappedEndpoints.class, () -> pathMappedEndpoints); WebEndpointProperties properties = context.getBean(WebEndpointProperties.class); if (!properties.getBasePath().equals(pathMappedEndpoints.getBasePath())) { properties.setBasePath(pathMappedEndpoints.getBasePath()); } } if (matcherProvider != null) { context.registerBean(RequestMatcherProvider.class, () -> matcherProvider); } return assertThat(new RequestMatcherAssert(context, matcher)); } static
EndpointRequestTests
java
netty__netty
codec-classes-quic/src/main/java/io/netty/handler/codec/quic/BoringSSLKeylessManagerFactory.java
{ "start": 6620, "end": 10639 }
class ____ extends KeyStore { private static final String ALIAS = "key"; private KeylessKeyStore(final X509Certificate[] certificateChain) { super(new KeyStoreSpi() { private final Date creationDate = new Date(); @Override @Nullable public Key engineGetKey(String alias, char[] password) { if (engineContainsAlias(alias)) { return BoringSSLKeylessPrivateKey.INSTANCE; } return null; } @Override public Certificate @Nullable [] engineGetCertificateChain(String alias) { return engineContainsAlias(alias)? certificateChain.clone() : null; } @Override @Nullable public Certificate engineGetCertificate(String alias) { return engineContainsAlias(alias)? certificateChain[0] : null; } @Override @Nullable public Date engineGetCreationDate(String alias) { return engineContainsAlias(alias)? creationDate : null; } @Override public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException { throw new KeyStoreException("Not supported"); } @Override public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) throws KeyStoreException { throw new KeyStoreException("Not supported"); } @Override public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException { throw new KeyStoreException("Not supported"); } @Override public void engineDeleteEntry(String alias) throws KeyStoreException { throw new KeyStoreException("Not supported"); } @Override public Enumeration<String> engineAliases() { return Collections.enumeration(Collections.singleton(ALIAS)); } @Override public boolean engineContainsAlias(String alias) { return ALIAS.equals(alias); } @Override public int engineSize() { return 1; } @Override public boolean engineIsKeyEntry(String alias) { return engineContainsAlias(alias); } @Override public boolean engineIsCertificateEntry(String alias) { return engineContainsAlias(alias); } @Override @Nullable public String engineGetCertificateAlias(Certificate cert) { if (cert instanceof X509Certificate) { for (X509Certificate x509Certificate : certificateChain) { if (x509Certificate.equals(cert)) { return ALIAS; } } } return null; } @Override public void engineStore(OutputStream stream, char[] password) { throw new UnsupportedOperationException(); } @Override public void engineLoad(@Nullable InputStream stream, char @Nullable [] password) { if (stream != null && password != null) { throw new UnsupportedOperationException(); } } }, null, "keyless"); } } }
KeylessKeyStore
java
spring-projects__spring-boot
module/spring-boot-security/src/test/java/org/springframework/boot/security/autoconfigure/web/servlet/ServletWebSecurityAutoConfigurationTests.java
{ "start": 10131, "end": 10376 }
class ____ { private @Nullable RSAPublicKey publicKey; @Nullable RSAPublicKey getPublicKey() { return this.publicKey; } void setPublicKey(@Nullable RSAPublicKey publicKey) { this.publicKey = publicKey; } } static
JwtProperties
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/client/versioning/HelloClient.java
{ "start": 987, "end": 1214 }
interface ____ { @Get("/greeting/{name}") String sayHello(String name); @Version("2") @Get("/greeting/{name}") @SingleResult Publisher<String> sayHelloTwo(String name); // <2> } // end::clazz[]
HelloClient
java
apache__hadoop
hadoop-tools/hadoop-streaming/src/main/java/org/apache/hadoop/streaming/io/TextOutputReader.java
{ "start": 1410, "end": 3492 }
class ____ extends OutputReader<Text, Text> { private LineReader lineReader; private byte[] bytes; private DataInput clientIn; private Configuration conf; private int numKeyFields; private byte[] separator; private Text key; private Text value; private Text line; @Override public void initialize(PipeMapRed pipeMapRed) throws IOException { super.initialize(pipeMapRed); clientIn = pipeMapRed.getClientInput(); conf = pipeMapRed.getConfiguration(); numKeyFields = pipeMapRed.getNumOfKeyFields(); separator = pipeMapRed.getFieldSeparator(); lineReader = new LineReader((InputStream)clientIn, conf); key = new Text(); value = new Text(); line = new Text(); } @Override public boolean readKeyValue() throws IOException { if (lineReader.readLine(line) <= 0) { return false; } bytes = line.getBytes(); splitKeyVal(bytes, line.getLength(), key, value); line.clear(); return true; } @Override public Text getCurrentKey() throws IOException { return key; } @Override public Text getCurrentValue() throws IOException { return value; } @Override public String getLastOutput() { if (bytes != null) { return new String(bytes, StandardCharsets.UTF_8); } else { return null; } } // split a UTF-8 line into key and value private void splitKeyVal(byte[] line, int length, Text key, Text val) throws IOException { // Need to find numKeyFields separators int pos = UTF8ByteArrayUtils.findBytes(line, 0, length, separator); for(int k=1; k<numKeyFields && pos!=-1; k++) { pos = UTF8ByteArrayUtils.findBytes(line, pos + separator.length, length, separator); } try { if (pos == -1) { key.set(line, 0, length); val.set(""); } else { StreamKeyValUtil.splitKeyVal(line, 0, length, key, val, pos, separator.length); } } catch (CharacterCodingException e) { throw new IOException(StringUtils.stringifyException(e)); } } }
TextOutputReader
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/pool/vendor/MySqlExceptionSorterTest_1.java
{ "start": 306, "end": 1859 }
class ____ extends PoolTestCase { public void test_0() throws Exception { MySqlExceptionSorter sorter = new MySqlExceptionSorter(); Class clazz = MySqlUtils.getCommunicationsExceptionClass(); if ("com.mysql.jdbc.CommunicationsException".equals(clazz.getName())) { Constructor constructor = null; for (Constructor item : clazz.getConstructors()) { if (item.getParameterTypes().length == 4) { constructor = item; break; } } SQLException rootException = new SQLException( new SQLException("Could not retrieve transition read-only status server", (Exception) constructor.newInstance(null, 0, 0, null) ) ); assertTrue(sorter.isExceptionFatal(rootException)); } else { Constructor constructor = null; for (Constructor item : clazz.getConstructors()) { if (item.getParameterTypes().length == 2) { constructor = item; break; } } SQLException rootException = new SQLException( new SQLException("Could not retrieve transition read-only status server", (Exception) constructor.newInstance(null, null) ) ); assertTrue(sorter.isExceptionFatal(rootException)); } } }
MySqlExceptionSorterTest_1
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/exec/internal/StandardJdbcMutationExecutor.java
{ "start": 717, "end": 4943 }
class ____ implements JdbcMutationExecutor { /** * Singleton access */ public static final StandardJdbcMutationExecutor INSTANCE = new StandardJdbcMutationExecutor(); @Override public int execute( JdbcOperationQueryMutation jdbcMutation, JdbcParameterBindings jdbcParameterBindings, Function<String, PreparedStatement> statementCreator, BiConsumer<Integer, PreparedStatement> expectationCheck, ExecutionContext executionContext) { final var session = executionContext.getSession(); session.autoFlushIfRequired( jdbcMutation.getAffectedTableNames() ); final var logicalConnection = session.getJdbcCoordinator().getLogicalConnection(); final var jdbcServices = session.getJdbcServices(); final String finalSql = applyOptions( jdbcMutation, executionContext, jdbcServices ); final var queryOptions = executionContext.getQueryOptions(); try { // prepare the query final var preparedStatement = statementCreator.apply( finalSql ); try { final Integer timeout = queryOptions.getTimeout(); if ( timeout != null ) { preparedStatement.setQueryTimeout( timeout ); } // bind parameters // todo : validate that all query parameters were bound? int paramBindingPosition = 1; for ( var parameterBinder : jdbcMutation.getParameterBinders() ) { parameterBinder.bindParameterValue( preparedStatement, paramBindingPosition++, jdbcParameterBindings, executionContext ); } session.getEventListenerManager().jdbcExecuteStatementStart(); final var eventMonitor = session.getEventMonitor(); final var executionEvent = eventMonitor.beginJdbcPreparedStatementExecutionEvent(); try { final int rows = preparedStatement.executeUpdate(); expectationCheck.accept( rows, preparedStatement ); return rows; } finally { eventMonitor.completeJdbcPreparedStatementExecutionEvent( executionEvent, finalSql ); session.getEventListenerManager().jdbcExecuteStatementEnd(); } } finally { logicalConnection.getResourceRegistry().release( preparedStatement ); } } catch (SQLException e) { return handleException( jdbcMutation, e, jdbcServices, finalSql ); } finally { executionContext.afterStatement( logicalConnection ); } } private static int handleException( JdbcOperationQueryMutation jdbcMutation, SQLException sqle, JdbcServices jdbcServices, String finalSql) { final var exception = jdbcServices.getSqlExceptionHelper() .convert( sqle, "JDBC exception executing SQL", finalSql ); if ( exception instanceof ConstraintViolationException constraintViolationException && jdbcMutation instanceof JdbcOperationQueryInsert jdbcInsert ) { if ( constraintViolationException.getKind() == ConstraintViolationException.ConstraintKind.UNIQUE ) { final String uniqueConstraintNameThatMayFail = jdbcInsert.getUniqueConstraintNameThatMayFail(); if ( uniqueConstraintNameThatMayFail != null ) { final String violatedConstraintName = constraintViolationException.getConstraintName(); if ( constraintNameMatches( uniqueConstraintNameThatMayFail, violatedConstraintName ) ) { return 0; } } } } throw exception; } private static String applyOptions( JdbcOperationQueryMutation jdbcMutation, ExecutionContext executionContext, JdbcServices jdbcServices) { final var queryOptions = executionContext.getQueryOptions(); return queryOptions == null ? jdbcMutation.getSqlString() : jdbcServices.getDialect().addSqlHintOrComment( jdbcMutation.getSqlString(), queryOptions, executionContext.getSession().getFactory().getSessionFactoryOptions().isCommentsEnabled() ); } private static boolean constraintNameMatches(String uniqueConstraintNameThatMayFail, String violatedConstraintName) { return uniqueConstraintNameThatMayFail.isEmpty() || uniqueConstraintNameThatMayFail.equalsIgnoreCase( violatedConstraintName ) || violatedConstraintName != null && violatedConstraintName.indexOf('.') > 0 && uniqueConstraintNameThatMayFail.equalsIgnoreCase( violatedConstraintName.substring(violatedConstraintName.lastIndexOf('.') + 1) ); } }
StandardJdbcMutationExecutor
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/SystemUtils.java
{ "start": 56190, "end": 56705 }
class ____ loaded. * </p> * * @since 3.4 */ public static final boolean IS_OS_MAC_OSX_MAVERICKS = getOsMatches("Mac OS X", "10.9"); /** * The constant {@code true} if this is macOS X Yosemite. * <p> * The value depends on the value of the {@link #OS_NAME} and {@link #OS_VERSION} constants. * </p> * <p> * The value is {@code false} if {@link #OS_NAME} or {@link #OS_VERSION} is {@code null}. * </p> * <p> * This value is initialized when the
is
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/search/suggest/TermSuggestionOptionTests.java
{ "start": 1444, "end": 4321 }
class ____ extends ESTestCase { public static Option createTestItem() { Text text = new Text(randomAlphaOfLengthBetween(5, 15)); float score = randomFloat(); int freq = randomInt(); return new Option(text, freq, score); } public void testFromXContent() throws IOException { doTestFromXContent(false); } public void testFromXContentWithRandomFields() throws IOException { doTestFromXContent(true); } private void doTestFromXContent(boolean addRandomFields) throws IOException { Option option = createTestItem(); XContentType xContentType = randomFrom(XContentType.values()); boolean humanReadable = randomBoolean(); BytesReference originalBytes = toShuffledXContent(option, xContentType, ToXContent.EMPTY_PARAMS, humanReadable); BytesReference mutated; if (addRandomFields) { mutated = insertRandomFields(xContentType, originalBytes, null, random()); } else { mutated = originalBytes; } Option parsed; try (XContentParser parser = createParser(xContentType.xContent(), mutated)) { ensureExpectedToken(XContentParser.Token.START_OBJECT, parser.nextToken(), parser); parsed = parseEntryOption(parser); assertEquals(XContentParser.Token.END_OBJECT, parser.currentToken()); assertNull(parser.nextToken()); } assertEquals(option.getText(), parsed.getText()); assertEquals(option.getScore(), parsed.getScore(), Float.MIN_VALUE); assertEquals(option.getFreq(), parsed.getFreq()); assertToXContentEquivalent(originalBytes, toXContent(parsed, xContentType, humanReadable), xContentType); } public void testToXContent() throws IOException { Option option = new Option(new Text("someText"), 100, 1.3f); BytesReference xContent = toXContent(option, XContentType.JSON, randomBoolean()); assertEquals(""" {"text":"someText","score":1.3,"freq":100}""", xContent.utf8ToString()); } private static final ConstructingObjectParser<Option, Void> PARSER = new ConstructingObjectParser<>( "TermSuggestionOptionParser", true, args -> { Text text = new Text((String) args[0]); int freq = (Integer) args[1]; float score = (Float) args[2]; return new Option(text, freq, score); } ); static { PARSER.declareString(constructorArg(), Suggest.Suggestion.Entry.Option.TEXT); PARSER.declareInt(constructorArg(), TermSuggestion.Entry.Option.FREQ); PARSER.declareFloat(constructorArg(), Suggest.Suggestion.Entry.Option.SCORE); } public static Option parseEntryOption(XContentParser parser) { return PARSER.apply(parser, null); } }
TermSuggestionOptionTests
java
apache__camel
components/camel-jms/src/main/java/org/apache/camel/component/jms/DefaultSpringErrorHandler.java
{ "start": 1141, "end": 1923 }
class ____ implements ErrorHandler { private final LoggingExceptionHandler handler; private final boolean logStackTrace; public DefaultSpringErrorHandler(CamelContext camelContext, Class<?> owner, LoggingLevel level, boolean logStackTrace) { this.handler = new LoggingExceptionHandler(camelContext, owner, level); this.logStackTrace = logStackTrace; } @Override public void handleError(Throwable throwable) { if (logStackTrace) { handler.handleException("Execution of JMS message listener failed", throwable); } else { handler.handleException("Execution of JMS message listener failed. Caused by: [" + throwable.getMessage() + "]", null); } } }
DefaultSpringErrorHandler
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/google/ListGenerators.java
{ "start": 2642, "end": 3102 }
class ____ extends TestStringListGenerator { @Override protected List<String> create(String[] elements) { String[] suffix = {"f", "g"}; String[] all = new String[elements.length + suffix.length]; arraycopy(elements, 0, all, 0, elements.length); arraycopy(suffix, 0, all, elements.length, suffix.length); return ImmutableList.copyOf(all).subList(0, elements.length); } } public static
ImmutableListHeadSubListGenerator
java
google__guava
android/guava-tests/test/com/google/common/base/FinalizableReferenceQueueTest.java
{ "start": 1642, "end": 1809 }
class ____ aren't available // - possibly no real concept of separate ClassLoaders? @AndroidIncompatible @GwtIncompatible @RunWith(JUnit4.class) @NullUnmarked public
files
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/wrappedio/WrappedStatistics.java
{ "start": 2360, "end": 6540 }
class ____ { private WrappedStatistics() { } /** * Probe for an object being an instance of {@code IOStatisticsSource}. * @param object object to probe * @return true if the object is the right type. */ public static boolean isIOStatisticsSource(Object object) { return object instanceof IOStatisticsSource; } /** * Probe for an object being an instance of {@code IOStatistics}. * @param object object to probe * @return true if the object is the right type. */ public static boolean isIOStatistics(Object object) { return object instanceof IOStatistics; } /** * Probe for an object being an instance of {@code IOStatisticsSnapshot}. * @param object object to probe * @return true if the object is the right type. */ public static boolean isIOStatisticsSnapshot(Serializable object) { return object instanceof IOStatisticsSnapshot; } /** * Aggregate an existing {@link IOStatisticsSnapshot} with * the supplied statistics. * @param snapshot snapshot to update * @param statistics IOStatistics to add * @return true if the snapshot was updated. * @throws IllegalArgumentException if the {@code statistics} argument is not * null but not an instance of IOStatistics, or if {@code snapshot} is invalid. */ public static boolean iostatisticsSnapshot_aggregate( Serializable snapshot, @Nullable Object statistics) { requireIOStatisticsSnapshot(snapshot); if (statistics == null) { return false; } checkArgument(statistics instanceof IOStatistics, "Not an IOStatistics instance: %s", statistics); final IOStatistics sourceStats = (IOStatistics) statistics; return applyToIOStatisticsSnapshot(snapshot, s -> s.aggregate(sourceStats)); } /** * Create a new {@link IOStatisticsSnapshot} instance. * @return an empty IOStatisticsSnapshot. */ public static Serializable iostatisticsSnapshot_create() { return iostatisticsSnapshot_create(null); } /** * Create a new {@link IOStatisticsSnapshot} instance. * @param source optional source statistics * @return an IOStatisticsSnapshot. * @throws ClassCastException if the {@code source} is not null and not an IOStatistics instance */ public static Serializable iostatisticsSnapshot_create(@Nullable Object source) { return new IOStatisticsSnapshot((IOStatistics) source); } /** * Load IOStatisticsSnapshot from a Hadoop filesystem. * @param fs filesystem * @param path path * @return the loaded snapshot * @throws UncheckedIOException Any IO exception. */ public static Serializable iostatisticsSnapshot_load( FileSystem fs, Path path) { return uncheckIOExceptions(() -> IOStatisticsSnapshot.serializer().load(fs, path)); } /** * Extract the IOStatistics from an object in a serializable form. * @param source source object, may be null/not a statistics source/instance * @return {@link IOStatisticsSnapshot} or null if the object is null/doesn't have statistics */ public static Serializable iostatisticsSnapshot_retrieve(@Nullable Object source) { IOStatistics stats = retrieveIOStatistics(source); if (stats == null) { return null; } return iostatisticsSnapshot_create(stats); } /** * Save IOStatisticsSnapshot to a Hadoop filesystem as a JSON file. * @param snapshot statistics * @param fs filesystem * @param path path * @param overwrite should any existing file be overwritten? * @throws UncheckedIOException Any IO exception. */ public static void iostatisticsSnapshot_save( @Nullable Serializable snapshot, FileSystem fs, Path path, boolean overwrite) { applyToIOStatisticsSnapshot(snapshot, s -> { IOStatisticsSnapshot.serializer().save(fs, path, s, overwrite); return null; }); } /** * Save IOStatisticsSnapshot to a JSON string. * @param snapshot statistics; may be null or of an incompatible type * @return JSON string value * @throws UncheckedIOException Any IO/jackson exception. * @throws IllegalArgumentException if the supplied
WrappedStatistics
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/service/registry/ImportHttpServices.java
{ "start": 3698, "end": 3759 }
interface ____ { ImportHttpServices[] value(); } }
Container
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/node/POJONodeTest.java
{ "start": 369, "end": 473 }
class ____ extends NodeTestBase { @JsonSerialize(using = CustomSer.class) public static
POJONodeTest
java
apache__maven
compat/maven-model-builder/src/main/java/org/apache/maven/model/superpom/SuperPomProvider.java
{ "start": 1080, "end": 1640 }
interface ____ { /** * Gets the super POM for the specified model version. The returned model is supposed to be read-only, i.e. if the * caller intends to make updates to the model the return value must be cloned before updating to ensure the * modifications don't affect future retrievals of the super POM. * * @param version The model version to retrieve the super POM for (e.g. "4.0.0"), must not be {@code null}. * @return The super POM, never {@code null}. */ Model getSuperModel(String version); }
SuperPomProvider
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestHttpServerWithSpnego.java
{ "start": 2372, "end": 2443 }
class ____ tested for http server with SPNEGO authentication. */ public
is
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java
{ "start": 27302, "end": 27362 }
class ____ { } @FastAndSmoky static
MultiComposedTaggedClass
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/TableEnvironment.java
{ "start": 26075, "end": 26739 }
class ____ a temporary catalog function. * * <p>Compared to {@link #createTemporarySystemFunction(String, Class)} with a globally defined * name, catalog functions are always (implicitly or explicitly) identified by a catalog and * database. * * <p>Temporary functions can shadow permanent ones. If a permanent function under a given name * exists, it will be inaccessible in the current session. To make the permanent function * available again one can drop the corresponding temporary function. * * @param path The path under which the function will be registered. See also the {@link * TableEnvironment}
as
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/heap/KeyGroupPartitionedPriorityQueue.java
{ "start": 10960, "end": 11814 }
interface ____< T, PQS extends InternalPriorityQueue<T> & HeapPriorityQueueElement> { /** * Creates a new queue for a given key-group partition. * * @param keyGroupId the key-group of the elements managed by the produced queue. * @param numKeyGroups the total number of key-groups in the job. * @param elementPriorityComparator the comparator that determines the order of managed * elements by priority. * @return a new queue for the given key-group. */ @Nonnull PQS create( @Nonnegative int keyGroupId, @Nonnegative int numKeyGroups, @Nonnull KeyExtractorFunction<T> keyExtractorFunction, @Nonnull PriorityComparator<T> elementPriorityComparator); } }
PartitionQueueSetFactory
java
dropwizard__dropwizard
dropwizard-migrations/src/main/java/io/dropwizard/migrations/DbTagCommand.java
{ "start": 257, "end": 1015 }
class ____<T extends Configuration> extends AbstractLiquibaseCommand<T> { public DbTagCommand(DatabaseConfiguration<T> strategy, Class<T> configurationClass, String migrationsFileName) { super("tag", "Tag the database schema.", strategy, configurationClass, migrationsFileName); } @Override public void configure(Subparser subparser) { super.configure(subparser); subparser.addArgument("tag-name") .dest("tag-name") .nargs(1) .required(true) .help("The tag name"); } @Override public void run(Namespace namespace, Liquibase liquibase) throws Exception { liquibase.tag(namespace.<String>getList("tag-name").get(0)); } }
DbTagCommand
java
jhy__jsoup
src/test/java/org/jsoup/nodes/ElementIT.java
{ "start": 330, "end": 5799 }
class ____ { @Test public void testFastReparent() { StringBuilder htmlBuf = new StringBuilder(); int rows = 300000; for (int i = 1; i <= rows; i++) { htmlBuf .append("<p>El-") .append(i) .append("</p>"); } String html = htmlBuf.toString(); Document doc = Jsoup.parse(html); long start = System.currentTimeMillis(); Element wrapper = new Element("div"); List<Node> childNodes = doc.body().childNodes(); wrapper.insertChildren(0, childNodes); long runtime = System.currentTimeMillis() - start; assertEquals(rows, wrapper.childNodes.size()); assertEquals(rows, childNodes.size()); // child nodes is a wrapper, so still there assertEquals(0, doc.body().childNodes().size()); // but on a fresh look, all gone doc.body().empty().appendChild(wrapper); Element wrapperAcutal = doc.body().children().get(0); assertEquals(wrapper, wrapperAcutal); assertEquals("El-1", wrapperAcutal.children().get(0).text()); assertEquals("El-" + rows, wrapperAcutal.children().get(rows - 1).text()); assertTrue(runtime <= 10000); } @Test public void testFastReparentExistingContent() { StringBuilder htmlBuf = new StringBuilder(); int rows = 300000; for (int i = 1; i <= rows; i++) { htmlBuf .append("<p>El-") .append(i) .append("</p>"); } String html = htmlBuf.toString(); Document doc = Jsoup.parse(html); long start = System.currentTimeMillis(); Element wrapper = new Element("div"); wrapper.append("<p>Prior Content</p>"); wrapper.append("<p>End Content</p>"); assertEquals(2, wrapper.childNodes.size()); List<Node> childNodes = doc.body().childNodes(); wrapper.insertChildren(1, childNodes); long runtime = System.currentTimeMillis() - start; assertEquals(rows + 2, wrapper.childNodes.size()); assertEquals(rows, childNodes.size()); // child nodes is a wrapper, so still there assertEquals(0, doc.body().childNodes().size()); // but on a fresh look, all gone doc.body().empty().appendChild(wrapper); Element wrapperAcutal = doc.body().children().get(0); assertEquals(wrapper, wrapperAcutal); assertEquals("Prior Content", wrapperAcutal.children().get(0).text()); assertEquals("El-1", wrapperAcutal.children().get(1).text()); assertEquals("El-" + rows, wrapperAcutal.children().get(rows).text()); assertEquals("End Content", wrapperAcutal.children().get(rows + 1).text()); assertTrue(runtime <= 10000); } // These overflow tests take a couple seconds to run, so are in the slow tests @Test void hasTextNoOverflow() { // hasText() was recursive, so could overflow Document doc = new Document("https://example.com/"); Element el = doc.body(); for (int i = 0; i <= 50000; i++) { el = el.appendChild(doc.createElement("p")).firstElementChild(); } assertFalse(doc.hasText()); el.text("Hello"); assertTrue(doc.hasText()); assertEquals(el.text(), doc.text()); } @Test void dataNoOverflow() { // data() was recursive, so could overflow Document doc = new Document("https://example.com/"); Element el = doc.body(); for (int i = 0; i <= 50000; i++) { el = el.appendChild(doc.createElement("p")).firstElementChild(); } Element script = el.appendElement("script"); script.text("script"); // holds data nodes, so inserts as data, not text assertFalse(script.hasText()); assertEquals("script", script.data()); assertEquals(el.data(), doc.data()); } @Test void parentsNoOverflow() { // parents() was recursive, so could overflow Document doc = new Document("https://example.com/"); Element el = doc.body(); int num = 50000; for (int i = 0; i <= num; i++) { el = el.appendChild(doc.createElement("p")).firstElementChild(); } Elements parents = el.parents(); assertEquals(num+2, parents.size()); // +2 for html and body assertEquals(doc, el.ownerDocument()); } @Test void wrapNoOverflow() { // deepChild was recursive, so could overflow if presented with a fairly insane wrap Document doc = new Document("https://example.com/"); doc.parser().setMaxDepth(Integer.MAX_VALUE); // don't limit to 512 Element el = doc.body().appendElement("p"); int num = 50000; StringBuilder sb = new StringBuilder(); for (int i = 0; i <= num; i++) { sb.append("<div>"); } el.wrap(sb.toString()); String html = doc.body().html(); assertTrue(html.startsWith("<div>")); assertEquals(num + 3, el.parents().size()); // + 3 is for body, html, document } @Test public void testConcurrentMerge() throws Exception { // https://github.com/jhy/jsoup/discussions/2280 / https://github.com/jhy/jsoup/issues/2281 // This was failing because the template.clone().append(html) was reusing the same underlying parser object. // Document#clone now correctly clones its parser.
ElementIT
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/odps/OdpsFormatCommentTest15.java
{ "start": 121, "end": 586 }
class ____ extends TestCase { public void test_column_comment() throws Exception { String sql = "create table t1 (f0 bigint) partitioned by (ds string, hh string);"; assertEquals("CREATE TABLE t1 (" + "\n\tf0 BIGINT" + "\n)" + "\nPARTITIONED BY (" + "\n\tds STRING," + "\n\thh STRING" + "\n);", SQLUtils.formatOdps(sql)); } }
OdpsFormatCommentTest15
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/cascade/multicircle/nonjpa/identity/EntityD.java
{ "start": 238, "end": 1464 }
class ____ extends AbstractEntity { private static final long serialVersionUID = 2417176961L; @jakarta.persistence.OneToMany(mappedBy = "d") private java.util.Set<EntityB> bCollection = new java.util.HashSet<EntityB>(); @jakarta.persistence.ManyToOne(optional = false) private EntityC c; @jakarta.persistence.ManyToOne(optional = false) private EntityE e; @jakarta.persistence.OneToMany(mappedBy = "d") @org.hibernate.annotations.Cascade({ org.hibernate.annotations.CascadeType.PERSIST, org.hibernate.annotations.CascadeType.MERGE, org.hibernate.annotations.CascadeType.REFRESH }) private java.util.Set<EntityF> fCollection = new java.util.HashSet<EntityF>(); public java.util.Set<EntityB> getBCollection() { return bCollection; } public void setBCollection( java.util.Set<EntityB> parameter) { this.bCollection = parameter; } public EntityC getC() { return c; } public void setC(EntityC c) { this.c = c; } public EntityE getE() { return e; } public void setE(EntityE e) { this.e = e; } public java.util.Set<EntityF> getFCollection() { return fCollection; } public void setFCollection( java.util.Set<EntityF> parameter) { this.fCollection = parameter; } }
EntityD
java
micronaut-projects__micronaut-core
aop/src/main/java/io/micronaut/aop/Intercepted.java
{ "start": 793, "end": 843 }
interface ____ extends InterceptedBean { }
Intercepted
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/maps/Maps_assertHasSizeBetween_Test.java
{ "start": 1045, "end": 2575 }
class ____ extends MapsBaseTest { @Test void should_fail_if_actual_is_null() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertHasSizeBetween(INFO, null, 0, 6)) .withMessage(actualIsNull()); } @Test void should_throw_illegal_argument_exception_if_lower_boundary_is_greater_than_higher_boundary() { assertThatIllegalArgumentException().isThrownBy(() -> maps.assertHasSizeBetween(INFO, actual, 4, 2)) .withMessage("The higher boundary <2> must be greater than the lower boundary <4>."); } @Test void should_fail_if_size_of_actual_is_not_greater_than_or_equal_to_lower_boundary() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertHasSizeBetween(INFO, actual, 4, 6)) .withMessage(shouldHaveSizeBetween(actual, actual.size(), 4, 6).create()); } @Test void should_fail_if_size_of_actual_is_not_less_than_higher_boundary() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> maps.assertHasSizeBetween(INFO, actual, 0, 1)) .withMessage(shouldHaveSizeBetween(actual, actual.size(), 0, 1).create()); } @Test void should_pass_if_size_of_actual_is_between_boundaries() { maps.assertHasSizeBetween(INFO, actual, 1, 6); maps.assertHasSizeBetween(INFO, actual, actual.size(), actual.size()); } }
Maps_assertHasSizeBetween_Test
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/factories/assignment/Bar6Factory.java
{ "start": 275, "end": 425 }
class ____ { @ObjectFactory public Bar6 createBar6(Foo6A foo6A) { return new Bar6( foo6A.getPropA().toUpperCase() ); } }
Bar6Factory
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/search/arguments/TextFieldArgs.java
{ "start": 1165, "end": 3146 }
enum ____ { ENGLISH("dm:en"), FRENCH("dm:fr"), PORTUGUESE("dm:pt"), SPANISH("dm:es"); private final String matcher; PhoneticMatcher(String matcher) { this.matcher = matcher; } public String getMatcher() { return matcher; } } private Optional<Long> weight = Optional.empty(); private boolean noStem; private Optional<PhoneticMatcher> phonetic = Optional.empty(); private boolean withSuffixTrie; /** * Create a new {@link TextFieldArgs} using the builder pattern. * * @param <K> Key type * @return a new {@link Builder} */ public static <K> Builder<K> builder() { return new Builder<>(); } @Override public String getFieldType() { return "TEXT"; } /** * Get the weight of the field. * * @return the weight */ public Optional<Long> getWeight() { return weight; } /** * Check if stemming is disabled. * * @return true if stemming is disabled */ public boolean isNoStem() { return noStem; } /** * Get the phonetic matcher. * * @return the phonetic matcher */ public Optional<PhoneticMatcher> getPhonetic() { return phonetic; } /** * Check if suffix trie is enabled. * * @return true if suffix trie is enabled */ public boolean isWithSuffixTrie() { return withSuffixTrie; } @Override protected void buildTypeSpecificArgs(CommandArgs<K, ?> args) { weight.ifPresent(w -> args.add(WEIGHT).add(w)); if (noStem) { args.add(NOSTEM); } phonetic.ifPresent(p -> args.add(PHONETIC).add(p.getMatcher())); if (withSuffixTrie) { args.add(WITHSUFFIXTRIE); } } /** * Builder for {@link TextFieldArgs}. * * @param <K> Key type */ public static
PhoneticMatcher
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_1200/Issue1222_1.java
{ "start": 580, "end": 646 }
class ____ { public Type type; } private static
Model
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java
{ "start": 13162, "end": 13340 }
class ____ { @Bean TaskScheduler customTaskScheduler() { return new TestTaskScheduler(); } } @Configuration(proxyBeanMethods = false) static
TaskSchedulerConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/embeddable/ParentCacheTest.java
{ "start": 1367, "end": 2748 }
class ____ { @BeforeAll public void setUp(SessionFactoryScope scope) { scope.inTransaction( session -> { session.persist( new ParentEntity( new ChildEmbeddable( "test" ) ) ); } ); } @AfterAll public void tearDown(SessionFactoryScope scope) { scope.inTransaction( session -> session.createMutationQuery( "delete from ParentEntity" ).executeUpdate() ); } @Test public void test(SessionFactoryScope scope) { scope.getSessionFactory().getCache().evictEntityData(); final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( session -> { final ParentEntity parent = session.find( ParentEntity.class, 1L ); final ChildEmbeddable embeddable = parent.getChild(); assertThat( embeddable.getParent() ).isNotNull(); } ); assertThat( statistics.getSecondLevelCacheHitCount() ).isEqualTo( 0 ); assertThat( statistics.getSecondLevelCacheMissCount() ).isEqualTo( 1L ); assertThat( statistics.getSecondLevelCachePutCount() ).isEqualTo( 1L ); scope.inTransaction( session -> { final ParentEntity parent = session.find( ParentEntity.class, 1L ); final ChildEmbeddable embeddable = parent.getChild(); assertThat( embeddable.getParent() ).isNotNull(); } ); assertThat( statistics.getSecondLevelCacheHitCount() ).isEqualTo( 1L ); } @Embeddable public static
ParentCacheTest
java
spring-projects__spring-boot
module/spring-boot-tomcat/src/test/java/org/springframework/boot/tomcat/autoconfigure/metrics/TomcatMetricsAutoConfigurationTests.java
{ "start": 6746, "end": 6942 }
class ____ { @Bean TomcatMetrics customTomcatMetrics() { return new TomcatMetrics(null, Collections.emptyList()); } } @Configuration(proxyBeanMethods = false) static
CustomTomcatMetrics
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/internal/Paths.java
{ "start": 4293, "end": 24647 }
class ____ { private static final String UNABLE_TO_COMPARE_PATH_CONTENTS = "Unable to compare contents of paths:<%s> and:<%s>"; private static final Paths INSTANCE = new Paths(); private static final Filter<Path> ANY = any -> true; // TODO reduce the visibility of the fields annotated with @VisibleForTesting Diff diff = new Diff(); // TODO reduce the visibility of the fields annotated with @VisibleForTesting BinaryDiff binaryDiff = new BinaryDiff(); // TODO reduce the visibility of the fields annotated with @VisibleForTesting Failures failures = Failures.instance(); // TODO reduce the visibility of the fields annotated with @VisibleForTesting NioFilesWrapper nioFilesWrapper = NioFilesWrapper.instance(); public static Paths instance() { return INSTANCE; } private Paths() {} public void assertIsReadable(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); assertExists(info, actual); if (!Files.isReadable(actual)) throw failures.failure(info, shouldBeReadable(actual)); } public void assertIsWritable(AssertionInfo info, Path actual) { assertNotNull(info, actual); assertExists(info, actual); if (!Files.isWritable(actual)) throw failures.failure(info, shouldBeWritable(actual)); } public void assertIsExecutable(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); assertExists(info, actual); if (!Files.isExecutable(actual)) throw failures.failure(info, shouldBeExecutable(actual)); } public void assertExists(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); if (!Files.exists(actual)) throw failures.failure(info, shouldExist(actual)); } public void assertExistsNoFollowLinks(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); if (!Files.exists(actual, LinkOption.NOFOLLOW_LINKS)) throw failures.failure(info, shouldExistNoFollowLinks(actual)); } public void assertDoesNotExist(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); if (!Files.notExists(actual, LinkOption.NOFOLLOW_LINKS)) throw failures.failure(info, shouldNotExist(actual)); } public void assertIsRegularFile(final AssertionInfo info, final Path actual) { assertExists(info, actual); if (!Files.isRegularFile(actual)) throw failures.failure(info, shouldBeRegularFile(actual)); } public void assertIsDirectory(final AssertionInfo info, final Path actual) { assertExists(info, actual); if (!Files.isDirectory(actual)) throw failures.failure(info, shouldBeDirectory(actual)); } public void assertIsSymbolicLink(final AssertionInfo info, final Path actual) { assertExistsNoFollowLinks(info, actual); if (!Files.isSymbolicLink(actual)) throw failures.failure(info, shouldBeSymbolicLink(actual)); } public void assertIsAbsolute(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); if (!actual.isAbsolute()) throw failures.failure(info, shouldBeAbsolutePath(actual)); } public void assertIsRelative(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); if (actual.isAbsolute()) throw failures.failure(info, shouldBeRelativePath(actual)); } public void assertIsNormalized(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); if (!actual.normalize().equals(actual)) throw failures.failure(info, shouldBeNormalized(actual)); } public void assertIsCanonical(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); if (!actual.equals(toRealPath(actual))) throw failures.failure(info, shouldBeCanonicalPath(actual)); } public void assertHasParent(final AssertionInfo info, final Path actual, final Path expected) { assertNotNull(info, actual); checkExpectedParentPathIsNotNull(expected); Path parent = toRealPath(actual).getParent(); if (parent == null) throw failures.failure(info, shouldHaveParent(actual, expected)); if (!parent.equals(toRealPath(expected))) throw failures.failure(info, shouldHaveParent(actual, parent, expected)); } public void assertHasParentRaw(final AssertionInfo info, final Path actual, final Path expected) { assertNotNull(info, actual); checkExpectedParentPathIsNotNull(expected); Path parent = actual.getParent(); if (parent == null) throw failures.failure(info, shouldHaveParent(actual, expected)); if (!parent.equals(expected)) throw failures.failure(info, shouldHaveParent(actual, parent, expected)); } public void assertHasNoParent(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); if (toRealPath(actual).getParent() != null) throw failures.failure(info, shouldHaveNoParent(actual)); } public void assertHasNoParentRaw(final AssertionInfo info, final Path actual) { assertNotNull(info, actual); if (actual.getParent() != null) throw failures.failure(info, shouldHaveNoParent(actual)); } public void assertHasSize(final AssertionInfo info, final Path actual, long expectedSize) { assertIsRegularFile(info, actual); try { long actualSize = nioFilesWrapper.size(actual); if (actualSize != expectedSize) throw failures.failure(info, shouldHaveSize(actual, expectedSize)); } catch (IOException e) { throw new UncheckedIOException(e); } } public void assertStartsWith(final AssertionInfo info, final Path actual, final Path other) { assertNotNull(info, actual); assertExpectedStartPathIsNotNull(other); Path absoluteActual = Files.exists(actual) ? toRealPath(actual) : actual.toAbsolutePath().normalize(); Path absoluteOther = Files.exists(other) ? toRealPath(other) : other.toAbsolutePath().normalize(); if (!absoluteActual.startsWith(absoluteOther)) { throw failures.failure(info, shouldStartWith(actual, other)); } } public void assertStartsWithRaw(final AssertionInfo info, final Path actual, final Path other) { assertNotNull(info, actual); assertExpectedStartPathIsNotNull(other); if (!actual.startsWith(other)) throw failures.failure(info, shouldStartWith(actual, other)); } public void assertEndsWith(final AssertionInfo info, final Path actual, final Path other) { assertNotNull(info, actual); assertExpectedEndPathIsNotNull(other); Path path = Files.exists(actual) ? toRealPath(actual) : actual; if (!path.endsWith(other.normalize())) throw failures.failure(info, shouldEndWith(actual, other)); } public void assertEndsWithRaw(final AssertionInfo info, final Path actual, final Path end) { assertNotNull(info, actual); assertExpectedEndPathIsNotNull(end); if (!actual.endsWith(end)) throw failures.failure(info, shouldEndWith(actual, end)); } public void assertHasFileName(final AssertionInfo info, Path actual, String fileName) { assertNotNull(info, actual); requireNonNull(fileName, "expected fileName should not be null"); if (!actual.getFileName().endsWith(fileName)) throw failures.failure(info, shouldHaveName(actual, fileName)); } public void assertHasTextualContent(final AssertionInfo info, Path actual, String expected, Charset charset) { requireNonNull(expected, "The text to compare to should not be null"); assertIsReadable(info, actual); try { List<Delta<String>> diffs = diff.diff(actual, expected, charset); if (!diffs.isEmpty()) throw failures.failure(info, shouldHaveContent(actual, charset, diffs)); } catch (IOException e) { throw new UncheckedIOException("Unable to verify text contents of path:<%s>".formatted(actual), e); } } public void assertHasBinaryContent(AssertionInfo info, Path actual, byte[] expected) { requireNonNull(expected, "The binary content to compare to should not be null"); assertIsReadable(info, actual); try { BinaryDiffResult diffResult = binaryDiff.diff(actual, expected); if (!diffResult.hasNoDiff()) throw failures.failure(info, shouldHaveBinaryContent(actual, diffResult)); } catch (IOException e) { throw new UncheckedIOException("Unable to verify binary contents of path:<%s>".formatted(actual), e); } } public void assertHasSameBinaryContentAs(AssertionInfo info, Path actual, Path expected) { requireNonNull(expected, "The given Path to compare actual content to should not be null"); checkArgument(Files.exists(expected), "The given Path <%s> to compare actual content to should exist", expected); checkArgument(Files.isReadable(expected), "The given Path <%s> to compare actual content to should be readable", expected); assertIsReadable(info, actual); try { BinaryDiffResult binaryDiffResult = binaryDiff.diff(actual, readAllBytes(expected)); if (binaryDiffResult.hasDiff()) throw failures.failure(info, shouldHaveBinaryContent(actual, binaryDiffResult)); } catch (IOException ioe) { throw new UncheckedIOException(UNABLE_TO_COMPARE_PATH_CONTENTS.formatted(actual, expected), ioe); } } public void assertHasSameTextualContentAs(AssertionInfo info, Path actual, Charset actualCharset, Path expected, Charset expectedCharset) { requireNonNull(expected, "The given Path to compare actual content to should not be null"); checkArgument(Files.exists(expected), "The given Path <%s> to compare actual content to should exist", expected); checkArgument(Files.isReadable(expected), "The given Path <%s> to compare actual content to should be readable", expected); assertIsReadable(info, actual); try { List<Delta<String>> diffs = diff.diff(actual, actualCharset, expected, expectedCharset); if (!diffs.isEmpty()) throw failures.failure(info, shouldHaveSameContent(actual, expected, diffs)); } catch (IOException e) { throw new UncheckedIOException(UNABLE_TO_COMPARE_PATH_CONTENTS.formatted(actual, expected), e); } } public void assertHasDigest(AssertionInfo info, Path actual, MessageDigest digest, byte[] expected) { requireNonNull(digest, "The message digest algorithm should not be null"); requireNonNull(expected, "The binary representation of digest to compare to should not be null"); assertIsRegularFile(info, actual); assertIsReadable(info, actual); try (InputStream actualStream = nioFilesWrapper.newInputStream(actual)) { DigestDiff diff = Digests.digestDiff(actualStream, digest, expected); if (diff.digestsDiffer()) throw failures.failure(info, shouldHaveDigest(actual, diff)); } catch (IOException e) { throw new UncheckedIOException("Unable to calculate digest of path:<%s>".formatted(actual), e); } } public void assertHasDigest(AssertionInfo info, Path actual, MessageDigest digest, String expected) { requireNonNull(expected, "The string representation of digest to compare to should not be null"); assertHasDigest(info, actual, digest, Digests.fromHex(expected)); } public void assertHasDigest(AssertionInfo info, Path actual, String algorithm, byte[] expected) { requireNonNull(algorithm, "The message digest algorithm should not be null"); try { assertHasDigest(info, actual, MessageDigest.getInstance(algorithm), expected); } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Unable to find digest implementation for: <%s>".formatted(algorithm), e); } } public void assertHasDigest(AssertionInfo info, Path actual, String algorithm, String expected) { requireNonNull(expected, "The string representation of digest to compare to should not be null"); assertHasDigest(info, actual, algorithm, Digests.fromHex(expected)); } public void assertIsDirectoryContaining(AssertionInfo info, Path actual, Predicate<Path> filter) { requireNonNull(filter, "The paths filter should not be null"); assertIsDirectoryContaining(info, actual, filter::test, "the given filter"); } public void assertIsDirectoryContaining(AssertionInfo info, Path actual, String syntaxAndPattern) { requireNonNull(syntaxAndPattern, "The syntax and pattern should not be null"); PathMatcher pathMatcher = pathMatcher(info, actual, syntaxAndPattern); assertIsDirectoryContaining(info, actual, pathMatcher::matches, "the '%s' pattern".formatted(syntaxAndPattern)); } public void assertIsDirectoryRecursivelyContaining(AssertionInfo info, Path actual, String syntaxAndPattern) { requireNonNull(syntaxAndPattern, "The syntax and pattern should not be null"); PathMatcher pathMatcher = pathMatcher(info, actual, syntaxAndPattern); assertIsDirectoryRecursivelyContaining(info, actual, pathMatcher::matches, "the '%s' pattern".formatted(syntaxAndPattern)); } public void assertIsDirectoryRecursivelyContaining(AssertionInfo info, Path actual, Predicate<Path> filter) { requireNonNull(filter, "The files filter should not be null"); assertIsDirectoryRecursivelyContaining(info, actual, filter, "the given filter"); } public void assertIsDirectoryNotContaining(AssertionInfo info, Path actual, Predicate<Path> filter) { requireNonNull(filter, "The paths filter should not be null"); assertIsDirectoryNotContaining(info, actual, filter::test, "the given filter"); } public void assertIsDirectoryNotContaining(AssertionInfo info, Path actual, String syntaxAndPattern) { requireNonNull(syntaxAndPattern, "The syntax and pattern should not be null"); PathMatcher pathMatcher = pathMatcher(info, actual, syntaxAndPattern); assertIsDirectoryNotContaining(info, actual, pathMatcher::matches, "the '%s' pattern".formatted(syntaxAndPattern)); } public void assertIsEmptyDirectory(AssertionInfo info, Path actual) { List<Path> items = directoryContent(info, actual); if (!items.isEmpty()) throw failures.failure(info, shouldBeEmptyDirectory(actual, items)); } public void assertIsNotEmptyDirectory(AssertionInfo info, Path actual) { boolean isEmptyDirectory = directoryContent(info, actual).isEmpty(); if (isEmptyDirectory) throw failures.failure(info, shouldNotBeEmpty(actual)); } public void assertIsEmptyFile(AssertionInfo info, Path actual) { assertIsRegularFile(info, actual); try { if (nioFilesWrapper.size(actual) > 0) throw failures.failure(info, shouldBeEmpty(actual)); } catch (IOException e) { throw new UncheckedIOException(e); } } public void assertIsNotEmptyFile(AssertionInfo info, Path actual) { assertIsRegularFile(info, actual); try { if (nioFilesWrapper.size(actual) == 0) throw failures.failure(info, shouldNotBeEmpty(actual)); } catch (IOException e) { throw new UncheckedIOException(e); } } public void assertHasFileSystem(AssertionInfo info, Path actual, FileSystem expectedFileSystem) { assertNotNull(info, actual); requireNonNull(expectedFileSystem, "The expected file system should not be null"); FileSystem actualFileSystem = actual.getFileSystem(); requireNonNull(actualFileSystem, "The actual file system should not be null"); if (!expectedFileSystem.equals(actualFileSystem)) { throw failures.failure(info, shouldHaveFileSystem(actual, expectedFileSystem), actualFileSystem, expectedFileSystem); } } public void assertHasSameFileSystemAs(AssertionInfo info, Path actualPath, Path expectedPath) { assertNotNull(info, actualPath); requireNonNull(expectedPath, "The expected path should not be null"); FileSystem actualFileSystem = actualPath.getFileSystem(); requireNonNull(actualFileSystem, "The actual file system should not be null"); FileSystem expectedFileSystem = expectedPath.getFileSystem(); requireNonNull(expectedFileSystem, "The expected file system should not be null"); if (!expectedFileSystem.equals(actualFileSystem)) { throw failures.failure(info, shouldHaveSameFileSystemAs(actualPath, expectedPath), actualFileSystem, expectedFileSystem); } } // non-public section private List<Path> filterDirectory(AssertionInfo info, Path actual, Filter<Path> filter) { assertIsDirectory(info, actual); try (DirectoryStream<Path> stream = nioFilesWrapper.newDirectoryStream(actual, filter)) { return stream(stream.spliterator(), false).collect(toList()); } catch (IOException e) { throw new UncheckedIOException("Unable to list directory content: <%s>".formatted(actual), e); } } private List<Path> directoryContent(AssertionInfo info, Path actual) { return filterDirectory(info, actual, ANY); } private void assertIsDirectoryContaining(AssertionInfo info, Path actual, Filter<Path> filter, String filterPresentation) { List<Path> matchingFiles = filterDirectory(info, actual, filter); if (matchingFiles.isEmpty()) { throw failures.failure(info, directoryShouldContain(actual, directoryContent(info, actual), filterPresentation)); } } private boolean isDirectoryRecursivelyContaining(AssertionInfo info, Path actual, Predicate<Path> filter) { assertIsDirectory(info, actual); try (Stream<Path> actualContent = recursiveContentOf(actual)) { return actualContent.anyMatch(filter); } } private List<Path> sortedRecursiveContent(Path path) { try (Stream<Path> pathContent = recursiveContentOf(path)) { return pathContent.sorted().collect(toList()); } } private Stream<Path> recursiveContentOf(Path directory) { try { return walk(directory).filter(p -> !p.equals(directory)); } catch (IOException e) { throw new UncheckedIOException("Unable to walk recursively the directory :<%s>".formatted(directory), e); } } private void assertIsDirectoryRecursivelyContaining(AssertionInfo info, Path actual, Predicate<Path> filter, String filterPresentation) { if (!isDirectoryRecursivelyContaining(info, actual, filter)) { throw failures.failure(info, directoryShouldContainRecursively(actual, sortedRecursiveContent(actual), filterPresentation)); } } private void assertIsDirectoryNotContaining(AssertionInfo info, Path actual, Filter<Path> filter, String filterPresentation) { List<Path> matchingPaths = filterDirectory(info, actual, filter); if (!matchingPaths.isEmpty()) { throw failures.failure(info, directoryShouldNotContain(actual, matchingPaths, filterPresentation)); } } private PathMatcher pathMatcher(AssertionInfo info, Path actual, String syntaxAndPattern) { assertNotNull(info, actual); return actual.getFileSystem().getPathMatcher(syntaxAndPattern); } private static void assertNotNull(final AssertionInfo info, final Path actual) { Objects.instance().assertNotNull(info, actual); } private static void checkExpectedParentPathIsNotNull(final Path expected) { requireNonNull(expected, "expected parent path should not be null"); } private static void assertExpectedStartPathIsNotNull(final Path start) { requireNonNull(start, "the expected start path should not be null"); } private static void assertExpectedEndPathIsNotNull(final Path end) { requireNonNull(end, "the expected end path should not be null"); } private static Path toRealPath(Path path) { try { return path.toRealPath(); } catch (IOException e) { throw new UncheckedIOException(e); } } public void assertHasExtension(AssertionInfo info, Path actual, String expected) { requireNonNull(expected, "The expected extension should not be null."); assertIsRegularFile(info, actual); String extension = getExtension(actual).orElseThrow(() -> failures.failure(info, shouldHaveExtension(actual, expected))); if (!expected.equals(extension)) throw failures.failure(info, shouldHaveExtension(actual, extension, expected)); } public void assertHasNoExtension(AssertionInfo info, Path actual) { assertIsRegularFile(info, actual); Optional<String> extension = getExtension(actual); if (extension.isPresent()) throw failures.failure(info, shouldHaveNoExtension(actual, extension.get())); } private static Optional<String> getExtension(Path path) { String fileName = path.getFileName().toString(); return getFileNameExtension(fileName); } }
Paths
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest96.java
{ "start": 942, "end": 3614 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "CREATE TABLE \"CAOBOHAHA_IAU\".\"IAU_USERSESSION\" \n" + " ( \"IAU_ID\" NUMBER, \n" + " \"IAU_AUTHENTICATIONMETHOD\" VARCHAR2(255), \n" + " PRIMARY KEY (\"IAU_ID\")\n" + " USING INDEX (CREATE INDEX \"CAOBOHAHA_IAU\".\"DYN_IAU_USERSESSION_INDEX\" ON \"CAOBOHAHA_IAU\".\"IAU_USERSESSION\" (\"IAU_ID\") \n" + " PCTFREE 10 INITRANS 2 MAXTRANS 255 COMPUTE STATISTICS \n" + " TABLESPACE \"CAOBOHAHA_IAU\" ) ENABLE\n" + " ) SEGMENT CREATION DEFERRED \n" + " PCTFREE 10 PCTUSED 40 INITRANS 1 MAXTRANS 255 \n" + " NOCOMPRESS LOGGING\n" + " TABLESPACE \"CAOBOHAHA_IAU\" "; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals("CREATE TABLE \"CAOBOHAHA_IAU\".\"IAU_USERSESSION\" (\n" + "\t\"IAU_ID\" NUMBER,\n" + "\t\"IAU_AUTHENTICATIONMETHOD\" VARCHAR2(255),\n" + "\tPRIMARY KEY (\"IAU_ID\")\n" + "\t\tUSING INDEX (CREATE INDEX \"CAOBOHAHA_IAU\".\"DYN_IAU_USERSESSION_INDEX\" ON \"CAOBOHAHA_IAU\".\"IAU_USERSESSION\"(\"IAU_ID\")\n" + "\t\tCOMPUTE STATISTICS\n" + "\t\tPCTFREE 10\n" + "\t\tINITRANS 2\n" + "\t\tMAXTRANS 255\n" + "\t\tTABLESPACE \"CAOBOHAHA_IAU\")\n" + "\t\tENABLE\n" + ")\n" + "PCTFREE 10\n" + "PCTUSED 40\n" + "INITRANS 1\n" + "MAXTRANS 255\n" + "NOCOMPRESS\n" + "LOGGING\n" + "TABLESPACE \"CAOBOHAHA_IAU\"", stmt.toString()); } }
OracleCreateTableTest96
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/spring/tx/JMSTransactionalClientWithRollbackIT.java
{ "start": 2214, "end": 2478 }
class ____ implements Processor { private int count; @Override public void process(Exchange exchange) { exchange.getIn().setBody("Bye World"); exchange.getIn().setHeader("count", ++count); } } }
MyProcessor
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/multipart/MultipartMessageBodyWriter.java
{ "start": 1660, "end": 10738 }
class ____ extends ServerMessageBodyWriter.AllWriteableMessageBodyWriter { private static final String DOUBLE_DASH = "--"; private static final String LINE_SEPARATOR = "\r\n"; private static final String BOUNDARY_PARAM = "boundary"; @Override public void writeTo(Object o, Class<?> aClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream outputStream) throws IOException, WebApplicationException { writeMultiformData(o, mediaType, outputStream); } @Override public void writeResponse(Object o, Type genericType, ServerRequestContext context) throws WebApplicationException, IOException { writeMultiformData(o, context.getResponseMediaType(), context.getOrCreateOutputStream()); } public static final String getGeneratedMapperClassNameFor(String className) { return className + "_generated_mapper"; } private void writeMultiformData(Object o, MediaType mediaType, OutputStream outputStream) throws IOException { ResteasyReactiveRequestContext requestContext = CurrentRequestManager.get(); String boundary = generateBoundary(); appendBoundaryIntoMediaType(requestContext, boundary, mediaType); MultipartFormDataOutput formData; if (o instanceof MultipartFormDataOutput) { formData = (MultipartFormDataOutput) o; } else { formData = toFormData(o); } write(formData, boundary, outputStream, requestContext); } private MultipartFormDataOutput toFormData(Object o) { String transformer = getGeneratedMapperClassNameFor(o.getClass().getName()); BeanFactory.BeanInstance instance = new ReflectionBeanFactoryCreator().apply(transformer).createInstance(); return ((MultipartOutputInjectionTarget) instance.getInstance()).mapFrom(o); } private void write(MultipartFormDataOutput formDataOutput, String boundary, OutputStream outputStream, ResteasyReactiveRequestContext requestContext) throws IOException { Charset charset = requestContext.getDeployment().getRuntimeConfiguration().body().defaultCharset(); String boundaryLine = "--" + boundary; Map<String, List<PartItem>> parts = formDataOutput.getAllFormData(); for (var entry : parts.entrySet()) { String partName = entry.getKey(); List<PartItem> partItems = entry.getValue(); if (partItems.isEmpty()) { continue; } for (PartItem part : partItems) { Object partValue = part.getEntity(); if (partValue != null) { if (isListOf(part, File.class) || isListOf(part, FileDownload.class)) { List<Object> list = (List<Object>) partValue; for (int i = 0; i < list.size(); i++) { writePart(partName, list.get(i), part, boundaryLine, charset, outputStream, requestContext); } } else { writePart(partName, partValue, part, boundaryLine, charset, outputStream, requestContext); } } } } // write boundary: -- ... -- write(outputStream, boundaryLine + DOUBLE_DASH, charset); } private void writePart(String partName, Object partValue, PartItem part, String boundaryLine, Charset charset, OutputStream outputStream, ResteasyReactiveRequestContext requestContext) throws IOException { MediaType partType = part.getMediaType(); if (partValue instanceof FileDownload) { FileDownload fileDownload = (FileDownload) partValue; partValue = fileDownload.filePath().toFile(); // overwrite properties if set partName = isNotEmpty(fileDownload.name()) ? fileDownload.name() : partName; partType = isNotEmpty(fileDownload.contentType()) ? MediaType.valueOf(fileDownload.contentType()) : partType; charset = isNotEmpty(fileDownload.charSet()) ? Charset.forName(fileDownload.charSet()) : charset; } // write boundary: --... writeLine(outputStream, boundaryLine, charset); // write headers writeHeaders(partName, partValue, part, charset, outputStream); // extra line writeLine(outputStream, charset); // write content writeEntity(outputStream, partValue, partType, requestContext); // extra line writeLine(outputStream, charset); } private void writeHeaders(String partName, Object partValue, PartItem part, Charset charset, OutputStream outputStream) throws IOException { part.getHeaders().put(HttpHeaders.CONTENT_DISPOSITION, List.of("form-data; name=\"" + partName + "\"" + getFileNameIfFile(partValue, part.getFilename()))); part.getHeaders().put(CONTENT_TYPE, List.of(part.getMediaType())); for (Map.Entry<String, List<Object>> entry : part.getHeaders().entrySet()) { writeLine(outputStream, entry.getKey() + ": " + entry.getValue().stream().map(String::valueOf) .collect(Collectors.joining("; ")), charset); } } private String getFileNameIfFile(Object value, String partFileName) { if (value instanceof File) { return "; filename=\"" + ((File) value).getName() + "\""; } else if (value instanceof FileDownload) { return "; filename=\"" + ((FileDownload) value).fileName() + "\""; } else if (partFileName != null) { return "; filename=\"" + partFileName + "\""; } return ""; } private void writeLine(OutputStream os, String text, Charset defaultCharset) throws IOException { write(os, text, defaultCharset); writeLine(os, defaultCharset); } private void write(OutputStream os, String text, Charset defaultCharset) throws IOException { write(os, text.getBytes(defaultCharset)); } private void write(OutputStream os, byte[] bytes) throws IOException { os.write(bytes); } private void writeLine(OutputStream os, Charset defaultCharset) throws IOException { os.write(LINE_SEPARATOR.getBytes(defaultCharset)); } private void writeEntity(OutputStream os, Object entity, MediaType mediaType, ResteasyReactiveRequestContext context) throws IOException { ServerSerialisers serializers = context.getDeployment().getSerialisers(); Class<?> entityClass = entity.getClass(); Type entityType = null; @SuppressWarnings("unchecked") MessageBodyWriter<Object>[] writers = (MessageBodyWriter<Object>[]) serializers .findWriters(null, entityClass, mediaType, RuntimeType.SERVER) .toArray(ServerSerialisers.NO_WRITER); boolean wrote = false; for (MessageBodyWriter<Object> writer : writers) { if (writer.isWriteable(entityClass, entityType, Serialisers.NO_ANNOTATION, mediaType)) { try (NoopCloseAndFlushOutputStream writerOutput = new NoopCloseAndFlushOutputStream(os)) { // FIXME: spec doesn't really say what headers we should use here writer.writeTo(entity, entityClass, entityType, Serialisers.NO_ANNOTATION, mediaType, new QuarkusMultivaluedHashMap<>(), writerOutput); wrote = true; } break; } } if (!wrote) { throw new IllegalStateException("Could not find MessageBodyWriter for " + entityClass + " as " + mediaType); } } private String generateBoundary() { return UUID.randomUUID().toString(); } private void appendBoundaryIntoMediaType(ResteasyReactiveRequestContext requestContext, String boundary, MediaType mediaType) { MediaType mediaTypeWithBoundary = new MediaType(mediaType.getType(), mediaType.getSubtype(), Collections.singletonMap(BOUNDARY_PARAM, boundary)); requestContext.setResponseContentType(mediaTypeWithBoundary); // this is a total hack, but it's needed to make RestResponse<MultipartFormDataOutput> work properly requestContext.serverResponse().setResponseHeader(CONTENT_TYPE, mediaTypeWithBoundary.toString()); if (requestContext.getResponse().isCreated()) { requestContext.getResponse().get().getHeaders().remove(CONTENT_TYPE); } } private boolean isNotEmpty(String str) { return str != null && !str.isEmpty(); } private boolean isListOf(PartItem part, Class<?> paramType) { if (!(part.getEntity() instanceof Collection)) { return false; } return paramType.getName().equals(part.getGenericType()); } }
MultipartMessageBodyWriter
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-jetty/src/main/java/smoketest/jetty/service/HttpHeaderService.java
{ "start": 828, "end": 1202 }
class ____ { @Value("${server.jetty.max-http-response-header-size}") private int maxHttpResponseHeaderSize; /** * Generates a header value, which is longer than * 'server.jetty.max-http-response-header-size'. * @return the header value */ public String getHeaderValue() { return StringUtil.repeat('A', this.maxHttpResponseHeaderSize + 1); } }
HttpHeaderService
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/ingest/SimulateDocumentVerboseResult.java
{ "start": 1004, "end": 2361 }
class ____ implements SimulateDocumentResult { public static final String PROCESSOR_RESULT_FIELD = "processor_results"; private final List<SimulateProcessorResult> processorResults; public SimulateDocumentVerboseResult(List<SimulateProcessorResult> processorResults) { this.processorResults = processorResults; } /** * Read from a stream. */ public SimulateDocumentVerboseResult(StreamInput in) throws IOException { int size = in.readVInt(); processorResults = new ArrayList<>(size); for (int i = 0; i < size; i++) { processorResults.add(new SimulateProcessorResult(in)); } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeCollection(processorResults); } public List<SimulateProcessorResult> getProcessorResults() { return processorResults; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.startArray(PROCESSOR_RESULT_FIELD); for (SimulateProcessorResult processorResult : processorResults) { processorResult.toXContent(builder, params); } builder.endArray(); builder.endObject(); return builder; } }
SimulateDocumentVerboseResult
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/balancer/Dispatcher.java
{ "start": 20169, "end": 26478 }
class ____ { final StorageType storageType; final long maxSize2Move; private long scheduledSize = 0L; private StorageGroup(StorageType storageType, long maxSize2Move) { this.storageType = storageType; this.maxSize2Move = maxSize2Move; } public StorageType getStorageType() { return storageType; } private DDatanode getDDatanode() { return DDatanode.this; } public DatanodeInfo getDatanodeInfo() { return DDatanode.this.datanode; } /** Decide if still need to move more bytes */ boolean hasSpaceForScheduling() { return hasSpaceForScheduling(0L); } synchronized boolean hasSpaceForScheduling(long size) { return availableSizeToMove() > size; } /** @return the total number of bytes that need to be moved */ synchronized long availableSizeToMove() { return maxSize2Move - scheduledSize; } /** increment scheduled size */ public synchronized void incScheduledSize(long size) { scheduledSize += size; } /** @return scheduled size */ synchronized long getScheduledSize() { return scheduledSize; } /** Reset scheduled size to zero. */ synchronized void resetScheduledSize() { scheduledSize = 0L; } private PendingMove addPendingMove(DBlock block, final PendingMove pm) { if (getDDatanode().addPendingBlock(pm)) { if (pm.markMovedIfGoodBlock(block, getStorageType())) { incScheduledSize(pm.reportedBlock.getNumBytes()); return pm; } else { getDDatanode().removePendingBlock(pm); } } return null; } /** @return the name for display */ String getDisplayName() { return datanode + ":" + storageType; } @Override public String toString() { return getDisplayName(); } @Override public int hashCode() { return getStorageType().hashCode() ^ getDatanodeInfo().hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } else if (!(obj instanceof StorageGroup)) { return false; } else { final StorageGroup that = (StorageGroup) obj; return this.getStorageType() == that.getStorageType() && this.getDatanodeInfo().equals(that.getDatanodeInfo()); } } } final DatanodeInfo datanode; private final EnumMap<StorageType, Source> sourceMap = new EnumMap<StorageType, Source>(StorageType.class); private final EnumMap<StorageType, StorageGroup> targetMap = new EnumMap<StorageType, StorageGroup>(StorageType.class); protected long delayUntil = 0L; /** blocks being moved but not confirmed yet */ private final List<PendingMove> pendings; private volatile boolean hasFailure = false; private final Map<Long, Set<DatanodeInfo>> blockPinningFailures = new ConcurrentHashMap<>(); private volatile boolean hasSuccess = false; private ExecutorService moveExecutor; @Override public String toString() { return getClass().getSimpleName() + ":" + datanode; } private DDatanode(DatanodeInfo datanode, int maxConcurrentMoves) { this.datanode = datanode; this.pendings = new ArrayList<PendingMove>(maxConcurrentMoves); } public DatanodeInfo getDatanodeInfo() { return datanode; } synchronized ExecutorService initMoveExecutor(int poolSize) { return moveExecutor = Executors.newFixedThreadPool(poolSize); } synchronized ExecutorService getMoveExecutor() { return moveExecutor; } synchronized void shutdownMoveExecutor() { if (moveExecutor != null) { moveExecutor.shutdown(); moveExecutor = null; } } private static <G extends StorageGroup> void put(StorageType storageType, G g, EnumMap<StorageType, G> map) { final StorageGroup existing = map.put(storageType, g); Preconditions.checkState(existing == null); } public StorageGroup addTarget(StorageType storageType, long maxSize2Move) { final StorageGroup g = new StorageGroup(storageType, maxSize2Move); put(storageType, g, targetMap); return g; } public Source addSource(StorageType storageType, long maxSize2Move, Dispatcher d) { final Source s = d.new Source(storageType, maxSize2Move, this); put(storageType, s, sourceMap); return s; } synchronized private void activateDelay(long delta) { delayUntil = Time.monotonicNow() + delta; LOG.info(this + " activateDelay " + delta/1000.0 + " seconds"); } synchronized private boolean isDelayActive() { if (delayUntil == 0 || Time.monotonicNow() > delayUntil) { delayUntil = 0; return false; } return true; } /** Check if all the dispatched moves are done */ synchronized boolean isPendingQEmpty() { return pendings.isEmpty(); } /** Add a scheduled block move to the node */ synchronized boolean addPendingBlock(PendingMove pendingBlock) { if (!isDelayActive()) { return pendings.add(pendingBlock); } return false; } /** Remove a scheduled block move from the node */ synchronized boolean removePendingBlock(PendingMove pendingBlock) { return pendings.remove(pendingBlock); } void setHasFailure() { this.hasFailure = true; } private void addBlockPinningFailures(long blockId, DatanodeInfo source) { blockPinningFailures.compute(blockId, (key, pinnedLocations) -> { Set<DatanodeInfo> newPinnedLocations; if (pinnedLocations == null) { newPinnedLocations = new HashSet<>(); } else { newPinnedLocations = pinnedLocations; } newPinnedLocations.add(source); return newPinnedLocations; }); } Map<Long, Set<DatanodeInfo>> getBlockPinningFailureList() { return blockPinningFailures; } void setHasSuccess() { this.hasSuccess = true; } } /** A node that can be the sources of a block move */ public
StorageGroup
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractInputStreamAssert.java
{ "start": 1899, "end": 2383 }
class ____ all implementations of assertions for {@link InputStream}s. * @param <SELF> the "self" type of this assertion class. Please read &quot;<a href="http://bit.ly/1IZIRcY" * target="_blank">Emulating 'self types' using Java Generics to simplify fluent API implementation</a>&quot; * for more details. * @param <ACTUAL> the type of the "actual" value. * * @author Matthieu Baechler * @author Mikhail Mazursky * @author Stefan Birkner */ public abstract
for
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/util/TestCyclicIteration.java
{ "start": 1105, "end": 2359 }
class ____ { @Test public void testCyclicIteration() throws Exception { for(int n = 0; n < 5; n++) { checkCyclicIteration(n); } } private static void checkCyclicIteration(int numOfElements) { //create a tree map final NavigableMap<Integer, Integer> map = new TreeMap<Integer, Integer>(); final Integer[] integers = new Integer[numOfElements]; for(int i = 0; i < integers.length; i++) { integers[i] = 2*i; map.put(integers[i], integers[i]); } System.out.println("\n\nintegers=" + Arrays.asList(integers)); System.out.println("map=" + map); //try starting everywhere for(int start = -1; start <= 2*integers.length - 1; start++) { //get a cyclic iteration final List<Integer> iteration = new ArrayList<Integer>(); for(Map.Entry<Integer, Integer> e : new CyclicIteration<Integer, Integer>(map, start)) { iteration.add(e.getKey()); } System.out.println("start=" + start + ", iteration=" + iteration); //verify results for(int i = 0; i < integers.length; i++) { final int j = ((start+2)/2 + i)%integers.length; assertEquals(iteration.get(i), integers[j], "i=" + i + ", j=" + j); } } } }
TestCyclicIteration
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/results/graph/embeddable/internal/EmbeddableExpressionResultImpl.java
{ "start": 1581, "end": 5160 }
class ____<T> extends AbstractFetchParent implements EmbeddableResultGraphNode, DomainResult<T>, EmbeddableResult<T>, InitializerProducer<EmbeddableExpressionResultImpl<T>> { private final String resultVariable; private final boolean containsAnyNonScalars; private final EmbeddableMappingType fetchContainer; public EmbeddableExpressionResultImpl( NavigablePath navigablePath, EmbeddableValuedModelPart modelPart, SqlTuple sqlExpression, String resultVariable, DomainResultCreationState creationState) { super( navigablePath ); this.fetchContainer = modelPart.getEmbeddableTypeDescriptor(); this.resultVariable = resultVariable; final ImmutableFetchList.Builder fetches = new ImmutableFetchList.Builder( modelPart ); final EmbeddableMappingType mappingType = modelPart.getEmbeddableTypeDescriptor(); final int numberOfAttributeMappings = mappingType.getNumberOfAttributeMappings(); final SqlAstCreationState sqlAstCreationState = creationState.getSqlAstCreationState(); final TypeConfiguration typeConfiguration = sqlAstCreationState.getCreationContext().getTypeConfiguration(); final SqlExpressionResolver sqlExpressionResolver = sqlAstCreationState.getSqlExpressionResolver(); for ( int i = 0; i < numberOfAttributeMappings; i++ ) { final BasicAttributeMapping attribute = (BasicAttributeMapping) mappingType.getAttributeMapping( i ); final SqlSelection sqlSelection = sqlExpressionResolver.resolveSqlSelection( sqlExpression.getExpressions().get( i ), attribute.getJavaType(), this, typeConfiguration ); fetches.add( new BasicFetch<>( sqlSelection.getValuesArrayPosition(), this, resolveNavigablePath( attribute ), attribute, FetchTiming.IMMEDIATE, creationState, !sqlSelection.isVirtual() ) ); } resetFetches( fetches.build() ); this.containsAnyNonScalars = determineIfContainedAnyScalars( getFetches() ); } private static boolean determineIfContainedAnyScalars(ImmutableFetchList fetches) { for ( Fetch fetch : fetches ) { if ( fetch.containsAnyNonScalarResults() ) { return true; } } return false; } @Override public String getResultVariable() { return resultVariable; } @Override public boolean containsAnyNonScalarResults() { return containsAnyNonScalars; } @Override public EmbeddableMappingType getFetchContainer() { return this.fetchContainer; } @Override public JavaType<?> getResultJavaType() { return getReferencedMappingType().getJavaType(); } @Override public EmbeddableMappingType getReferencedMappingType() { return getFetchContainer(); } @Override public EmbeddableValuedModelPart getReferencedMappingContainer() { return getFetchContainer().getEmbeddedValueMapping(); } @Override public DomainResultAssembler<T> createResultAssembler( InitializerParent<?> parent, AssemblerCreationState creationState) { //noinspection unchecked return new EmbeddableAssembler( creationState.resolveInitializer( this, parent, this ).asEmbeddableInitializer() ); } @Override public Initializer<?> createInitializer( EmbeddableExpressionResultImpl<T> resultGraphNode, InitializerParent<?> parent, AssemblerCreationState creationState) { return resultGraphNode.createInitializer( parent, creationState ); } @Override public Initializer<?> createInitializer(InitializerParent<?> parent, AssemblerCreationState creationState) { return new EmbeddableInitializerImpl( this, null, null, parent, creationState, true ); } }
EmbeddableExpressionResultImpl
java
alibaba__nacos
common/src/main/java/com/alibaba/nacos/common/model/RequestHttpEntity.java
{ "start": 938, "end": 2661 }
class ____ { private final Header headers = Header.newInstance(); private final HttpClientConfig httpClientConfig; private final Query query; private final Object body; public RequestHttpEntity(Header header, Query query) { this(null, header, query); } public RequestHttpEntity(Header header, Object body) { this(null, header, body); } public RequestHttpEntity(Header header, Query query, Object body) { this(null, header, query, body); } public RequestHttpEntity(HttpClientConfig httpClientConfig, Header header, Query query) { this(httpClientConfig, header, query, null); } public RequestHttpEntity(HttpClientConfig httpClientConfig, Header header, Object body) { this(httpClientConfig, header, null, body); } public RequestHttpEntity(HttpClientConfig httpClientConfig, Header header, Query query, Object body) { handleHeader(header); this.httpClientConfig = httpClientConfig; this.query = query; this.body = body; } private void handleHeader(Header header) { if (header != null && !header.getHeader().isEmpty()) { Map<String, String> headerMap = header.getHeader(); headers.addAll(headerMap); } } public Header getHeaders() { return headers; } public Query getQuery() { return query; } public Object getBody() { return body; } public HttpClientConfig getHttpClientConfig() { return httpClientConfig; } public boolean isEmptyBody() { return body == null; } }
RequestHttpEntity
java
apache__camel
components/camel-box/camel-box-component/src/generated/java/org/apache/camel/component/box/BoxFilesManagerEndpointConfigurationConfigurer.java
{ "start": 732, "end": 17480 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("Access", com.box.sdk.BoxSharedLink.Access.class); map.put("AccessTokenCache", com.box.sdk.IAccessTokenCache.class); map.put("ApiName", org.apache.camel.component.box.internal.BoxApiName.class); map.put("AuthenticationType", java.lang.String.class); map.put("Check", java.lang.Boolean.class); map.put("ClientId", java.lang.String.class); map.put("ClientSecret", java.lang.String.class); map.put("Content", java.io.InputStream.class); map.put("Created", java.util.Date.class); map.put("DestinationFolderId", java.lang.String.class); map.put("EncryptionAlgorithm", com.box.sdk.EncryptionAlgorithm.class); map.put("EnterpriseId", java.lang.String.class); map.put("Fields", java.lang.String[].class); map.put("FileContent", java.io.InputStream.class); map.put("FileId", java.lang.String.class); map.put("FileName", java.lang.String.class); map.put("FileSize", java.lang.Long.class); map.put("HttpParams", java.util.Map.class); map.put("Info", com.box.sdk.BoxFile.Info.class); map.put("Listener", com.box.sdk.ProgressListener.class); map.put("MaxCacheEntries", int.class); map.put("Metadata", com.box.sdk.Metadata.class); map.put("MethodName", java.lang.String.class); map.put("Modified", java.util.Date.class); map.put("NewFileName", java.lang.String.class); map.put("NewName", java.lang.String.class); map.put("Output", java.io.OutputStream.class); map.put("ParentFolderId", java.lang.String.class); map.put("Permissions", com.box.sdk.BoxSharedLink.Permissions.class); map.put("PrivateKeyFile", java.lang.String.class); map.put("PrivateKeyPassword", java.lang.String.class); map.put("PublicKeyId", java.lang.String.class); map.put("RangeEnd", java.lang.Long.class); map.put("RangeStart", java.lang.Long.class); map.put("Size", java.lang.Long.class); map.put("SslContextParameters", org.apache.camel.support.jsse.SSLContextParameters.class); map.put("TypeName", java.lang.String.class); map.put("UnshareDate", java.util.Date.class); map.put("UserId", java.lang.String.class); map.put("UserName", java.lang.String.class); map.put("UserPassword", java.lang.String.class); map.put("Version", java.lang.Integer.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.component.box.BoxFilesManagerEndpointConfiguration target = (org.apache.camel.component.box.BoxFilesManagerEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "access": target.setAccess(property(camelContext, com.box.sdk.BoxSharedLink.Access.class, value)); return true; case "accesstokencache": case "accessTokenCache": target.setAccessTokenCache(property(camelContext, com.box.sdk.IAccessTokenCache.class, value)); return true; case "apiname": case "apiName": target.setApiName(property(camelContext, org.apache.camel.component.box.internal.BoxApiName.class, value)); return true; case "authenticationtype": case "authenticationType": target.setAuthenticationType(property(camelContext, java.lang.String.class, value)); return true; case "check": target.setCheck(property(camelContext, java.lang.Boolean.class, value)); return true; case "clientid": case "clientId": target.setClientId(property(camelContext, java.lang.String.class, value)); return true; case "clientsecret": case "clientSecret": target.setClientSecret(property(camelContext, java.lang.String.class, value)); return true; case "content": target.setContent(property(camelContext, java.io.InputStream.class, value)); return true; case "created": target.setCreated(property(camelContext, java.util.Date.class, value)); return true; case "destinationfolderid": case "destinationFolderId": target.setDestinationFolderId(property(camelContext, java.lang.String.class, value)); return true; case "encryptionalgorithm": case "encryptionAlgorithm": target.setEncryptionAlgorithm(property(camelContext, com.box.sdk.EncryptionAlgorithm.class, value)); return true; case "enterpriseid": case "enterpriseId": target.setEnterpriseId(property(camelContext, java.lang.String.class, value)); return true; case "fields": target.setFields(property(camelContext, java.lang.String[].class, value)); return true; case "filecontent": case "fileContent": target.setFileContent(property(camelContext, java.io.InputStream.class, value)); return true; case "fileid": case "fileId": target.setFileId(property(camelContext, java.lang.String.class, value)); return true; case "filename": case "fileName": target.setFileName(property(camelContext, java.lang.String.class, value)); return true; case "filesize": case "fileSize": target.setFileSize(property(camelContext, java.lang.Long.class, value)); return true; case "httpparams": case "httpParams": target.setHttpParams(property(camelContext, java.util.Map.class, value)); return true; case "info": target.setInfo(property(camelContext, com.box.sdk.BoxFile.Info.class, value)); return true; case "listener": target.setListener(property(camelContext, com.box.sdk.ProgressListener.class, value)); return true; case "maxcacheentries": case "maxCacheEntries": target.setMaxCacheEntries(property(camelContext, int.class, value)); return true; case "metadata": target.setMetadata(property(camelContext, com.box.sdk.Metadata.class, value)); return true; case "methodname": case "methodName": target.setMethodName(property(camelContext, java.lang.String.class, value)); return true; case "modified": target.setModified(property(camelContext, java.util.Date.class, value)); return true; case "newfilename": case "newFileName": target.setNewFileName(property(camelContext, java.lang.String.class, value)); return true; case "newname": case "newName": target.setNewName(property(camelContext, java.lang.String.class, value)); return true; case "output": target.setOutput(property(camelContext, java.io.OutputStream.class, value)); return true; case "parentfolderid": case "parentFolderId": target.setParentFolderId(property(camelContext, java.lang.String.class, value)); return true; case "permissions": target.setPermissions(property(camelContext, com.box.sdk.BoxSharedLink.Permissions.class, value)); return true; case "privatekeyfile": case "privateKeyFile": target.setPrivateKeyFile(property(camelContext, java.lang.String.class, value)); return true; case "privatekeypassword": case "privateKeyPassword": target.setPrivateKeyPassword(property(camelContext, java.lang.String.class, value)); return true; case "publickeyid": case "publicKeyId": target.setPublicKeyId(property(camelContext, java.lang.String.class, value)); return true; case "rangeend": case "rangeEnd": target.setRangeEnd(property(camelContext, java.lang.Long.class, value)); return true; case "rangestart": case "rangeStart": target.setRangeStart(property(camelContext, java.lang.Long.class, value)); return true; case "size": target.setSize(property(camelContext, java.lang.Long.class, value)); return true; case "sslcontextparameters": case "sslContextParameters": target.setSslContextParameters(property(camelContext, org.apache.camel.support.jsse.SSLContextParameters.class, value)); return true; case "typename": case "typeName": target.setTypeName(property(camelContext, java.lang.String.class, value)); return true; case "unsharedate": case "unshareDate": target.setUnshareDate(property(camelContext, java.util.Date.class, value)); return true; case "userid": case "userId": target.setUserId(property(camelContext, java.lang.String.class, value)); return true; case "username": case "userName": target.setUserName(property(camelContext, java.lang.String.class, value)); return true; case "userpassword": case "userPassword": target.setUserPassword(property(camelContext, java.lang.String.class, value)); return true; case "version": target.setVersion(property(camelContext, java.lang.Integer.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "access": return com.box.sdk.BoxSharedLink.Access.class; case "accesstokencache": case "accessTokenCache": return com.box.sdk.IAccessTokenCache.class; case "apiname": case "apiName": return org.apache.camel.component.box.internal.BoxApiName.class; case "authenticationtype": case "authenticationType": return java.lang.String.class; case "check": return java.lang.Boolean.class; case "clientid": case "clientId": return java.lang.String.class; case "clientsecret": case "clientSecret": return java.lang.String.class; case "content": return java.io.InputStream.class; case "created": return java.util.Date.class; case "destinationfolderid": case "destinationFolderId": return java.lang.String.class; case "encryptionalgorithm": case "encryptionAlgorithm": return com.box.sdk.EncryptionAlgorithm.class; case "enterpriseid": case "enterpriseId": return java.lang.String.class; case "fields": return java.lang.String[].class; case "filecontent": case "fileContent": return java.io.InputStream.class; case "fileid": case "fileId": return java.lang.String.class; case "filename": case "fileName": return java.lang.String.class; case "filesize": case "fileSize": return java.lang.Long.class; case "httpparams": case "httpParams": return java.util.Map.class; case "info": return com.box.sdk.BoxFile.Info.class; case "listener": return com.box.sdk.ProgressListener.class; case "maxcacheentries": case "maxCacheEntries": return int.class; case "metadata": return com.box.sdk.Metadata.class; case "methodname": case "methodName": return java.lang.String.class; case "modified": return java.util.Date.class; case "newfilename": case "newFileName": return java.lang.String.class; case "newname": case "newName": return java.lang.String.class; case "output": return java.io.OutputStream.class; case "parentfolderid": case "parentFolderId": return java.lang.String.class; case "permissions": return com.box.sdk.BoxSharedLink.Permissions.class; case "privatekeyfile": case "privateKeyFile": return java.lang.String.class; case "privatekeypassword": case "privateKeyPassword": return java.lang.String.class; case "publickeyid": case "publicKeyId": return java.lang.String.class; case "rangeend": case "rangeEnd": return java.lang.Long.class; case "rangestart": case "rangeStart": return java.lang.Long.class; case "size": return java.lang.Long.class; case "sslcontextparameters": case "sslContextParameters": return org.apache.camel.support.jsse.SSLContextParameters.class; case "typename": case "typeName": return java.lang.String.class; case "unsharedate": case "unshareDate": return java.util.Date.class; case "userid": case "userId": return java.lang.String.class; case "username": case "userName": return java.lang.String.class; case "userpassword": case "userPassword": return java.lang.String.class; case "version": return java.lang.Integer.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.component.box.BoxFilesManagerEndpointConfiguration target = (org.apache.camel.component.box.BoxFilesManagerEndpointConfiguration) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "access": return target.getAccess(); case "accesstokencache": case "accessTokenCache": return target.getAccessTokenCache(); case "apiname": case "apiName": return target.getApiName(); case "authenticationtype": case "authenticationType": return target.getAuthenticationType(); case "check": return target.getCheck(); case "clientid": case "clientId": return target.getClientId(); case "clientsecret": case "clientSecret": return target.getClientSecret(); case "content": return target.getContent(); case "created": return target.getCreated(); case "destinationfolderid": case "destinationFolderId": return target.getDestinationFolderId(); case "encryptionalgorithm": case "encryptionAlgorithm": return target.getEncryptionAlgorithm(); case "enterpriseid": case "enterpriseId": return target.getEnterpriseId(); case "fields": return target.getFields(); case "filecontent": case "fileContent": return target.getFileContent(); case "fileid": case "fileId": return target.getFileId(); case "filename": case "fileName": return target.getFileName(); case "filesize": case "fileSize": return target.getFileSize(); case "httpparams": case "httpParams": return target.getHttpParams(); case "info": return target.getInfo(); case "listener": return target.getListener(); case "maxcacheentries": case "maxCacheEntries": return target.getMaxCacheEntries(); case "metadata": return target.getMetadata(); case "methodname": case "methodName": return target.getMethodName(); case "modified": return target.getModified(); case "newfilename": case "newFileName": return target.getNewFileName(); case "newname": case "newName": return target.getNewName(); case "output": return target.getOutput(); case "parentfolderid": case "parentFolderId": return target.getParentFolderId(); case "permissions": return target.getPermissions(); case "privatekeyfile": case "privateKeyFile": return target.getPrivateKeyFile(); case "privatekeypassword": case "privateKeyPassword": return target.getPrivateKeyPassword(); case "publickeyid": case "publicKeyId": return target.getPublicKeyId(); case "rangeend": case "rangeEnd": return target.getRangeEnd(); case "rangestart": case "rangeStart": return target.getRangeStart(); case "size": return target.getSize(); case "sslcontextparameters": case "sslContextParameters": return target.getSslContextParameters(); case "typename": case "typeName": return target.getTypeName(); case "unsharedate": case "unshareDate": return target.getUnshareDate(); case "userid": case "userId": return target.getUserId(); case "username": case "userName": return target.getUserName(); case "userpassword": case "userPassword": return target.getUserPassword(); case "version": return target.getVersion(); default: return null; } } @Override public Object getCollectionValueType(Object target, String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "httpparams": case "httpParams": return java.lang.Object.class; default: return null; } } }
BoxFilesManagerEndpointConfigurationConfigurer
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/AnnotationsPropertySourceTests.java
{ "start": 9529, "end": 9647 }
interface ____ { String value(); } @AttributeLevelWithPrefixAnnotation("abc") static
TypeLevelWithPrefixAnnotation
java
redisson__redisson
redisson/src/test/java/org/redisson/RedissonListMultimapReactiveTest.java
{ "start": 228, "end": 640 }
class ____ extends BaseReactiveTest { @Test void testGet() { RListMultimapCacheReactive<String, String> multimap = redisson.getListMultimapCache("getListMultimapCache", StringCodec.INSTANCE); multimap.putAll("key", List.of("A", "B")).block(); Assertions.assertThat(multimap.get("key").readAll().block()).containsExactlyInAnyOrder("A", "B"); } }
RedissonListMultimapReactiveTest
java
google__error-prone
check_api/src/test/java/com/google/errorprone/util/ASTHelpersFindSuperMethodsTest.java
{ "start": 6324, "end": 6387 }
class ____ extends Scanner { // A `
FindSuperMethodsTestScanner
java
apache__flink
flink-connectors/flink-connector-datagen/src/test/java/org/apache/flink/connector/datagen/source/TestDataGenerators.java
{ "start": 1385, "end": 3926 }
class ____ { /** * Creates a source that emits provided {@code data}, waits for two checkpoints and emits the * same {@code data } again. It is intended only to be used for test purposes. See {@link * DoubleEmittingSourceReaderWithCheckpointsInBetween} for details. * * @param typeInfo The type information of the elements. * @param data The collection of elements to create the stream from. * @param <OUT> The type of the returned data stream. */ public static <OUT> DataGeneratorSource<OUT> fromDataWithSnapshotsLatch( Collection<OUT> data, TypeInformation<OUT> typeInfo) { IndexLookupGeneratorFunction<OUT> generatorFunction = new IndexLookupGeneratorFunction<>(typeInfo, data); return new DataGeneratorSource<>( (SourceReaderFactory<OUT, NumberSequenceSplit>) (readerContext) -> new DoubleEmittingSourceReaderWithCheckpointsInBetween<>( readerContext, generatorFunction), generatorFunction, data.size(), typeInfo); } /** * Creates a source that emits provided {@code data}, waits for two checkpoints and emits the * same {@code data } again. It is intended only to be used for test purposes. See {@link * DoubleEmittingSourceReaderWithCheckpointsInBetween} for details. * * @param typeInfo The type information of the elements. * @param data The collection of elements to create the stream from. * @param <OUT> The type of the returned data stream. * @param allowedToExit The boolean supplier that makes it possible to delay termination based * on external conditions. */ public static <OUT> DataGeneratorSource<OUT> fromDataWithSnapshotsLatch( Collection<OUT> data, TypeInformation<OUT> typeInfo, BooleanSupplier allowedToExit) { IndexLookupGeneratorFunction<OUT> generatorFunction = new IndexLookupGeneratorFunction<>(typeInfo, data); return new DataGeneratorSource<>( (SourceReaderFactory<OUT, NumberSequenceSplit>) (readerContext) -> new DoubleEmittingSourceReaderWithCheckpointsInBetween<>( readerContext, generatorFunction, allowedToExit), generatorFunction, data.size(), typeInfo); } }
TestDataGenerators
java
apache__camel
components/camel-twilio/src/test/java/org/apache/camel/component/twilio/AbstractTwilioTestSupport.java
{ "start": 1377, "end": 3298 }
class ____ extends CamelTestSupport { private static final String TEST_OPTIONS_PROPERTIES = "/test-options.properties"; private static Properties properties = new Properties(); static { loadProperties(); } private static void loadProperties() { // read Twilio component configuration from TEST_OPTIONS_PROPERTIES TestSupport.loadExternalPropertiesQuietly(properties, AbstractTwilioTestSupport.class, TEST_OPTIONS_PROPERTIES); } private static boolean hasCredentials() { if (properties.isEmpty()) { loadProperties(); } return !properties.getProperty("username", "").isEmpty() && !properties.getProperty("password", "").isEmpty(); } @Override protected CamelContext createCamelContext() throws Exception { final CamelContext context = super.createCamelContext(); Map<String, Object> options = new HashMap<>(); for (Map.Entry<Object, Object> entry : properties.entrySet()) { options.put(entry.getKey().toString(), entry.getValue().toString().isEmpty() ? "value" : entry.getValue()); } // add TwilioComponent to Camel context final TwilioComponent component = new TwilioComponent(context); PropertyBindingSupport.bindProperties(context, component, options); context.addComponent("twilio", component); return context; } @SuppressWarnings("unchecked") protected <T> T requestBodyAndHeaders(String endpointUri, Object body, Map<String, Object> headers) throws CamelExecutionException { return (T) template().requestBodyAndHeaders(endpointUri, body, headers); } @SuppressWarnings("unchecked") protected <T> T requestBody(String endpoint, Object body) throws CamelExecutionException { return (T) template().requestBody(endpoint, body); } }
AbstractTwilioTestSupport
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-sharedcachemanager/src/main/java/org/apache/hadoop/yarn/server/sharedcachemanager/webapp/SCMWebServer.java
{ "start": 2691, "end": 3034 }
class ____ extends WebApp { private final SharedCacheManager scm; public SCMWebApp(SharedCacheManager scm) { this.scm = scm; } @Override public void setup() { if (scm != null) { bind(SharedCacheManager.class).toInstance(scm); } route("/", SCMController.class, "overview"); } } }
SCMWebApp
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SshEndpointBuilderFactory.java
{ "start": 65829, "end": 69948 }
interface ____ extends AdvancedSshEndpointConsumerBuilder, AdvancedSshEndpointProducerBuilder { default SshEndpointBuilder basic() { return (SshEndpointBuilder) this; } /** * Sets the channel type to pass to the Channel as part of command * execution. Defaults to exec. * * The option is a: <code>java.lang.String</code> type. * * Default: exec * Group: advanced * * @param channelType the value to set * @return the dsl builder */ default AdvancedSshEndpointBuilder channelType(String channelType) { doSetProperty("channelType", channelType); return this; } /** * Instance of ClientBuilder used by the producer or consumer to create * a new SshClient. * * The option is a: <code>org.apache.sshd.client.ClientBuilder</code> * type. * * Group: advanced * * @param clientBuilder the value to set * @return the dsl builder */ default AdvancedSshEndpointBuilder clientBuilder(org.apache.sshd.client.ClientBuilder clientBuilder) { doSetProperty("clientBuilder", clientBuilder); return this; } /** * Instance of ClientBuilder used by the producer or consumer to create * a new SshClient. * * The option will be converted to a * <code>org.apache.sshd.client.ClientBuilder</code> type. * * Group: advanced * * @param clientBuilder the value to set * @return the dsl builder */ default AdvancedSshEndpointBuilder clientBuilder(String clientBuilder) { doSetProperty("clientBuilder", clientBuilder); return this; } /** * Whether to use compression, and if so which. * * The option is a: <code>java.lang.String</code> type. * * Group: advanced * * @param compressions the value to set * @return the dsl builder */ default AdvancedSshEndpointBuilder compressions(String compressions) { doSetProperty("compressions", compressions); return this; } /** * Sets the shellPrompt to be dropped when response is read after * command execution. * * The option is a: <code>java.lang.String</code> type. * * Group: advanced * * @param shellPrompt the value to set * @return the dsl builder */ default AdvancedSshEndpointBuilder shellPrompt(String shellPrompt) { doSetProperty("shellPrompt", shellPrompt); return this; } /** * Sets the sleep period in milliseconds to wait reading response from * shell prompt. Defaults to 100 milliseconds. * * The option is a: <code>long</code> type. * * Default: 100 * Group: advanced * * @param sleepForShellPrompt the value to set * @return the dsl builder */ default AdvancedSshEndpointBuilder sleepForShellPrompt(long sleepForShellPrompt) { doSetProperty("sleepForShellPrompt", sleepForShellPrompt); return this; } /** * Sets the sleep period in milliseconds to wait reading response from * shell prompt. Defaults to 100 milliseconds. * * The option will be converted to a <code>long</code> type. * * Default: 100 * Group: advanced * * @param sleepForShellPrompt the value to set * @return the dsl builder */ default AdvancedSshEndpointBuilder sleepForShellPrompt(String sleepForShellPrompt) { doSetProperty("sleepForShellPrompt", sleepForShellPrompt); return this; } } public
AdvancedSshEndpointBuilder
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/slack/message/MessageElement.java
{ "start": 428, "end": 485 }
interface ____ extends ToXContentObject {
MessageElement
java
apache__flink
flink-python/src/main/java/org/apache/flink/streaming/api/runners/python/beam/BeamDataStreamPythonFunctionRunner.java
{ "start": 2795, "end": 13305 }
class ____ extends BeamPythonFunctionRunner { private static final String TRANSFORM_ID_PREFIX = "transform-"; private static final String COLLECTION_PREFIX = "collection-"; private static final String CODER_PREFIX = "coder-"; @Nullable private final FlinkFnApi.CoderInfoDescriptor timerCoderDescriptor; private final String headOperatorFunctionUrn; private final List<FlinkFnApi.UserDefinedDataStreamFunction> userDefinedDataStreamFunctions; public BeamDataStreamPythonFunctionRunner( Environment environment, String taskName, ProcessPythonEnvironmentManager environmentManager, String headOperatorFunctionUrn, List<FlinkFnApi.UserDefinedDataStreamFunction> userDefinedDataStreamFunctions, @Nullable FlinkMetricContainer flinkMetricContainer, @Nullable KeyedStateBackend<?> keyedStateBackend, @Nullable OperatorStateBackend operatorStateBackend, @Nullable TypeSerializer<?> keySerializer, @Nullable TypeSerializer<?> namespaceSerializer, @Nullable TimerRegistration timerRegistration, MemoryManager memoryManager, double managedMemoryFraction, FlinkFnApi.CoderInfoDescriptor inputCoderDescriptor, FlinkFnApi.CoderInfoDescriptor outputCoderDescriptor, @Nullable FlinkFnApi.CoderInfoDescriptor timerCoderDescriptor, Map<String, FlinkFnApi.CoderInfoDescriptor> sideOutputCoderDescriptors) { super( environment, taskName, environmentManager, flinkMetricContainer, keyedStateBackend, operatorStateBackend, keySerializer, namespaceSerializer, timerRegistration, memoryManager, managedMemoryFraction, inputCoderDescriptor, outputCoderDescriptor, sideOutputCoderDescriptors); this.headOperatorFunctionUrn = Preconditions.checkNotNull(headOperatorFunctionUrn); Preconditions.checkArgument( userDefinedDataStreamFunctions != null && userDefinedDataStreamFunctions.size() >= 1); this.userDefinedDataStreamFunctions = userDefinedDataStreamFunctions; this.timerCoderDescriptor = timerCoderDescriptor; } @Override protected void buildTransforms(RunnerApi.Components.Builder componentsBuilder) { for (int i = 0; i < userDefinedDataStreamFunctions.size(); i++) { final Map<String, String> outputCollectionMap = new HashMap<>(); // Prepare side outputs if (i == userDefinedDataStreamFunctions.size() - 1) { for (Map.Entry<String, FlinkFnApi.CoderInfoDescriptor> entry : sideOutputCoderDescriptors.entrySet()) { final String reviseCollectionId = COLLECTION_PREFIX + "revise-" + entry.getKey(); final String reviseCoderId = CODER_PREFIX + "revise-" + entry.getKey(); outputCollectionMap.put(entry.getKey(), reviseCollectionId); addCollectionToComponents(componentsBuilder, reviseCollectionId, reviseCoderId); } } // Prepare main outputs final String outputCollectionId = COLLECTION_PREFIX + i; final String outputCoderId = CODER_PREFIX + i; outputCollectionMap.put(MAIN_OUTPUT_NAME, outputCollectionId); addCollectionToComponents(componentsBuilder, outputCollectionId, outputCoderId); final String transformId = TRANSFORM_ID_PREFIX + i; final FlinkFnApi.UserDefinedDataStreamFunction functionProto = userDefinedDataStreamFunctions.get(i); if (i == 0) { addTransformToComponents( componentsBuilder, transformId, createUdfPayload(functionProto, headOperatorFunctionUrn, true), INPUT_COLLECTION_ID, outputCollectionMap); } else { addTransformToComponents( componentsBuilder, transformId, createUdfPayload(functionProto, STATELESS_FUNCTION_URN, false), COLLECTION_PREFIX + (i - 1), outputCollectionMap); } } // Add REVISE_OUTPUT transformation for side outputs for (Map.Entry<String, FlinkFnApi.CoderInfoDescriptor> entry : sideOutputCoderDescriptors.entrySet()) { addTransformToComponents( componentsBuilder, TRANSFORM_ID_PREFIX + "revise-" + entry.getKey(), createRevisePayload(), COLLECTION_PREFIX + "revise-" + entry.getKey(), Collections.singletonMap(MAIN_OUTPUT_NAME, entry.getKey())); } // Add REVISE_OUTPUT transformation for main output addTransformToComponents( componentsBuilder, TRANSFORM_ID_PREFIX + "revise", createRevisePayload(), COLLECTION_PREFIX + (userDefinedDataStreamFunctions.size() - 1), Collections.singletonMap(MAIN_OUTPUT_NAME, OUTPUT_COLLECTION_ID)); } private RunnerApi.ParDoPayload createRevisePayload() { final FlinkFnApi.UserDefinedDataStreamFunction proto = createReviseOutputDataStreamFunctionProto(); final RunnerApi.ParDoPayload.Builder payloadBuilder = RunnerApi.ParDoPayload.newBuilder() .setDoFn( RunnerApi.FunctionSpec.newBuilder() .setUrn(STATELESS_FUNCTION_URN) .setPayload( org.apache.beam.vendor.grpc.v1p60p1.com.google .protobuf.ByteString.copyFrom( proto.toByteArray())) .build()); return payloadBuilder.build(); } private RunnerApi.ParDoPayload createUdfPayload( FlinkFnApi.UserDefinedDataStreamFunction proto, String urn, boolean createTimer) { // Use ParDoPayload as a wrapper of the actual payload as timer is only supported in // ParDo final RunnerApi.ParDoPayload.Builder payloadBuilder = RunnerApi.ParDoPayload.newBuilder() .setDoFn( RunnerApi.FunctionSpec.newBuilder() .setUrn(urn) .setPayload( org.apache.beam.vendor.grpc.v1p60p1.com.google .protobuf.ByteString.copyFrom( proto.toByteArray())) .build()); // Timer is only available in the head operator if (createTimer && timerCoderDescriptor != null) { payloadBuilder.putTimerFamilySpecs( TIMER_ID, RunnerApi.TimerFamilySpec.newBuilder() // this field is not used, always set it as event time .setTimeDomain(RunnerApi.TimeDomain.Enum.EVENT_TIME) .setTimerFamilyCoderId(WRAPPER_TIMER_CODER_ID) .build()); } return payloadBuilder.build(); } private void addTransformToComponents( RunnerApi.Components.Builder componentsBuilder, String transformId, RunnerApi.ParDoPayload payload, String inputCollectionId, Map<String, String> outputCollectionMap) { final RunnerApi.PTransform.Builder transformBuilder = RunnerApi.PTransform.newBuilder() .setUniqueName(transformId) .setSpec( RunnerApi.FunctionSpec.newBuilder() .setUrn( BeamUrns.getUrn( RunnerApi.StandardPTransforms.Primitives .PAR_DO)) .setPayload(payload.toByteString()) .build()); transformBuilder.putInputs(MAIN_INPUT_NAME, inputCollectionId); transformBuilder.putAllOutputs(outputCollectionMap); componentsBuilder.putTransforms(transformId, transformBuilder.build()); } private void addCollectionToComponents( RunnerApi.Components.Builder componentsBuilder, String collectionId, String coderId) { componentsBuilder .putPcollections( collectionId, RunnerApi.PCollection.newBuilder() .setWindowingStrategyId(WINDOW_STRATEGY) .setCoderId(coderId) .build()) .putCoders(coderId, createCoderProto(inputCoderDescriptor)); } @Override protected List<TimerReference> getTimers(RunnerApi.Components components) { if (timerCoderDescriptor != null) { RunnerApi.ExecutableStagePayload.TimerId timerId = RunnerApi.ExecutableStagePayload.TimerId.newBuilder() .setTransformId(TRANSFORM_ID_PREFIX + 0) .setLocalName(TIMER_ID) .build(); return Collections.singletonList(TimerReference.fromTimerId(timerId, components)); } else { return Collections.emptyList(); } } @Override protected Optional<RunnerApi.Coder> getOptionalTimerCoderProto() { if (timerCoderDescriptor != null) { return Optional.of(ProtoUtils.createCoderProto(timerCoderDescriptor)); } else { return Optional.empty(); } } }
BeamDataStreamPythonFunctionRunner
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/SupervisingRouteControllerSplitOnExceptionTest.java
{ "start": 1221, "end": 3155 }
class ____ extends ContextTestSupport { @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); SupervisingRouteController src = context.getRouteController().supervising(); src.setBackOffDelay(25); src.setBackOffMaxAttempts(3); src.setInitialDelay(100); src.setThreadPoolSize(1); return context; } @Test public void testSupervising() throws Exception { getMockEndpoint("mock:error").expectedMessageCount(1); getMockEndpoint("mock:uk").expectedMessageCount(0); getMockEndpoint("mock:other").expectedMessageCount(0); template.sendBody("direct:start", "<hello>World"); assertMockEndpointsSatisfied(); } @Override protected RoutesBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { onException().handled(true).split().method(SupervisingRouteControllerSplitOnExceptionTest.class, "mySplit") .streaming().log("Exception occurred").to("mock:error"); from("direct:start") .choice() .when(xpath("/person/city = 'London'")) .log("UK message") .to("mock:uk") .otherwise() .log("Other message") .to("mock:other"); } }; } public static List<Message> mySplit(@Body Message inputMessage) { List<Message> outputMessages = new ArrayList<>(); Message outputMessage = inputMessage.copy(); outputMessage.setBody(inputMessage.getBody()); outputMessages.add(outputMessage); return outputMessages; } }
SupervisingRouteControllerSplitOnExceptionTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/HashMapStateBackendMigrationTest.java
{ "start": 1759, "end": 2859 }
class ____ extends StateBackendMigrationTestBase<HashMapStateBackend> { @TempDir private static Path tempFolder; @Parameters public static List<Object> modes() { return Arrays.asList( (SupplierWithException<CheckpointStorage, IOException>) JobManagerCheckpointStorage::new, (SupplierWithException<CheckpointStorage, IOException>) () -> { String checkpointPath = TempDirUtils.newFolder(tempFolder).toURI().toString(); return new FileSystemCheckpointStorage(checkpointPath); }); } @Parameter public SupplierWithException<CheckpointStorage, IOException> storageSupplier; @Override protected HashMapStateBackend getStateBackend() throws Exception { return new HashMapStateBackend(); } @Override protected CheckpointStorage getCheckpointStorage() throws Exception { return storageSupplier.get(); } }
HashMapStateBackendMigrationTest
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/recursive/AbstractRecursiveOperationConfiguration.java
{ "start": 1168, "end": 8932 }
class ____ { protected static final String DEFAULT_DELIMITER = ", "; private final Set<String> ignoredFields = new LinkedHashSet<>(); private final List<Pattern> ignoredFieldsRegexes = new ArrayList<>(); private final Set<Class<?>> ignoredTypes = new LinkedHashSet<>(); private final List<Pattern> ignoredTypesRegexes = new ArrayList<>(); protected AbstractRecursiveOperationConfiguration(AbstractBuilder<?> builder) { ignoreFields(builder.ignoredFields); ignoreFieldsMatchingRegexes(builder.ignoredFieldsMatchingRegexes); ignoreFieldsOfTypes(builder.ignoredTypes); } protected AbstractRecursiveOperationConfiguration() {} /** * Adds the given fields to the set of fields from the object under test to ignore in the recursive comparison. * <p> * The fields are ignored by name, not by value. * <p> * See {@link RecursiveComparisonAssert#ignoringFields(String...) RecursiveComparisonAssert#ignoringFields(String...)} for examples. * * @param fieldsToIgnore the fields of the object under test to ignore in the comparison. */ public void ignoreFields(String... fieldsToIgnore) { List<String> fieldLocations = list(fieldsToIgnore); ignoredFields.addAll(fieldLocations); } /** * Returns the set of fields from the object under test to ignore in the recursive comparison. * * @return the set of fields from the object under test to ignore in the recursive comparison. */ public Set<String> getIgnoredFields() { return ignoredFields; } /** * Allows to ignore in the recursive comparison the object under test fields matching the given regexes. The given regexes are added to the already registered ones. * <p> * See {@link RecursiveComparisonAssert#ignoringFieldsMatchingRegexes(String...) RecursiveComparisonAssert#ignoringFieldsMatchingRegexes(String...)} for examples. * * @param regexes regexes used to ignore fields in the comparison. */ public void ignoreFieldsMatchingRegexes(String... regexes) { List<Pattern> patterns = toPatterns(regexes); ignoredFieldsRegexes.addAll(patterns); } public List<Pattern> getIgnoredFieldsRegexes() { return ignoredFieldsRegexes; } /** * Makes the recursive assertion to ignore the object under test fields of the given types. * The fields are ignored if their types <b>exactly match one of the ignored types</b>, for example if a field is a subtype of an ignored type it is not ignored. * <p> * If some object under test fields are null it is not possible to evaluate their types and thus these fields are not ignored. * <p> * Example: see {@link RecursiveComparisonAssert#ignoringFieldsOfTypes(Class[])}. * * @param types the types of the object under test to ignore in the comparison. */ public void ignoreFieldsOfTypes(Class<?>... types) { stream(types).map(AbstractRecursiveOperationConfiguration::asWrapperIfPrimitiveType).forEach(ignoredTypes::add); } /** * Makes the recursive comparison to ignore the fields of the object under test having types matching one of the given regexes. * The fields are ignored if their types <b>exactly match one of the regexes</b>, if a field is a subtype of a matched type it is not ignored. * <p> * One use case of this method is to ignore types that can't be introspected. * <p> * If {@code strictTypeChecking} mode is enabled and a field of the object under test is null, the recursive * comparison evaluates the corresponding expected field's type (if not null), if it is disabled then the field is evaluated as * usual (i.e. it is not ignored). * <p> * <b>Warning</b>: primitive types are not directly supported because under the hood they are converted to their * corresponding wrapping types, for example {@code int} to {@code java.lang.Integer}. The preferred way to ignore * primitive types is to use {@link #ignoreFieldsOfTypes(Class[])}. * Another way is to ignore the wrapping type, for example ignoring {@code java.lang.Integer} ignores both * {@code java.lang.Integer} and {@code int} fields. * <p> * Example: see {@link RecursiveComparisonAssert#ignoringFieldsOfTypesMatchingRegexes(String...)}. * * @param regexes regexes specifying the types to ignore. */ public void ignoreFieldsOfTypesMatchingRegexes(String... regexes) { List<Pattern> patterns = toPatterns(regexes); ignoredTypesRegexes.addAll(patterns); } protected static Class<?> asWrapperIfPrimitiveType(Class<?> type) { if (!type.isPrimitive()) return type; if (type.equals(boolean.class)) return Boolean.class; if (type.equals(byte.class)) return Byte.class; if (type.equals(int.class)) return Integer.class; if (type.equals(short.class)) return Short.class; if (type.equals(char.class)) return Character.class; if (type.equals(float.class)) return Float.class; if (type.equals(double.class)) return Double.class; // should not arrive here since we have tested primitive types first return type; } /** * Returns the set of fields from the object under test types to ignore in the recursive comparison. * * @return the set of fields from the object under test types to ignore in the recursive comparison. */ public Set<Class<?>> getIgnoredTypes() { return ignoredTypes; } /** * Returns the regexes that will be used to ignore fields with types matching these regexes in the recursive comparison. * * @return the regexes that will be used to ignore fields with types matching these regexes in the recursive comparison. */ public List<Pattern> getIgnoredTypesRegexes() { return ignoredTypesRegexes; } protected void describeIgnoredFields(StringBuilder description) { if (!getIgnoredFields().isEmpty()) description.append("- the following fields were ignored in the comparison: %s%n".formatted(describeIgnoredFields())); } protected void describeIgnoredFieldsRegexes(StringBuilder description) { if (!getIgnoredFieldsRegexes().isEmpty()) description.append("- the fields matching the following regexes were ignored in the comparison: %s%n".formatted( describeRegexes(getIgnoredFieldsRegexes()))); } protected String describeIgnoredTypes() { List<String> typesDescription = getIgnoredTypes().stream() .map(Class::getName) .collect(toList()); return join(typesDescription); } protected String describeRegexes(List<Pattern> regexes) { List<String> fieldsDescription = regexes.stream() .map(Pattern::pattern) .collect(toList()); return join(fieldsDescription); } protected static String join(Collection<String> typesDescription) { return Strings.join(typesDescription).with(DEFAULT_DELIMITER); } public boolean matchesAnIgnoredFieldRegex(FieldLocation fieldLocation) { // checks parent fields as if a parent field is ignored all subfields (including this field location) should be too. return getIgnoredFieldsRegexes().stream().anyMatch(fieldLocation::hierarchyMatchesRegex); } public boolean matchesAnIgnoredField(FieldLocation fieldLocation) { // checks parent fields as if a parent field is ignored all subfields (including this field location) should be too. return getIgnoredFields().stream().anyMatch(fieldLocation::hierarchyMatches); } private String describeIgnoredFields() { return join(getIgnoredFields()); } protected static
AbstractRecursiveOperationConfiguration
java
alibaba__druid
core/src/main/java/com/alibaba/druid/pool/DruidConnectionHolder.java
{ "start": 1569, "end": 15609 }
class ____ { private static final Log LOG = LogFactory.getLog(DruidConnectionHolder.class); static volatile boolean ORACLE_SOCKET_FIELD_ERROR; static volatile Field ORACLE_FIELD_NET; static volatile Field ORACLE_FIELD_S_ATTS; static volatile Field ORACLE_FIELD_NT; static volatile Field ORACLE_FIELD_SOCKET; public static boolean holdabilityUnsupported; protected final DruidAbstractDataSource dataSource; protected final long connectionId; protected final Connection conn; protected final List<ConnectionEventListener> connectionEventListeners = new CopyOnWriteArrayList<ConnectionEventListener>(); protected final List<StatementEventListener> statementEventListeners = new CopyOnWriteArrayList<StatementEventListener>(); protected final long connectTimeMillis; protected volatile long lastActiveTimeMillis; protected volatile long lastExecTimeMillis; protected volatile long lastKeepTimeMillis; protected volatile long lastValidTimeMillis; protected long useCount; private long keepAliveCheckCount; private long lastNotEmptyWaitNanos; private final long createNanoSpan; protected PreparedStatementPool statementPool; protected final List<Statement> statementTrace = new ArrayList<Statement>(2); protected final boolean defaultReadOnly; protected final int defaultHoldability; protected final int defaultTransactionIsolation; protected final boolean defaultAutoCommit; protected boolean underlyingReadOnly; protected int underlyingHoldability; protected int underlyingTransactionIsolation; protected boolean underlyingAutoCommit; protected volatile boolean discard; protected volatile boolean active; protected final Map<String, Object> variables; protected final Map<String, Object> globalVariables; final ReentrantLock lock = new ReentrantLock(); protected String initSchema; protected Socket socket; protected final long userPasswordVersion; volatile FilterChainImpl filterChain; public DruidConnectionHolder(DruidAbstractDataSource dataSource, PhysicalConnectionInfo pyConnectInfo) throws SQLException { this( dataSource, pyConnectInfo.getPhysicalConnection(), pyConnectInfo.getConnectNanoSpan(), pyConnectInfo.getVairiables(), pyConnectInfo.getGlobalVairiables() ); } public DruidConnectionHolder(DruidAbstractDataSource dataSource, Connection conn, long connectNanoSpan) throws SQLException { this(dataSource, conn, connectNanoSpan, null, null); } public DruidConnectionHolder( DruidAbstractDataSource dataSource, Connection conn, long connectNanoSpan, Map<String, Object> variables, Map<String, Object> globalVariables ) throws SQLException { this.dataSource = dataSource; this.conn = conn; this.createNanoSpan = connectNanoSpan; this.variables = variables; this.globalVariables = globalVariables; this.userPasswordVersion = dataSource.getUserPasswordVersion(); this.connectTimeMillis = System.currentTimeMillis(); this.lastActiveTimeMillis = connectTimeMillis; this.lastExecTimeMillis = connectTimeMillis; this.underlyingAutoCommit = conn.getAutoCommit(); if (conn instanceof WrapperProxy) { this.connectionId = ((WrapperProxy) conn).getId(); } else { this.connectionId = dataSource.createConnectionId(); } Class<? extends Connection> conClass = conn.getClass(); String connClassName = conClass.getName(); if ((!ORACLE_SOCKET_FIELD_ERROR) && connClassName.equals("oracle.jdbc.driver.T4CConnection")) { try { if (ORACLE_FIELD_NET == null) { Field field = conClass.getDeclaredField("net"); field.setAccessible(true); ORACLE_FIELD_NET = field; } Object net = ORACLE_FIELD_NET.get(conn); if (ORACLE_FIELD_S_ATTS == null) { // NSProtocol Field field = net.getClass().getSuperclass().getDeclaredField("sAtts"); field.setAccessible(true); ORACLE_FIELD_S_ATTS = field; } Object sAtts = ORACLE_FIELD_S_ATTS.get(net); if (ORACLE_FIELD_NT == null) { Field field = sAtts.getClass().getDeclaredField("nt"); field.setAccessible(true); ORACLE_FIELD_NT = field; } Object nt = ORACLE_FIELD_NT.get(sAtts); if (ORACLE_FIELD_SOCKET == null) { Field field = nt.getClass().getDeclaredField("socket"); field.setAccessible(true); ORACLE_FIELD_SOCKET = field; } socket = (Socket) ORACLE_FIELD_SOCKET.get(nt); } catch (Throwable ignored) { ORACLE_SOCKET_FIELD_ERROR = true; // ignored } } { boolean initUnderlyHoldability = !holdabilityUnsupported; DbType dbType = DbType.of(dataSource.dbTypeName); if (dbType == DbType.sybase // || dbType == DbType.db2 // || dbType == DbType.hive // || dbType == DbType.odps // ) { initUnderlyHoldability = false; } if (initUnderlyHoldability) { try { this.underlyingHoldability = conn.getHoldability(); } catch (UnsupportedOperationException e) { holdabilityUnsupported = true; LOG.warn("getHoldability unsupported", e); } catch (SQLFeatureNotSupportedException e) { holdabilityUnsupported = true; LOG.warn("getHoldability unsupported", e); } catch (SQLException e) { // bug fixed for hive jdbc-driver if ("Method not supported".equals(e.getMessage())) { holdabilityUnsupported = true; } LOG.warn("getHoldability error", e); } } } this.underlyingReadOnly = conn.isReadOnly(); try { this.underlyingTransactionIsolation = conn.getTransactionIsolation(); } catch (SQLException e) { // compartible for alibaba corba if ("HY000".equals(e.getSQLState()) || "com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException".equals(e.getClass().getName())) { // skip } else { throw e; } } this.defaultHoldability = underlyingHoldability; this.defaultTransactionIsolation = underlyingTransactionIsolation; this.defaultAutoCommit = underlyingAutoCommit; this.defaultReadOnly = underlyingReadOnly; } protected FilterChainImpl createChain() { FilterChainImpl chain = this.filterChain; if (chain == null) { chain = new FilterChainImpl(dataSource); } else { this.filterChain = null; } return chain; } protected void recycleFilterChain(FilterChainImpl chain) { chain.reset(); this.filterChain = chain; } public long getConnectTimeMillis() { return connectTimeMillis; } public boolean isUnderlyingReadOnly() { return underlyingReadOnly; } public void setUnderlyingReadOnly(boolean underlyingReadOnly) { this.underlyingReadOnly = underlyingReadOnly; } public int getUnderlyingHoldability() { return underlyingHoldability; } public void setUnderlyingHoldability(int underlyingHoldability) { this.underlyingHoldability = underlyingHoldability; } public int getUnderlyingTransactionIsolation() { return underlyingTransactionIsolation; } public void setUnderlyingTransactionIsolation(int underlyingTransactionIsolation) { this.underlyingTransactionIsolation = underlyingTransactionIsolation; } public boolean isUnderlyingAutoCommit() { return underlyingAutoCommit; } public void setUnderlyingAutoCommit(boolean underlyingAutoCommit) { this.underlyingAutoCommit = underlyingAutoCommit; } public long getLastActiveTimeMillis() { return lastActiveTimeMillis; } public void setLastActiveTimeMillis(long lastActiveMillis) { this.lastActiveTimeMillis = lastActiveMillis; } public long getLastExecTimeMillis() { return lastExecTimeMillis; } public void setLastExecTimeMillis(long lastExecTimeMillis) { this.lastExecTimeMillis = lastExecTimeMillis; } public void addTrace(DruidPooledStatement stmt) { lock.lock(); try { statementTrace.add(stmt); } finally { lock.unlock(); } } public void removeTrace(DruidPooledStatement stmt) { lock.lock(); try { statementTrace.remove(stmt); } finally { lock.unlock(); } } public List<ConnectionEventListener> getConnectionEventListeners() { return connectionEventListeners; } public List<StatementEventListener> getStatementEventListeners() { return statementEventListeners; } public PreparedStatementPool getStatementPool() { if (statementPool == null) { statementPool = new PreparedStatementPool(this); } return statementPool; } public PreparedStatementPool getStatementPoolDirect() { return statementPool; } public void clearStatementCache() { if (this.statementPool == null) { return; } this.statementPool.clear(); } public DruidAbstractDataSource getDataSource() { return dataSource; } public boolean isPoolPreparedStatements() { return dataSource.isPoolPreparedStatements(); } public Connection getConnection() { return conn; } public long getTimeMillis() { return connectTimeMillis; } public long getUseCount() { return useCount; } public long getConnectionId() { return connectionId; } public void incrementUseCount() { useCount++; } public long getKeepAliveCheckCount() { return keepAliveCheckCount; } public void incrementKeepAliveCheckCount() { keepAliveCheckCount++; } public void reset() throws SQLException { // reset default settings if (underlyingReadOnly != defaultReadOnly) { conn.setReadOnly(defaultReadOnly); underlyingReadOnly = defaultReadOnly; } if (underlyingHoldability != defaultHoldability) { conn.setHoldability(defaultHoldability); underlyingHoldability = defaultHoldability; } if (!dataSource.isKeepConnectionUnderlyingTransactionIsolation() && underlyingTransactionIsolation != defaultTransactionIsolation) { conn.setTransactionIsolation(defaultTransactionIsolation); underlyingTransactionIsolation = defaultTransactionIsolation; } if (underlyingAutoCommit != defaultAutoCommit) { conn.setAutoCommit(defaultAutoCommit); underlyingAutoCommit = defaultAutoCommit; } if (!connectionEventListeners.isEmpty()) { connectionEventListeners.clear(); } if (!statementEventListeners.isEmpty()) { statementEventListeners.clear(); } lock.lock(); try { if (!statementTrace.isEmpty()) { Object[] items = statementTrace.toArray(); for (int i = 0; i < items.length; i++) { Object item = items[i]; Statement stmt = (Statement) item; JdbcUtils.close(stmt); } statementTrace.clear(); } } finally { lock.unlock(); } conn.clearWarnings(); } public boolean isDiscard() { return discard; } public void setDiscard(boolean discard) { this.discard = discard; } public long getCreateNanoSpan() { return createNanoSpan; } public long getLastNotEmptyWaitNanos() { return lastNotEmptyWaitNanos; } protected void setLastNotEmptyWaitNanos(long lastNotEmptyWaitNanos) { this.lastNotEmptyWaitNanos = lastNotEmptyWaitNanos; } public String toString() { StringBuilder buf = new StringBuilder(); buf.append("{ID:"); buf.append(System.identityHashCode(conn)); buf.append(", ConnectTime:\""); buf.append(Utils.toString(new Date(this.connectTimeMillis))); buf.append("\", UseCount:"); buf.append(useCount); if (lastActiveTimeMillis > 0) { buf.append(", LastActiveTime:\""); buf.append(Utils.toString(new Date(lastActiveTimeMillis))); buf.append("\""); } if (lastKeepTimeMillis > 0) { buf.append(", LastKeepTimeMillis:\""); buf.append(Utils.toString(new Date(lastKeepTimeMillis))); buf.append("\""); } if (statementPool != null && statementPool.getMap().size() > 0) { buf.append("\", CachedStatementCount:"); buf.append(statementPool.getMap().size()); } buf.append("}"); return buf.toString(); } public long getUserPasswordVersion() { return userPasswordVersion; } }
DruidConnectionHolder
java
google__guice
core/src/com/google/inject/internal/ConstructionProxy.java
{ "start": 1097, "end": 2042 }
interface ____<T> { /** Constructs an instance of {@code T} for the given arguments. */ T newInstance(Object... arguments) throws InvocationTargetException; /** * Returns the method handle for the constructor, using the supplied handles to provide * parameters. * * <p>The returned handle has {@link InternalMethodHandles#ELEMENT_FACTORY_TYPE} as its signature. */ MethodHandle getConstructHandle(MethodHandle[] parameterHandles); /** Returns the injection point for this constructor. */ InjectionPoint getInjectionPoint(); /** * Returns the injected constructor. If the injected constructor is synthetic (such as generated * code for method interception), the natural constructor is returned. */ Constructor<T> getConstructor(); /** Returns the interceptors applied to each method, in order of invocation. */ ImmutableMap<Method, List<MethodInterceptor>> getMethodInterceptors(); }
ConstructionProxy
java
reactor__reactor-core
reactor-core/src/test/java/reactor/core/publisher/ContextLossDetectionTest.java
{ "start": 6987, "end": 7486 }
class ____ implements BiFunction<CorePublisher<ContextView>, ContextView, Publisher<ContextView>> { final LossyTransformer delegate; protected LossyBiTransformer(LossyTransformer delegate) { this.delegate = delegate; } @Override public Publisher<ContextView> apply(CorePublisher<ContextView> publisher, ContextView contextView) { return delegate.apply(publisher); } @Override public String toString() { return delegate.toString(); } } static abstract
LossyBiTransformer
java
quarkusio__quarkus
extensions/smallrye-reactive-messaging/deployment/src/test/java/io/quarkus/smallrye/reactivemessaging/hotreload/SomeSource.java
{ "start": 271, "end": 651 }
class ____ { @Outgoing("my-source") public Multi<Integer> source() { return Multi.createFrom().items(0, 1, 2, 3, 4, 5, 6, 7, 8) .map(new Function<Integer, Integer>() { @Override public Integer apply(Integer l) { return l + 1; } }); } }
SomeSource
java
grpc__grpc-java
services/src/generated/main/grpc/io/grpc/reflection/v1/ServerReflectionGrpc.java
{ "start": 5742, "end": 6101 }
class ____ implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return ServerReflectionGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service ServerReflection. */ public static final
ServerReflectionImplBase
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/cluster/IndexRemovalReason.java
{ "start": 595, "end": 2282 }
enum ____ { /** * Shard of this index were previously assigned to this node but all shards have been relocated. * The index should be removed and all associated resources released. Persistent parts of the index * like the shards files, state and transaction logs are kept around in the case of a disaster recovery. */ NO_LONGER_ASSIGNED, /** * The index is deleted. Persistent parts of the index like the shards files, state and transaction logs are removed once * all resources are released. */ DELETED, /** * The index has been closed. The index should be removed and all associated resources released. Persistent parts of the index * like the shards files, state and transaction logs are kept around in the case of a disaster recovery. */ CLOSED, /** * Something around index management has failed and the index should be removed. * Persistent parts of the index like the shards files, state and transaction logs are kept around in the * case of a disaster recovery. */ FAILURE, /** * The index has been reopened. The index should be removed and all associated resources released. Persistent parts of the index * like the shards files, state and transaction logs are kept around in the case of a disaster recovery. */ REOPENED, /** * The index is closed as part of the node shutdown process. The index should be removed and all associated resources released. * Persistent parts of the index like the shards files, state and transaction logs should be kept around in the case the node * restarts. */ SHUTDOWN, }
IndexRemovalReason
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/codec/PerFieldFormatSupplier.java
{ "start": 1911, "end": 8336 }
class ____ { private static final Set<String> INCLUDE_META_FIELDS; private static final Set<String> EXCLUDE_MAPPER_TYPES; static { // TODO: should we just allow all fields to use tsdb doc values codec? // Avoid using tsdb codec for fields like _seq_no, _primary_term. // But _tsid and _ts_routing_hash should always use the tsdb codec. Set<String> includeMetaField = new HashSet<>(3); includeMetaField.add(TimeSeriesIdFieldMapper.NAME); includeMetaField.add(TimeSeriesRoutingHashFieldMapper.NAME); includeMetaField.add(SeqNoFieldMapper.NAME); // Don't the include _recovery_source_size and _recovery_source fields, since their values can be trimmed away in // RecoverySourcePruneMergePolicy, which leads to inconsistencies between merge stats and actual values. INCLUDE_META_FIELDS = Collections.unmodifiableSet(includeMetaField); EXCLUDE_MAPPER_TYPES = Set.of("geo_shape"); } private static final DocValuesFormat docValuesFormat = new Lucene90DocValuesFormat(); private static final KnnVectorsFormat knnVectorsFormat = new Lucene99HnswVectorsFormat(); private static final ES819TSDBDocValuesFormat tsdbDocValuesFormat = new ES819TSDBDocValuesFormat(); private static final ES812PostingsFormat es812PostingsFormat = new ES812PostingsFormat(); private static final PostingsFormat completionPostingsFormat = PostingsFormat.forName("Completion101"); private final ES87BloomFilterPostingsFormat bloomFilterPostingsFormat; private final MapperService mapperService; private final PostingsFormat defaultPostingsFormat; public PerFieldFormatSupplier(MapperService mapperService, BigArrays bigArrays) { this.mapperService = mapperService; this.bloomFilterPostingsFormat = new ES87BloomFilterPostingsFormat(bigArrays, this::internalGetPostingsFormatForField); this.defaultPostingsFormat = getDefaultPostingsFormat(mapperService); } private static PostingsFormat getDefaultPostingsFormat(final MapperService mapperService) { // we migrated to using a new postings format for the standard indices with Lucene 10.3 if (mapperService != null && mapperService.getIndexSettings().getIndexVersionCreated().onOrAfter(IndexVersions.UPGRADE_TO_LUCENE_10_3_0)) { if (IndexSettings.USE_ES_812_POSTINGS_FORMAT.get(mapperService.getIndexSettings().getSettings())) { return es812PostingsFormat; } else { return Elasticsearch92Lucene103Codec.DEFAULT_POSTINGS_FORMAT; } } else { // our own posting format using PFOR, used for logsdb and tsdb indices by default return es812PostingsFormat; } } public PostingsFormat getPostingsFormatForField(String field) { if (useBloomFilter(field)) { return bloomFilterPostingsFormat; } return internalGetPostingsFormatForField(field); } private PostingsFormat internalGetPostingsFormatForField(String field) { if (mapperService != null) { Mapper mapper = mapperService.mappingLookup().getMapper(field); if (mapper instanceof CompletionFieldMapper) { return completionPostingsFormat; } } return defaultPostingsFormat; } boolean useBloomFilter(String field) { if (mapperService == null) { return false; } IndexSettings indexSettings = mapperService.getIndexSettings(); if (mapperService.mappingLookup().isDataStreamTimestampFieldEnabled()) { // In case for time series indices, the _id isn't randomly generated, // but based on dimension fields and timestamp field, so during indexing // version/seq_no/term needs to be looked up and having a bloom filter // can speed this up significantly. return indexSettings.getMode() == IndexMode.TIME_SERIES && IdFieldMapper.NAME.equals(field) && IndexSettings.BLOOM_FILTER_ID_FIELD_ENABLED_SETTING.get(indexSettings.getSettings()); } else { return IdFieldMapper.NAME.equals(field) && IndexSettings.BLOOM_FILTER_ID_FIELD_ENABLED_SETTING.get(indexSettings.getSettings()); } } public KnnVectorsFormat getKnnVectorsFormatForField(String field) { if (mapperService != null) { Mapper mapper = mapperService.mappingLookup().getMapper(field); if (mapper instanceof DenseVectorFieldMapper vectorMapper) { return vectorMapper.getKnnVectorsFormatForField(knnVectorsFormat, mapperService.getIndexSettings()); } } return knnVectorsFormat; } public DocValuesFormat getDocValuesFormatForField(String field) { if (useTSDBDocValuesFormat(field)) { return tsdbDocValuesFormat; } return docValuesFormat; } boolean useTSDBDocValuesFormat(final String field) { if (excludeFields(field)) { return false; } if (excludeMapperTypes(field)) { return false; } return mapperService != null && mapperService.getIndexSettings().useTimeSeriesDocValuesFormat() && mapperService.getIndexSettings().isES87TSDBCodecEnabled(); } private boolean excludeFields(String fieldName) { return fieldName.startsWith("_") && INCLUDE_META_FIELDS.contains(fieldName) == false; } private boolean excludeMapperTypes(String fieldName) { var typeName = getMapperType(fieldName); if (typeName == null) { return false; } return EXCLUDE_MAPPER_TYPES.contains(getMapperType(fieldName)); } private boolean isTimeSeriesModeIndex() { return mapperService != null && IndexMode.TIME_SERIES == mapperService.getIndexSettings().getMode(); } private boolean isLogsModeIndex() { return mapperService != null && IndexMode.LOGSDB == mapperService.getIndexSettings().getMode(); } String getMapperType(final String field) { if (mapperService != null) { Mapper mapper = mapperService.mappingLookup().getMapper(field); if (mapper != null) { return mapper.typeName(); } } return null; } }
PerFieldFormatSupplier
java
apache__spark
common/sketch/src/main/java/org/apache/spark/util/sketch/CountMinSketch.java
{ "start": 2167, "end": 2210 }
class ____ stream-lib. */ public abstract
from
java
alibaba__druid
core/src/main/java/com/alibaba/druid/stat/JdbcDataSourceStat.java
{ "start": 1426, "end": 15604 }
class ____ implements JdbcDataSourceStatMBean { private static final Log LOG = LogFactory.getLog(JdbcDataSourceStat.class); private final String name; private final String url; private String dbType; private final JdbcConnectionStat connectionStat = new JdbcConnectionStat(); private final JdbcResultSetStat resultSetStat = new JdbcResultSetStat(); private final JdbcStatementStat statementStat = new JdbcStatementStat(); private int maxSqlSize = 1000; private ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); private final LinkedHashMap<String, JdbcSqlStat> sqlStatMap; private final AtomicLong skipSqlCount = new AtomicLong(); private final Histogram connectionHoldHistogram = new Histogram(new long[]{ // // 1, 10, 100, 1000, 10 * 1000, // 100 * 1000, 1000 * 1000 // }); private final ConcurrentMap<Long, JdbcConnectionStat.Entry> connections = new ConcurrentHashMap<Long, JdbcConnectionStat.Entry>( 16, 0.75f, 1); private final AtomicLong clobOpenCount = new AtomicLong(); private final AtomicLong blobOpenCount = new AtomicLong(); private final AtomicLong keepAliveCheckCount = new AtomicLong(); private boolean resetStatEnable = true; private static JdbcDataSourceStat global; static { String dbType = null; { String property = System.getProperty("druid.globalDbType"); if (property != null && property.length() > 0) { dbType = property; } } global = new JdbcDataSourceStat("Global", "Global", dbType); } public static JdbcDataSourceStat getGlobal() { return global; } public static void setGlobal(JdbcDataSourceStat value) { global = value; } public void configFromProperties(Properties properties) { } public boolean isResetStatEnable() { return resetStatEnable; } public void setResetStatEnable(boolean resetStatEnable) { this.resetStatEnable = resetStatEnable; } public JdbcDataSourceStat(String name, String url) { this(name, url, null); } public JdbcDataSourceStat(String name, String url, String dbType) { this(name, url, dbType, null); } @SuppressWarnings("serial") public JdbcDataSourceStat(String name, String url, String dbType, Properties connectProperties) { this.name = name; this.url = url; this.dbType = dbType; if (connectProperties != null) { Object arg = connectProperties.get(Constants.DRUID_STAT_SQL_MAX_SIZE); if (arg == null) { arg = System.getProperty(Constants.DRUID_STAT_SQL_MAX_SIZE); } if (arg != null) { try { maxSqlSize = Integer.parseInt(arg.toString()); } catch (NumberFormatException ex) { LOG.error("maxSize parse error", ex); } } } sqlStatMap = new LinkedHashMap<String, JdbcSqlStat>(16, 0.75f, false) { protected boolean removeEldestEntry(Map.Entry<String, JdbcSqlStat> eldest) { boolean remove = (size() > maxSqlSize); if (remove) { JdbcSqlStat sqlStat = eldest.getValue(); if (sqlStat.getRunningCount() > 0 || sqlStat.getExecuteCount() > 0) { skipSqlCount.incrementAndGet(); } } return remove; } }; } public int getMaxSqlSize() { return this.maxSqlSize; } public void setMaxSqlSize(int value) { if (value == this.maxSqlSize) { return; } lock.writeLock().lock(); try { if (value < this.maxSqlSize) { int removeCount = this.maxSqlSize - value; Iterator<Map.Entry<String, JdbcSqlStat>> iter = sqlStatMap.entrySet().iterator(); while (iter.hasNext()) { iter.next(); if (removeCount > 0) { iter.remove(); removeCount--; } else { break; } } } this.maxSqlSize = value; } finally { lock.writeLock().unlock(); } } public String getDbType() { return dbType; } public void setDbType(String dbType) { this.dbType = dbType; } public long getSkipSqlCount() { return skipSqlCount.get(); } public long getSkipSqlCountAndReset() { return skipSqlCount.getAndSet(0); } public void reset() { if (!isResetStatEnable()) { return; } blobOpenCount.set(0); clobOpenCount.set(0); connectionStat.reset(); statementStat.reset(); resultSetStat.reset(); connectionHoldHistogram.reset(); skipSqlCount.set(0); lock.writeLock().lock(); try { Iterator<Map.Entry<String, JdbcSqlStat>> iter = sqlStatMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, JdbcSqlStat> entry = iter.next(); JdbcSqlStat stat = entry.getValue(); if (stat.getExecuteCount() == 0 && stat.getRunningCount() == 0) { stat.setRemoved(true); iter.remove(); } else { stat.reset(); } } } finally { lock.writeLock().unlock(); } for (JdbcConnectionStat.Entry connectionStat : connections.values()) { connectionStat.reset(); } } public Histogram getConnectionHoldHistogram() { return connectionHoldHistogram; } public JdbcConnectionStat getConnectionStat() { return connectionStat; } public JdbcResultSetStat getResultSetStat() { return resultSetStat; } public JdbcStatementStat getStatementStat() { return statementStat; } @Override public String getConnectionUrl() { return url; } @Override public TabularData getSqlList() throws JMException { Map<String, JdbcSqlStat> sqlStatMap = this.getSqlStatMap(); CompositeType rowType = JdbcSqlStat.getCompositeType(); String[] indexNames = rowType.keySet().toArray(new String[rowType.keySet().size()]); TabularType tabularType = new TabularType("SqlListStatistic", "SqlListStatistic", rowType, indexNames); TabularData data = new TabularDataSupport(tabularType); for (Map.Entry<String, JdbcSqlStat> entry : sqlStatMap.entrySet()) { data.put(entry.getValue().getCompositeData()); } return data; } public static StatFilter getStatFilter(DataSourceProxy dataSource) { for (Filter filter : dataSource.getProxyFilters()) { if (filter instanceof StatFilter) { return (StatFilter) filter; } } return null; } public JdbcSqlStat getSqlStat(int id) { return getSqlStat((long) id); } public JdbcSqlStat getSqlStat(long id) { lock.readLock().lock(); try { for (Map.Entry<String, JdbcSqlStat> entry : this.sqlStatMap.entrySet()) { if (entry.getValue().getId() == id) { return entry.getValue(); } } return null; } finally { lock.readLock().unlock(); } } public final ConcurrentMap<Long, JdbcConnectionStat.Entry> getConnections() { return connections; } @Override public TabularData getConnectionList() throws JMException { CompositeType rowType = JdbcConnectionStat.Entry.getCompositeType(); String[] indexNames = rowType.keySet().toArray(new String[rowType.keySet().size()]); TabularType tabularType = new TabularType("ConnectionListStatistic", "ConnectionListStatistic", rowType, indexNames); TabularData data = new TabularDataSupport(tabularType); for (Map.Entry<Long, JdbcConnectionStat.Entry> entry : getConnections().entrySet()) { data.put(entry.getValue().getCompositeData()); } return data; } public String getName() { return name; } public String getUrl() { return url; } public Map<String, JdbcSqlStat> getSqlStatMap() { Map<String, JdbcSqlStat> map = new LinkedHashMap<String, JdbcSqlStat>(sqlStatMap.size()); lock.readLock().lock(); try { map.putAll(sqlStatMap); } finally { lock.readLock().unlock(); } return map; } public List<JdbcSqlStatValue> getSqlStatMapAndReset() { List<JdbcSqlStat> stats = new ArrayList<JdbcSqlStat>(sqlStatMap.size()); lock.writeLock().lock(); try { Iterator<Map.Entry<String, JdbcSqlStat>> iter = sqlStatMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, JdbcSqlStat> entry = iter.next(); JdbcSqlStat stat = entry.getValue(); if (stat.getExecuteCount() == 0 && stat.getRunningCount() == 0) { stat.setRemoved(true); iter.remove(); } else { stats.add(entry.getValue()); } } } finally { lock.writeLock().unlock(); } List<JdbcSqlStatValue> values = new ArrayList<JdbcSqlStatValue>(stats.size()); for (JdbcSqlStat stat : stats) { JdbcSqlStatValue value = stat.getValueAndReset(); if (value.getExecuteCount() == 0 && value.getRunningCount() == 0) { continue; } values.add(value); } return values; } public List<JdbcSqlStatValue> getRuningSqlList() { List<JdbcSqlStat> stats = new ArrayList<JdbcSqlStat>(sqlStatMap.size()); lock.readLock().lock(); try { for (Map.Entry<String, JdbcSqlStat> entry : sqlStatMap.entrySet()) { JdbcSqlStat stat = entry.getValue(); if (stat.getRunningCount() >= 0) { stats.add(entry.getValue()); } } } finally { lock.readLock().unlock(); } List<JdbcSqlStatValue> values = new ArrayList<JdbcSqlStatValue>(stats.size()); for (JdbcSqlStat stat : stats) { JdbcSqlStatValue value = stat.getValue(false); if (value.getRunningCount() > 0) { values.add(value); } } return values; } public JdbcSqlStat getSqlStat(String sql) { lock.readLock().lock(); try { return sqlStatMap.get(sql); } finally { lock.readLock().unlock(); } } public JdbcSqlStat createSqlStat(String sql) { lock.writeLock().lock(); try { JdbcSqlStat sqlStat = sqlStatMap.get(sql); if (sqlStat == null) { sqlStat = new JdbcSqlStat(sql); sqlStat.setDbType(this.dbType); sqlStat.setName(this.name); sqlStatMap.put(sql, sqlStat); } return sqlStat; } finally { lock.writeLock().unlock(); } } @Override public long getConnectionActiveCount() { return this.connections.size(); } @Override public long getConnectionConnectAliveMillis() { long nowNano = System.nanoTime(); long aliveNanoSpan = this.getConnectionStat().getAliveTotal(); for (JdbcConnectionStat.Entry connection : connections.values()) { aliveNanoSpan += nowNano - connection.getEstablishNano(); } return aliveNanoSpan / (1000 * 1000); } public long getConnectionConnectAliveMillisMax() { long max = this.getConnectionStat().getAliveNanoMax(); long nowNano = System.nanoTime(); for (JdbcConnectionStat.Entry connection : connections.values()) { long connectionAliveNano = nowNano - connection.getEstablishNano(); if (connectionAliveNano > max) { max = connectionAliveNano; } } return max / (1000 * 1000); } public long getConnectionConnectAliveMillisMin() { long min = this.getConnectionStat().getAliveNanoMin(); long nowNano = System.nanoTime(); for (JdbcConnectionStat.Entry connection : connections.values()) { long connectionAliveNano = nowNano - connection.getEstablishNano(); if (connectionAliveNano < min || min == 0) { min = connectionAliveNano; } } return min / (1000 * 1000); } public long[] getConnectionHistogramRanges() { return connectionStat.getHistogramRanges(); } public long[] getConnectionHistogramValues() { return connectionStat.getHistorgramValues(); } public long getClobOpenCount() { return clobOpenCount.get(); } public long getClobOpenCountAndReset() { return clobOpenCount.getAndSet(0); } public void incrementClobOpenCount() { clobOpenCount.incrementAndGet(); } public long getBlobOpenCount() { return blobOpenCount.get(); } public long getBlobOpenCountAndReset() { return blobOpenCount.getAndSet(0); } public void incrementBlobOpenCount() { blobOpenCount.incrementAndGet(); } public long getKeepAliveCheckCount() { return keepAliveCheckCount.get(); } public long getKeepAliveCheckCountAndReset() { return keepAliveCheckCount.getAndSet(0); } public void addKeepAliveCheckCount(long delta) { keepAliveCheckCount.addAndGet(delta); } }
JdbcDataSourceStat
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/api/extension/ExecutableInvokerIntegrationTests.java
{ "start": 2749, "end": 3109 }
class ____ implements BeforeAllCallback { @Override public void beforeAll(ExtensionContext context) throws Exception { Constructor<?> constructor = context.getRequiredTestClass() // .getDeclaredConstructor(TestInfo.class, ExtensionContext.class); context.getExecutableInvoker().invoke(constructor); } } static
ExecuteConstructorTwiceExtension
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/engine/RefreshFailedEngineException.java
{ "start": 648, "end": 938 }
class ____ extends EngineException { public RefreshFailedEngineException(ShardId shardId, Throwable t) { super(shardId, "Refresh failed", t); } public RefreshFailedEngineException(StreamInput in) throws IOException { super(in); } }
RefreshFailedEngineException
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TempDirectoryTests.java
{ "start": 45063, "end": 45752 }
class ____ { static final Path UNDELETABLE_PATH = Path.of("undeletable"); static final String TEMP_DIR = "TEMP_DIR"; @RegisterExtension BeforeEachCallback injector = context -> context // .getStore(TempDirectory.NAMESPACE) // .put(TempDirectory.FILE_OPERATIONS_KEY, (FileOperations) path -> { if (path.endsWith(UNDELETABLE_PATH)) { throw new IOException("Simulated failure"); } else { Files.delete(path); } }); @TempDir Path tempDir; @BeforeEach void reportTempDir(TestReporter reporter) { reporter.publishEntry(TEMP_DIR, tempDir.toString()); } } @SuppressWarnings("JUnitMalformedDeclaration") static
UndeletableTestCase
java
apache__maven
its/core-it-suite/src/test/resources/mng-8293-bom-import-from-reactor/module/src/main/java/org/mvndaemon/mvnd/test/upgrades/bom/module/UseHello.java
{ "start": 869, "end": 956 }
class ____ { public void use() { System.out.println("Hello"); } }
UseHello
java
apache__kafka
coordinator-common/src/main/java/org/apache/kafka/coordinator/common/runtime/Deserializer.java
{ "start": 1129, "end": 1521 }
class ____ extends RuntimeException { private final short unknownType; public UnknownRecordTypeException(short unknownType) { super(String.format("Found an unknown record type %d", unknownType)); this.unknownType = unknownType; } public short unknownType() { return unknownType; } }
UnknownRecordTypeException
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/remote/AbstractPushCallBack.java
{ "start": 820, "end": 1077 }
class ____ implements PushCallBack { private long timeout; public AbstractPushCallBack(long timeout) { this.timeout = timeout; } @Override public long getTimeout() { return timeout; } }
AbstractPushCallBack
java
apache__camel
components/camel-mail/src/test/java/org/apache/camel/component/mail/Mailbox.java
{ "start": 1625, "end": 2014 }
class ____ to {@code org.jvnet.mock_javamail.Mailbox} to make the migration * from mock_javamail to GreenMail easier. * <p> * Note that {@link Mailbox} stores a static copy of the underlying GreenMail folder which was up to date only at the * time when the given {@link Mailbox} was created. This is by design to avoid needing to synchronize in the caller * code. */ public final
similar
java
dropwizard__dropwizard
dropwizard-validation/src/test/java/io/dropwizard/validation/SelfValidationTest.java
{ "start": 3192, "end": 3456 }
class ____ extends FailingExample { @SuppressWarnings("unused") @SelfValidation public void subValidateFail(ViolationCollector col) { col.addViolation(FAILED + "subclass"); } } public static
AnnotatedSubclassExample
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/HeuristicCompletionException.java
{ "start": 914, "end": 2337 }
class ____ extends TransactionException { /** * Unknown outcome state. */ public static final int STATE_UNKNOWN = 0; /** * Committed outcome state. */ public static final int STATE_COMMITTED = 1; /** * Rolledback outcome state. */ public static final int STATE_ROLLED_BACK = 2; /** * Mixed outcome state. */ public static final int STATE_MIXED = 3; public static String getStateString(int state) { return switch (state) { case STATE_COMMITTED -> "committed"; case STATE_ROLLED_BACK -> "rolled back"; case STATE_MIXED -> "mixed"; default -> "unknown"; }; } /** * The outcome state of the transaction: have some or all resources been committed? */ private final int outcomeState; /** * Constructor for HeuristicCompletionException. * @param outcomeState the outcome state of the transaction * @param cause the root cause from the transaction API in use */ public HeuristicCompletionException(int outcomeState, Throwable cause) { super("Heuristic completion: outcome state is " + getStateString(outcomeState), cause); this.outcomeState = outcomeState; } /** * Return the outcome state of the transaction state, * as one of the constants in this class. * @see #STATE_UNKNOWN * @see #STATE_COMMITTED * @see #STATE_ROLLED_BACK * @see #STATE_MIXED */ public int getOutcomeState() { return this.outcomeState; } }
HeuristicCompletionException
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/metamodel/MixedIdAndIdClassHandling.java
{ "start": 1063, "end": 2345 }
class ____ { @Test @JiraKey( "HHH-8533" ) public void testAccess(EntityManagerFactoryScope scope) { EntityType<FullTimeEmployee> entityType = scope.getEntityManagerFactory().getMetamodel().entity( FullTimeEmployee.class ); try { entityType.getId( String.class ); fail( "getId on entity defining @IdClass should cause IAE" ); } catch (IllegalArgumentException expected) { } assertNotNull( entityType.getSupertype().getIdClassAttributes() ); assertEquals( 1, entityType.getSupertype().getIdClassAttributes().size() ); assertFalse( entityType.hasSingleIdAttribute() ); } @Test @JiraKey( "HHH-6951" ) public void testGetIdType(EntityManagerFactoryScope scope) { EntityType<FullTimeEmployee> fullTimeEmployeeEntityType = scope.getEntityManagerFactory().getMetamodel().entity( FullTimeEmployee.class ); assertEquals( String.class, fullTimeEmployeeEntityType.getIdType().getJavaType() ); // return single @Id instead of @IdClass EntityType<Person> personEntityType = scope.getEntityManagerFactory().getMetamodel().entity( Person.class ); assertEquals( PersonId.class, personEntityType.getIdType().getJavaType() ); // return @IdClass instead of null } @MappedSuperclass @IdClass( EmployeeId.class ) public static abstract
MixedIdAndIdClassHandling
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/distributed/EagerAssignor.java
{ "start": 1938, "end": 9469 }
class ____ implements ConnectAssignor { private final Logger log; public EagerAssignor(LogContext logContext) { this.log = logContext.logger(EagerAssignor.class); } @Override public Map<String, ByteBuffer> performAssignment(String leaderId, ConnectProtocolCompatibility protocol, List<JoinGroupResponseMember> allMemberMetadata, WorkerCoordinator coordinator) { log.debug("Performing task assignment"); Map<String, ExtendedWorkerState> memberConfigs = new HashMap<>(); for (JoinGroupResponseMember member : allMemberMetadata) memberConfigs.put(member.memberId(), IncrementalCooperativeConnectProtocol.deserializeMetadata(ByteBuffer.wrap(member.metadata()))); long maxOffset = findMaxMemberConfigOffset(memberConfigs, coordinator); Long leaderOffset = ensureLeaderConfig(maxOffset, coordinator); if (leaderOffset == null) return fillAssignmentsAndSerialize(memberConfigs.keySet(), Assignment.CONFIG_MISMATCH, leaderId, memberConfigs.get(leaderId).url(), maxOffset, new HashMap<>(), new HashMap<>()); return performTaskAssignment(leaderId, leaderOffset, memberConfigs, coordinator); } private Long ensureLeaderConfig(long maxOffset, WorkerCoordinator coordinator) { // If this leader is behind some other members, we can't do assignment if (coordinator.configSnapshot().offset() < maxOffset) { // We might be able to take a new snapshot to catch up immediately and avoid another round of syncing here. // Alternatively, if this node has already passed the maximum reported by any other member of the group, it // is also safe to use this newer state. ClusterConfigState updatedSnapshot = coordinator.configFreshSnapshot(); if (updatedSnapshot.offset() < maxOffset) { log.info("Was selected to perform assignments, but do not have latest config found in sync request. " + "Returning an empty configuration to trigger re-sync."); return null; } else { coordinator.configSnapshot(updatedSnapshot); return updatedSnapshot.offset(); } } return maxOffset; } private Map<String, ByteBuffer> performTaskAssignment(String leaderId, long maxOffset, Map<String, ExtendedWorkerState> memberConfigs, WorkerCoordinator coordinator) { Map<String, Collection<String>> connectorAssignments = new HashMap<>(); Map<String, Collection<ConnectorTaskId>> taskAssignments = new HashMap<>(); // Perform round-robin task assignment. Assign all connectors and then all tasks because assigning both the // connector and its tasks can lead to very uneven distribution of work in some common cases (e.g. for connectors // that generate only 1 task each; in a cluster of 2 or an even # of nodes, only even nodes will be assigned // connectors and only odd nodes will be assigned tasks, but tasks are, on average, actually more resource // intensive than connectors). List<String> connectorsSorted = sorted(coordinator.configSnapshot().connectors()); CircularIterator<String> memberIt = new CircularIterator<>(sorted(memberConfigs.keySet())); for (String connectorId : connectorsSorted) { String connectorAssignedTo = memberIt.next(); log.trace("Assigning connector {} to {}", connectorId, connectorAssignedTo); Collection<String> memberConnectors = connectorAssignments.computeIfAbsent(connectorAssignedTo, k -> new ArrayList<>()); memberConnectors.add(connectorId); } for (String connectorId : connectorsSorted) { for (ConnectorTaskId taskId : sorted(coordinator.configSnapshot().tasks(connectorId))) { String taskAssignedTo = memberIt.next(); log.trace("Assigning task {} to {}", taskId, taskAssignedTo); Collection<ConnectorTaskId> memberTasks = taskAssignments.computeIfAbsent(taskAssignedTo, k -> new ArrayList<>()); memberTasks.add(taskId); } } coordinator.leaderState(new LeaderState(memberConfigs, connectorAssignments, taskAssignments)); return fillAssignmentsAndSerialize(memberConfigs.keySet(), Assignment.NO_ERROR, leaderId, memberConfigs.get(leaderId).url(), maxOffset, connectorAssignments, taskAssignments); } private Map<String, ByteBuffer> fillAssignmentsAndSerialize(Collection<String> members, short error, String leaderId, String leaderUrl, long maxOffset, Map<String, Collection<String>> connectorAssignments, Map<String, Collection<ConnectorTaskId>> taskAssignments) { Map<String, ByteBuffer> groupAssignment = new HashMap<>(); for (String member : members) { Collection<String> connectors = connectorAssignments.getOrDefault(member, List.of()); if (connectors == null) { connectors = List.of(); } Collection<ConnectorTaskId> tasks = taskAssignments.getOrDefault(member, List.of()); if (tasks == null) { tasks = List.of(); } Assignment assignment = new Assignment(error, leaderId, leaderUrl, maxOffset, connectors, tasks); log.debug("Assignment: {} -> {}", member, assignment); groupAssignment.put(member, ConnectProtocol.serializeAssignment(assignment)); } log.debug("Finished assignment"); return groupAssignment; } private long findMaxMemberConfigOffset(Map<String, ExtendedWorkerState> memberConfigs, WorkerCoordinator coordinator) { // The new config offset is the maximum seen by any member. We always perform assignment using this offset, // even if some members have fallen behind. The config offset used to generate the assignment is included in // the response so members that have fallen behind will not use the assignment until they have caught up. Long maxOffset = null; for (Map.Entry<String, ExtendedWorkerState> stateEntry : memberConfigs.entrySet()) { long memberRootOffset = stateEntry.getValue().offset(); if (maxOffset == null) maxOffset = memberRootOffset; else maxOffset = Math.max(maxOffset, memberRootOffset); } log.debug("Max config offset root: {}, local snapshot config offsets root: {}", maxOffset, coordinator.configSnapshot().offset()); return maxOffset; } private static <T extends Comparable<T>> List<T> sorted(Collection<T> members) { List<T> res = new ArrayList<>(members); Collections.sort(res); return res; } }
EagerAssignor
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/io/network/netty/PartitionRequestQueueTest.java
{ "start": 11011, "end": 11647 }
class ____ extends DefaultBufferResultSubpartitionView { private ReadOnlyBufferResultSubpartitionView(int buffersInBacklog) { super(buffersInBacklog); } @Nullable @Override public BufferAndBacklog getNextBuffer() { BufferAndBacklog nextBuffer = super.getNextBuffer(); return new BufferAndBacklog( nextBuffer.buffer().readOnlySlice(), nextBuffer.buffersInBacklog(), nextBuffer.getNextDataType(), 0); } } private static
ReadOnlyBufferResultSubpartitionView
java
apache__camel
components/camel-http/src/test/java/org/apache/camel/component/http/HttpConcurrentTest.java
{ "start": 1440, "end": 3841 }
class ____ extends BaseHttpTest { private final AtomicInteger counter = new AtomicInteger(); private HttpServer localServer; @Override public void setupResources() throws Exception { localServer = ServerBootstrap.bootstrap() .setCanonicalHostName("localhost").setHttpProcessor(getBasicHttpProcessor()) .setConnectionReuseStrategy(getConnectionReuseStrategy()).setResponseFactory(getHttpResponseFactory()) .setSslContext(getSSLContext()) .register("/", (request, response, context) -> { try { Thread.sleep(1000); } catch (InterruptedException e) { // ignore } response.setCode(HttpStatus.SC_OK); response.setEntity(new StringEntity(Integer.toString(counter.incrementAndGet()))); }).create(); localServer.start(); } @Override public void cleanupResources() throws Exception { if (localServer != null) { localServer.stop(); } } @Test public void testNoConcurrentProducers() throws Exception { doSendMessages(1, 1); } @Test public void testConcurrentProducers() throws Exception { doSendMessages(10, 5); } private void doSendMessages(int files, int poolSize) throws Exception { ExecutorService executor = Executors.newFixedThreadPool(poolSize); // we access the responses Map below only inside the main thread, // so no need for a thread-safe Map implementation Map<Integer, Future<String>> responses = new HashMap<>(); for (int i = 0; i < files; i++) { Future<String> out = executor.submit(() -> template.requestBody( "http://localhost:" + localServer.getLocalPort(), null, String.class)); responses.put(i, out); } assertEquals(files, responses.size()); // get all responses Set<String> unique = new HashSet<>(); for (Future<String> future : responses.values()) { unique.add(future.get()); } // should be 'files' unique responses assertEquals(files, unique.size(), "Should be " + files + " unique responses"); executor.shutdownNow(); } }
HttpConcurrentTest
java
quarkusio__quarkus
integration-tests/kubernetes-client/src/test/java/io/quarkus/it/kubernetes/client/NamespacedConfigMapPropertiesTest.java
{ "start": 505, "end": 1482 }
class ____ { @Test public void testPropertiesReadFromConfigMap() { ConfigMapPropertiesTest.assertProperty("dummy", "dummyFromDemo"); ConfigMapPropertiesTest.assertProperty("someProp1", "val1FromDemo"); ConfigMapPropertiesTest.assertProperty("someProp2", "val2FromDemo"); ConfigMapPropertiesTest.assertProperty("someProp3", "val3FromDemo"); ConfigMapPropertiesTest.assertProperty("someProp4", "val4FromDemo"); ConfigMapPropertiesTest.assertProperty("someProp5", "val5FromDemo"); SecretPropertiesTest.assertProperty("dummysecret", "dummysecretFromDemo"); SecretPropertiesTest.assertProperty("secretProp1", "val1FromDemo"); SecretPropertiesTest.assertProperty("secretProp2", "val2FromDemo"); SecretPropertiesTest.assertProperty("secretProp3", "val3FromDemo"); SecretPropertiesTest.assertProperty("secretProp4", "val4FromDemo"); } public static
NamespacedConfigMapPropertiesTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvMedianLongEvaluator.java
{ "start": 4864, "end": 5356 }
class ____ implements EvalOperator.ExpressionEvaluator.Factory { private final EvalOperator.ExpressionEvaluator.Factory field; public Factory(EvalOperator.ExpressionEvaluator.Factory field) { this.field = field; } @Override public MvMedianLongEvaluator get(DriverContext context) { return new MvMedianLongEvaluator(field.get(context), context); } @Override public String toString() { return "MvMedian[field=" + field + "]"; } } }
Factory
java
mockito__mockito
mockito-core/src/main/java/org/mockito/stubbing/VoidAnswer5.java
{ "start": 166, "end": 1338 }
interface ____ be used for configuring mock's answer for a five argument invocation that returns nothing. * * Answer specifies an action that is executed when you interact with the mock. * <p> * Example of stubbing a mock with this custom answer: * * <pre class="code"><code class="java"> * import static org.mockito.AdditionalAnswers.answerVoid; * * doAnswer(answerVoid( * new VoidAnswer5&lt;String, Integer, String, Character, String&gt;() { * public void answer(String msg, Integer count, String another, Character c, String subject) throws Exception { * throw new Exception(String.format(msg, another, c, count, subject)); * } * })).when(mock).someMethod(anyString(), anyInt(), anyString(), anyChar(), anyString()); * * //Following will raise an exception with the message "ka-boom &lt;3 mockito" * mock.someMethod("%s-boom %c%d %s", 3, "ka", '&lt;', "mockito"); * </code></pre> * * @param <A0> type of the first argument * @param <A1> type of the second argument * @param <A2> type of the third argument * @param <A3> type of the fourth argument * @param <A4> type of the fifth argument * @see Answer */ public
to
java
netty__netty
transport-classes-io_uring/src/main/java/io/netty/channel/uring/IoUringDomainSocketChannel.java
{ "start": 3398, "end": 10240 }
class ____ extends IoUringStreamUnsafe { private MsgHdrMemory writeMsgHdrMemory; private MsgHdrMemory readMsgHdrMemory; @Override protected int scheduleWriteSingle(Object msg) { if (msg instanceof FileDescriptor) { // we can reuse the same memory for any fd // because we never have more than a single outstanding write. if (writeMsgHdrMemory == null) { writeMsgHdrMemory = new MsgHdrMemory(); } IoRegistration registration = registration(); IoUringIoOps ioUringIoOps = prepSendFdIoOps((FileDescriptor) msg, writeMsgHdrMemory); writeId = registration.submit(ioUringIoOps); writeOpCode = Native.IORING_OP_SENDMSG; if (writeId == 0) { MsgHdrMemory memory = writeMsgHdrMemory; writeMsgHdrMemory = null; memory.release(); return 0; } return 1; } return super.scheduleWriteSingle(msg); } @Override boolean writeComplete0(byte op, int res, int flags, short data, int outstanding) { if (op == Native.IORING_OP_SENDMSG) { writeId = 0; writeOpCode = 0; if (res == Native.ERRNO_ECANCELED_NEGATIVE) { return true; } try { int nativeCallResult = res >= 0 ? res : Errors.ioResult("io_uring sendmsg", res); if (nativeCallResult >= 0) { ChannelOutboundBuffer channelOutboundBuffer = unsafe().outboundBuffer(); channelOutboundBuffer.remove(); } } catch (Throwable throwable) { handleWriteError(throwable); } return true; } return super.writeComplete0(op, res, flags, data, outstanding); } private IoUringIoOps prepSendFdIoOps(FileDescriptor fileDescriptor, MsgHdrMemory msgHdrMemory) { msgHdrMemory.setScmRightsFd(fileDescriptor.intValue()); return IoUringIoOps.newSendmsg( fd().intValue(), (byte) 0, 0, msgHdrMemory.address(), msgHdrMemory.idx()); } @Override protected int scheduleRead0(boolean first, boolean socketIsEmpty) { DomainSocketReadMode readMode = config.getReadMode(); switch (readMode) { case FILE_DESCRIPTORS: return scheduleRecvReadFd(); case BYTES: return super.scheduleRead0(first, socketIsEmpty); default: throw new Error("Unexpected read mode: " + readMode); } } private int scheduleRecvReadFd() { // we can reuse the same memory for any fd // because we only submit one outstanding read if (readMsgHdrMemory == null) { readMsgHdrMemory = new MsgHdrMemory(); } readMsgHdrMemory.prepRecvReadFd(); IoRegistration registration = registration(); IoUringIoOps ioUringIoOps = IoUringIoOps.newRecvmsg( fd().intValue(), (byte) 0, 0, readMsgHdrMemory.address(), readMsgHdrMemory.idx()); readId = registration.submit(ioUringIoOps); readOpCode = Native.IORING_OP_RECVMSG; if (readId == 0) { MsgHdrMemory memory = readMsgHdrMemory; readMsgHdrMemory = null; memory.release(); return 0; } return 1; } @Override protected void readComplete0(byte op, int res, int flags, short data, int outstanding) { if (op == Native.IORING_OP_RECVMSG) { readId = 0; if (res == Native.ERRNO_ECANCELED_NEGATIVE) { return; } final IoUringRecvByteAllocatorHandle allocHandle = recvBufAllocHandle(); final ChannelPipeline pipeline = pipeline(); try { int nativeCallResult = res >= 0 ? res : Errors.ioResult("io_uring recvmsg", res); int nativeFd = readMsgHdrMemory.getScmRightsFd(); allocHandle.lastBytesRead(nativeFd); allocHandle.incMessagesRead(1); pipeline.fireChannelRead(new FileDescriptor(nativeFd)); } catch (Throwable throwable) { handleReadException(pipeline, null, throwable, false, allocHandle); } finally { allocHandle.readComplete(); pipeline.fireChannelReadComplete(); } return; } super.readComplete0(op, res, flags, data, outstanding); } @Override public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { // Make sure to assign local/remote first before triggering the callback, to prevent potential NPE issues. ChannelPromise channelPromise = newPromise().addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { local = localAddress != null ? (DomainSocketAddress) localAddress : socket.localDomainSocketAddress(); remote = (DomainSocketAddress) remoteAddress; promise.setSuccess(); } else { promise.setFailure(future.cause()); } } }); super.connect(remoteAddress, localAddress, channelPromise); } @Override public void unregistered() { super.unregistered(); if (readMsgHdrMemory != null) { readMsgHdrMemory.release(); readMsgHdrMemory = null; } if (writeMsgHdrMemory != null) { writeMsgHdrMemory.release(); writeMsgHdrMemory = null; } } } @Override boolean isPollInFirst() { DomainSocketReadMode readMode = config.getReadMode(); switch (readMode) { case BYTES: return super.isPollInFirst(); case FILE_DESCRIPTORS: return false; default: throw new Error("Unexpected read mode: " + readMode); } } }
IoUringDomainSocketUnsafe
java
alibaba__druid
core/src/main/java/com/alibaba/druid/sql/ast/statement/SQLShowFunctionsStatement.java
{ "start": 906, "end": 1786 }
class ____ extends SQLStatementImpl implements SQLShowStatement, SQLReplaceable { protected SQLExpr like; private SQLName kind; public SQLExpr getLike() { return like; } public void setLike(SQLExpr x) { if (x != null) { x.setParent(this); } this.like = x; } public SQLName getKind() { return kind; } public void setKind(SQLName kind) { this.kind = kind; } @Override protected void accept0(SQLASTVisitor visitor) { if (visitor.visit(this)) { if (like != null) { like.accept(visitor); } } } @Override public boolean replace(SQLExpr expr, SQLExpr target) { if (like == expr) { setLike(target); return true; } return false; } }
SQLShowFunctionsStatement
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/mixins/TestMixinInheritance.java
{ "start": 726, "end": 863 }
class ____ { public int getIdo() { return 13; } public String getNameo() { return "Bill"; } } static abstract
Beano2
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/DataXceiverServer.java
{ "start": 1853, "end": 2991 }
class ____ implements Runnable { public static final Logger LOG = DataNode.LOG; /** * Default time to wait (in seconds) for the number of running threads to drop * below the newly requested maximum before giving up. */ private static final int DEFAULT_RECONFIGURE_WAIT = 30; private final PeerServer peerServer; private final DataNode datanode; private final HashMap<Peer, Thread> peers = new HashMap<>(); private final HashMap<Peer, DataXceiver> peersXceiver = new HashMap<>(); private final Lock lock = new ReentrantLock(); private final Condition noPeers = lock.newCondition(); private boolean closed = false; private int maxReconfigureWaitTime = DEFAULT_RECONFIGURE_WAIT; /** * Maximal number of concurrent xceivers per node. * Enforcing the limit is required in order to avoid data-node * running out of memory. */ volatile int maxXceiverCount; /** * A manager to make sure that cluster balancing does not take too much * resources. * * It limits the number of block moves for balancing and the total amount of * bandwidth they can use. */ static
DataXceiverServer
java
grpc__grpc-java
xds/src/test/java/io/grpc/xds/internal/rbac/engine/GrpcAuthorizationEngineTest.java
{ "start": 3081, "end": 23006 }
class ____ { @Rule public final MockitoRule mocks = MockitoJUnit.rule(); private static final String POLICY_NAME = "policy-name"; private static final String HEADER_KEY = "header-key"; private static final String HEADER_VALUE = "header-val"; private static final String IP_ADDR1 = "10.10.10.0"; private static final String IP_ADDR2 = "68.36.0.19"; private static final int PORT = 100; private static final String PATH = "/auth/engine"; private static final StringMatcher STRING_MATCHER = StringMatcher.forExact("/" + PATH, false); private static final Metadata HEADER = metadata(HEADER_KEY, HEADER_VALUE); @Mock private ServerCall<Void,Void> serverCall; @Mock private SSLSession sslSession; @Before public void setUp() throws Exception { X509Certificate[] certs = {TestUtils.loadX509Cert("server1.pem")}; when(sslSession.getPeerCertificates()).thenReturn(certs); Attributes attributes = Attributes.newBuilder() .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, new InetSocketAddress(IP_ADDR2, PORT)) .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, new InetSocketAddress(IP_ADDR1, PORT)) .set(Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession) .build(); when(serverCall.getAttributes()).thenReturn(attributes); when(serverCall.getMethodDescriptor()).thenReturn(method().build()); } @Test public void ipMatcher() throws Exception { CidrMatcher ip1 = CidrMatcher.create(InetAddress.getByName(IP_ADDR1), 24); DestinationIpMatcher destIpMatcher = DestinationIpMatcher.create(ip1); CidrMatcher ip2 = CidrMatcher.create(InetAddress.getByName(IP_ADDR2), 24); SourceIpMatcher sourceIpMatcher = SourceIpMatcher.create(ip2); DestinationPortMatcher portMatcher = DestinationPortMatcher.create(PORT); OrMatcher permission = OrMatcher.create(AndMatcher.create(portMatcher, destIpMatcher)); OrMatcher principal = OrMatcher.create(sourceIpMatcher); PolicyMatcher policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal); GrpcAuthorizationEngine engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW)); AuthDecision decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.ALLOW); assertThat(decision.matchingPolicyName()).isEqualTo(POLICY_NAME); Attributes attributes = Attributes.newBuilder() .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, new InetSocketAddress(IP_ADDR2, PORT)) .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, new InetSocketAddress(IP_ADDR1, 2)) .build(); when(serverCall.getAttributes()).thenReturn(attributes); decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.DENY); assertThat(decision.matchingPolicyName()).isEqualTo(null); attributes = Attributes.newBuilder() .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, null) .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, new InetSocketAddress("1.1.1.1", PORT)) .build(); when(serverCall.getAttributes()).thenReturn(attributes); decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.DENY); assertThat(decision.matchingPolicyName()).isEqualTo(null); engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.DENY)); decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.ALLOW); assertThat(decision.matchingPolicyName()).isEqualTo(null); } @Test public void headerMatcher() { AuthHeaderMatcher headerMatcher = AuthHeaderMatcher.create(Matchers.HeaderMatcher .forExactValue(HEADER_KEY, HEADER_VALUE, false)); OrMatcher principal = OrMatcher.create(headerMatcher); OrMatcher permission = OrMatcher.create( InvertMatcher.create(DestinationPortMatcher.create(PORT + 1))); PolicyMatcher policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal); GrpcAuthorizationEngine engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW)); AuthDecision decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.ALLOW); assertThat(decision.matchingPolicyName()).isEqualTo(POLICY_NAME); HEADER.put(Metadata.Key.of(HEADER_KEY, Metadata.ASCII_STRING_MARSHALLER), HEADER_VALUE); headerMatcher = AuthHeaderMatcher.create(Matchers.HeaderMatcher .forExactValue(HEADER_KEY, HEADER_VALUE + "," + HEADER_VALUE, false)); principal = OrMatcher.create(headerMatcher); policyMatcher = PolicyMatcher.create(POLICY_NAME, OrMatcher.create(AlwaysTrueMatcher.INSTANCE), principal); engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW)); decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.ALLOW); headerMatcher = AuthHeaderMatcher.create(Matchers.HeaderMatcher .forExactValue(HEADER_KEY + Metadata.BINARY_HEADER_SUFFIX, HEADER_VALUE, false)); principal = OrMatcher.create(headerMatcher); policyMatcher = PolicyMatcher.create(POLICY_NAME, OrMatcher.create(AlwaysTrueMatcher.INSTANCE), principal); engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW)); decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.DENY); } @Test public void headerMatcher_binaryHeader() { AuthHeaderMatcher headerMatcher = AuthHeaderMatcher.create(Matchers.HeaderMatcher .forExactValue(HEADER_KEY + Metadata.BINARY_HEADER_SUFFIX, BaseEncoding.base64().omitPadding().encode(HEADER_VALUE.getBytes(US_ASCII)), false)); OrMatcher principal = OrMatcher.create(headerMatcher); OrMatcher permission = OrMatcher.create( InvertMatcher.create(DestinationPortMatcher.create(PORT + 1))); PolicyMatcher policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal); GrpcAuthorizationEngine engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW)); Metadata metadata = new Metadata(); metadata.put(Metadata.Key.of(HEADER_KEY + Metadata.BINARY_HEADER_SUFFIX, Metadata.BINARY_BYTE_MARSHALLER), HEADER_VALUE.getBytes(US_ASCII)); AuthDecision decision = engine.evaluate(metadata, serverCall); assertThat(decision.decision()).isEqualTo(Action.ALLOW); assertThat(decision.matchingPolicyName()).isEqualTo(POLICY_NAME); } @Test public void headerMatcher_hardcodePostMethod() { AuthHeaderMatcher headerMatcher = AuthHeaderMatcher.create(Matchers.HeaderMatcher .forExactValue(":method", "POST", false)); OrMatcher principal = OrMatcher.create(headerMatcher); OrMatcher permission = OrMatcher.create( InvertMatcher.create(DestinationPortMatcher.create(PORT + 1))); PolicyMatcher policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal); GrpcAuthorizationEngine engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW)); AuthDecision decision = engine.evaluate(new Metadata(), serverCall); assertThat(decision.decision()).isEqualTo(Action.ALLOW); assertThat(decision.matchingPolicyName()).isEqualTo(POLICY_NAME); } @Test public void headerMatcher_pathHeader() { AuthHeaderMatcher headerMatcher = AuthHeaderMatcher.create(Matchers.HeaderMatcher .forExactValue(":path", "/" + PATH, false)); OrMatcher principal = OrMatcher.create(headerMatcher); OrMatcher permission = OrMatcher.create( InvertMatcher.create(DestinationPortMatcher.create(PORT + 1))); PolicyMatcher policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal); GrpcAuthorizationEngine engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW)); AuthDecision decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.ALLOW); assertThat(decision.matchingPolicyName()).isEqualTo(POLICY_NAME); } @Test public void headerMatcher_aliasAuthorityAndHost() { AuthHeaderMatcher headerMatcher = AuthHeaderMatcher.create(Matchers.HeaderMatcher .forExactValue("Host", "google.com", false)); OrMatcher principal = OrMatcher.create(headerMatcher); OrMatcher permission = OrMatcher.create( InvertMatcher.create(DestinationPortMatcher.create(PORT + 1))); PolicyMatcher policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal); GrpcAuthorizationEngine engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW)); when(serverCall.getAuthority()).thenReturn("google.com"); AuthDecision decision = engine.evaluate(new Metadata(), serverCall); assertThat(decision.decision()).isEqualTo(Action.ALLOW); assertThat(decision.matchingPolicyName()).isEqualTo(POLICY_NAME); } @Test public void pathMatcher() { PathMatcher pathMatcher = PathMatcher.create(STRING_MATCHER); OrMatcher permission = OrMatcher.create(AlwaysTrueMatcher.INSTANCE); OrMatcher principal = OrMatcher.create(pathMatcher); PolicyMatcher policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal); GrpcAuthorizationEngine engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.DENY)); AuthDecision decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.DENY); assertThat(decision.matchingPolicyName()).isEqualTo(POLICY_NAME); } @Test public void authenticatedMatcher() throws Exception { AuthenticatedMatcher authMatcher = AuthenticatedMatcher.create( StringMatcher.forExact("*.test.google.fr", false)); PathMatcher pathMatcher = PathMatcher.create(STRING_MATCHER); OrMatcher permission = OrMatcher.create(authMatcher); OrMatcher principal = OrMatcher.create(pathMatcher); PolicyMatcher policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal); GrpcAuthorizationEngine engine = new GrpcAuthorizationEngine( AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW)); AuthDecision decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.ALLOW); assertThat(decision.matchingPolicyName()).isEqualTo(POLICY_NAME); X509Certificate[] certs = {TestUtils.loadX509Cert("badserver.pem")}; when(sslSession.getPeerCertificates()).thenReturn(certs); decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.DENY); assertThat(decision.matchingPolicyName()).isEqualTo(null); X509Certificate mockCert = mock(X509Certificate.class); when(sslSession.getPeerCertificates()).thenReturn(new X509Certificate[]{mockCert}); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.DENY); when(mockCert.getSubjectX500Principal()).thenReturn(new X500Principal("")); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.DENY); when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList( Arrays.asList(2, "*.test.google.fr"))); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW); when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList( Arrays.asList(6, "*.test.google.fr"))); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW); when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList( Arrays.asList(10, "*.test.google.fr"))); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.DENY); when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList( Arrays.asList(2, "google.com"), Arrays.asList(6, "*.test.google.fr"))); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW); when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList( Arrays.asList(6, "*.test.google.fr"), Arrays.asList(2, "google.com"))); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW); when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList( Arrays.asList(2, "*.test.google.fr"), Arrays.asList(6, "google.com"))); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.DENY); when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList( Arrays.asList(2, "*.test.google.fr"), Arrays.asList(6, "google.com"), Arrays.asList(6, "*.test.google.fr"))); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW); // match any authenticated connection if StringMatcher not set in AuthenticatedMatcher permission = OrMatcher.create(AuthenticatedMatcher.create(null)); policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal); when(mockCert.getSubjectAlternativeNames()).thenReturn( Arrays.<List<?>>asList(Arrays.asList(6, "random"))); engine = new GrpcAuthorizationEngine(AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW)); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW); // not match any unauthenticated connection Attributes attributes = Attributes.newBuilder() .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, new InetSocketAddress(IP_ADDR2, PORT)) .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, new InetSocketAddress(IP_ADDR1, PORT)) .build(); when(serverCall.getAttributes()).thenReturn(attributes); assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.DENY); doThrow(new SSLPeerUnverifiedException("bad")).when(sslSession).getPeerCertificates(); decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.DENY); assertThat(decision.matchingPolicyName()).isEqualTo(null); } @Test public void multiplePolicies() throws Exception { AuthenticatedMatcher authMatcher = AuthenticatedMatcher.create( StringMatcher.forSuffix("TEST.google.fr", true)); PathMatcher pathMatcher = PathMatcher.create(STRING_MATCHER); OrMatcher principal = OrMatcher.create(AndMatcher.create(authMatcher, pathMatcher)); OrMatcher permission = OrMatcher.create(AndMatcher.create(pathMatcher, InvertMatcher.create(DestinationPortMatcher.create(PORT + 1)))); PolicyMatcher policyMatcher1 = PolicyMatcher.create(POLICY_NAME, permission, principal); AuthHeaderMatcher headerMatcher = AuthHeaderMatcher.create(Matchers.HeaderMatcher .forExactValue(HEADER_KEY, HEADER_VALUE + 1, false)); authMatcher = AuthenticatedMatcher.create( StringMatcher.forContains("TEST.google.fr")); principal = OrMatcher.create(headerMatcher, authMatcher); CidrMatcher ip1 = CidrMatcher.create(InetAddress.getByName(IP_ADDR1), 24); DestinationIpMatcher destIpMatcher = DestinationIpMatcher.create(ip1); permission = OrMatcher.create(destIpMatcher, pathMatcher); PolicyMatcher policyMatcher2 = PolicyMatcher.create(POLICY_NAME + "-2", permission, principal); GrpcAuthorizationEngine engine = new GrpcAuthorizationEngine( AuthConfig.create(ImmutableList.of(policyMatcher1, policyMatcher2), Action.DENY)); AuthDecision decision = engine.evaluate(HEADER, serverCall); assertThat(decision.decision()).isEqualTo(Action.DENY); assertThat(decision.matchingPolicyName()).isEqualTo(POLICY_NAME); } @Test public void matchersEqualHashcode() throws Exception { PathMatcher pathMatcher = PathMatcher.create(STRING_MATCHER); AuthHeaderMatcher headerMatcher = AuthHeaderMatcher.create( Matchers.HeaderMatcher.forExactValue("foo", "bar", true)); DestinationIpMatcher destinationIpMatcher = DestinationIpMatcher.create( CidrMatcher.create(InetAddress.getByName(IP_ADDR1), 24)); DestinationPortMatcher destinationPortMatcher = DestinationPortMatcher.create(PORT); GrpcAuthorizationEngine.DestinationPortRangeMatcher portRangeMatcher = GrpcAuthorizationEngine.DestinationPortRangeMatcher.create(PORT, PORT + 1); InvertMatcher invertMatcher = InvertMatcher.create(portRangeMatcher); GrpcAuthorizationEngine.RequestedServerNameMatcher requestedServerNameMatcher = GrpcAuthorizationEngine.RequestedServerNameMatcher.create(STRING_MATCHER); OrMatcher permission = OrMatcher.create(pathMatcher, headerMatcher, destinationIpMatcher, destinationPortMatcher, invertMatcher, requestedServerNameMatcher); AuthenticatedMatcher authenticatedMatcher = AuthenticatedMatcher.create(STRING_MATCHER); SourceIpMatcher sourceIpMatcher1 = SourceIpMatcher.create( CidrMatcher.create(InetAddress.getByName(IP_ADDR1), 24)); OrMatcher principal = OrMatcher.create(authenticatedMatcher, AndMatcher.create(sourceIpMatcher1, AlwaysTrueMatcher.INSTANCE)); PolicyMatcher policyMatcher1 = PolicyMatcher.create("match", permission, principal); AuthConfig config1 = AuthConfig.create(Collections.singletonList(policyMatcher1), Action.ALLOW); PathMatcher pathMatcher2 = PathMatcher.create(STRING_MATCHER); AuthHeaderMatcher headerMatcher2 = AuthHeaderMatcher.create( Matchers.HeaderMatcher.forExactValue("foo", "bar", true)); DestinationIpMatcher destinationIpMatcher2 = DestinationIpMatcher.create( CidrMatcher.create(InetAddress.getByName(IP_ADDR1), 24)); DestinationPortMatcher destinationPortMatcher2 = DestinationPortMatcher.create(PORT); GrpcAuthorizationEngine.DestinationPortRangeMatcher portRangeMatcher2 = GrpcAuthorizationEngine.DestinationPortRangeMatcher.create(PORT, PORT + 1); InvertMatcher invertMatcher2 = InvertMatcher.create(portRangeMatcher2); GrpcAuthorizationEngine.RequestedServerNameMatcher requestedServerNameMatcher2 = GrpcAuthorizationEngine.RequestedServerNameMatcher.create(STRING_MATCHER); OrMatcher permission2 = OrMatcher.create(pathMatcher2, headerMatcher2, destinationIpMatcher2, destinationPortMatcher2, invertMatcher2, requestedServerNameMatcher2); AuthenticatedMatcher authenticatedMatcher2 = AuthenticatedMatcher.create(STRING_MATCHER); SourceIpMatcher sourceIpMatcher2 = SourceIpMatcher.create( CidrMatcher.create(InetAddress.getByName(IP_ADDR1), 24)); OrMatcher principal2 = OrMatcher.create(authenticatedMatcher2, AndMatcher.create(sourceIpMatcher2, AlwaysTrueMatcher.INSTANCE)); PolicyMatcher policyMatcher2 = PolicyMatcher.create("match", permission2, principal2); AuthConfig config2 = AuthConfig.create(Collections.singletonList(policyMatcher2), Action.ALLOW); assertThat(config1).isEqualTo(config2); assertThat(config1.hashCode()).isEqualTo(config2.hashCode()); } private MethodDescriptor.Builder<Void, Void> method() { return MethodDescriptor.<Void,Void>newBuilder() .setType(MethodType.BIDI_STREAMING) .setFullMethodName(PATH) .setRequestMarshaller(TestMethodDescriptors.voidMarshaller()) .setResponseMarshaller(TestMethodDescriptors.voidMarshaller()); } private static Metadata metadata(String key, String value) { Metadata metadata = new Metadata(); metadata.put(Metadata.Key.of(key, Metadata.ASCII_STRING_MARSHALLER), value); return metadata; } }
GrpcAuthorizationEngineTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesReplicationControllersEndpointBuilderFactory.java
{ "start": 16703, "end": 23968 }
interface ____ extends EndpointConsumerBuilder { default KubernetesReplicationControllersEndpointConsumerBuilder basic() { return (KubernetesReplicationControllersEndpointConsumerBuilder) this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedKubernetesReplicationControllersEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedKubernetesReplicationControllersEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedKubernetesReplicationControllersEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedKubernetesReplicationControllersEndpointConsumerBuilder exceptionHandler(String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedKubernetesReplicationControllersEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedKubernetesReplicationControllersEndpointConsumerBuilder exchangePattern(String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Connection timeout in milliseconds to use when making requests to the * Kubernetes API server. * * The option is a: <code>java.lang.Integer</code> type. * * Group: advanced * * @param connectionTimeout the value to set * @return the dsl builder */ default AdvancedKubernetesReplicationControllersEndpointConsumerBuilder connectionTimeout(Integer connectionTimeout) { doSetProperty("connectionTimeout", connectionTimeout); return this; } /** * Connection timeout in milliseconds to use when making requests to the * Kubernetes API server. * * The option will be converted to a <code>java.lang.Integer</code> * type. * * Group: advanced * * @param connectionTimeout the value to set * @return the dsl builder */ default AdvancedKubernetesReplicationControllersEndpointConsumerBuilder connectionTimeout(String connectionTimeout) { doSetProperty("connectionTimeout", connectionTimeout); return this; } } /** * Builder for endpoint producers for the Kubernetes Replication Controller component. */ public
AdvancedKubernetesReplicationControllersEndpointConsumerBuilder
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/job/JobResourcesRequirementsUpdateHeaders.java
{ "start": 1326, "end": 2656 }
class ____ implements RuntimeMessageHeaders< JobResourceRequirementsBody, EmptyResponseBody, JobMessageParameters> { public static final JobResourcesRequirementsUpdateHeaders INSTANCE = new JobResourcesRequirementsUpdateHeaders(); private static final String URL = "/jobs/:" + JobIDPathParameter.KEY + "/resource-requirements"; @Override public HttpMethodWrapper getHttpMethod() { return HttpMethodWrapper.PUT; } @Override public String getTargetRestEndpointURL() { return URL; } @Override public Class<EmptyResponseBody> getResponseClass() { return EmptyResponseBody.class; } @Override public HttpResponseStatus getResponseStatusCode() { return HttpResponseStatus.OK; } @Override public String getDescription() { return "Request to update job's resource requirements."; } @Override public Class<JobResourceRequirementsBody> getRequestClass() { return JobResourceRequirementsBody.class; } @Override public JobMessageParameters getUnresolvedMessageParameters() { return new JobMessageParameters(); } @Override public String operationId() { return "updateJobResourceRequirements"; } }
JobResourcesRequirementsUpdateHeaders
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/cache/config/AnnotationDrivenCacheConfigTests.java
{ "start": 947, "end": 1228 }
class ____ extends AbstractCacheAnnotationTests { @Override protected ConfigurableApplicationContext getApplicationContext() { return new GenericXmlApplicationContext( "/org/springframework/cache/config/annotationDrivenCacheConfig.xml"); } }
AnnotationDrivenCacheConfigTests
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/scheduler/BoundedElasticScheduler.java
{ "start": 15040, "end": 24136 }
class ____ { final BoundedState[] array; final boolean shutdown; public BusyStates(BoundedState[] array, boolean shutdown) { this.array = array; this.shutdown = shutdown; } } /** * The {@link ZoneId} used for clocks. Since the {@link Clock} is only used to ensure * TTL cleanup is executed every N seconds, the zone doesn't really matter, hence UTC. * @implNote Note that {@link ZoneId#systemDefault()} isn't used since it triggers disk read, * contrary to {@link ZoneId#of(String)}. */ static final ZoneId ZONE_UTC = ZoneId.of("UTC"); static final BusyStates ALL_IDLE = new BusyStates(new BoundedState[0], false); static final BusyStates ALL_SHUTDOWN = new BusyStates(new BoundedState[0], true); static final ScheduledExecutorService EVICTOR_SHUTDOWN; static final BoundedServices SHUTDOWN; static final BoundedServices SHUTTING_DOWN; static final BoundedState CREATING; static { EVICTOR_SHUTDOWN = Executors.newSingleThreadScheduledExecutor(); EVICTOR_SHUTDOWN.shutdownNow(); SHUTDOWN = new BoundedServices(); SHUTTING_DOWN = new BoundedServices(); SHUTDOWN.dispose(); SHUTTING_DOWN.dispose(); ScheduledExecutorService s = Executors.newSingleThreadScheduledExecutor(); s.shutdownNow(); CREATING = new BoundedState(SHUTDOWN, s) { @Override public String toString() { return "CREATING BoundedState"; } }; CREATING.markCount = -1; //always -1, ensures tryPick never returns true CREATING.idleSinceTimestamp = -1; //consider evicted } static final AtomicLong EVICTOR_COUNTER = new AtomicLong(); static final ThreadFactory EVICTOR_FACTORY = r -> { Thread t = new Thread(r, Schedulers.BOUNDED_ELASTIC + "-evictor-" + EVICTOR_COUNTER.incrementAndGet()); t.setDaemon(true); return t; }; @SuppressWarnings("NotNullFieldNotInitialized") // initialized in constructor final BoundedElasticScheduler parent; //duplicated Clock field from parent so that SHUTDOWN can be instantiated and partially used final Clock clock; final ScheduledExecutorService evictor; final Deque<BoundedState> idleQueue; volatile BusyStates busyStates; static final AtomicReferenceFieldUpdater<BoundedServices, BusyStates> BUSY_STATES = AtomicReferenceFieldUpdater.newUpdater(BoundedServices.class, BusyStates.class, "busyStates"); //constructor for SHUTDOWN @SuppressWarnings("DataFlowIssue") // only used for SHUTDOWN instance private BoundedServices() { this.parent = null; this.clock = Clock.fixed(Instant.EPOCH, ZONE_UTC); this.idleQueue = new ConcurrentLinkedDeque<>(); this.busyStates = ALL_SHUTDOWN; this.evictor = EVICTOR_SHUTDOWN; } BoundedServices(BoundedElasticScheduler parent) { this.parent = parent; this.clock = parent.clock; this.idleQueue = new ConcurrentLinkedDeque<>(); this.busyStates = ALL_IDLE; this.evictor = Executors.newSingleThreadScheduledExecutor(EVICTOR_FACTORY); } /** * Trigger the eviction by computing the oldest acceptable timestamp and letting each {@link BoundedState} * check (and potentially shutdown) itself. */ void eviction() { final long evictionTimestamp = parent.clock.millis(); List<BoundedState> idleCandidates = new ArrayList<>(idleQueue); for (BoundedState candidate : idleCandidates) { if (candidate.tryEvict(evictionTimestamp, parent.ttlMillis)) { idleQueue.remove(candidate); decrementAndGet(); } } } /** * @param bs the state to set busy * @return true if the {@link BoundedState} could be added to the busy array (ie. we're not shut down), false if shutting down */ boolean setBusy(BoundedState bs) { for (; ; ) { BusyStates previous = busyStates; if (previous.shutdown) { return false; } int len = previous.array.length; BoundedState[] replacement = new BoundedState[len + 1]; System.arraycopy(previous.array, 0, replacement, 0, len); replacement[len] = bs; if (BUSY_STATES.compareAndSet(this, previous, new BusyStates(replacement, false))) { return true; } } } void setIdle(BoundedState boundedState) { for(;;) { BusyStates current = busyStates; BoundedState[] arr = busyStates.array; int len = arr.length; if (len == 0 || current.shutdown) { return; } BusyStates replacement = null; if (len == 1) { if (arr[0] == boundedState) { replacement = ALL_IDLE; } } else { for (int i = 0; i < len; i++) { BoundedState state = arr[i]; if (state == boundedState) { replacement = new BusyStates( new BoundedState[len - 1], false ); System.arraycopy(arr, 0, replacement.array, 0, i); System.arraycopy(arr, i + 1, replacement.array, i, len - i - 1); break; } } } if (replacement == null) { //bounded state not found, ignore return; } if (BUSY_STATES.compareAndSet(this, current, replacement)) { //impl. note: reversed order could lead to a race condition where state is added to idleQueue //then concurrently pick()ed into busyQueue then removed from same busyQueue. this.idleQueue.add(boundedState); // check whether we missed a shutdown if (this.busyStates.shutdown) { // we did, so we make sure the racing adds don't leak boundedState.shutdown(true); while ((boundedState = idleQueue.pollLast()) != null) { boundedState.shutdown(true); } } return; } } } /** * Pick a {@link BoundedState}, prioritizing idle ones then spinning up a new one if enough capacity. * Otherwise, picks an active one by taking from a {@link PriorityQueue}. The picking is * optimistically re-attempted if the picked slot cannot be marked as picked. * * @return the picked {@link BoundedState} */ BoundedState pick() { for (;;) { if (busyStates == ALL_SHUTDOWN) { return CREATING; //synonym for shutdown, since the underlying executor is shut down } int a = get(); if (!idleQueue.isEmpty()) { //try to find an idle resource BoundedState bs = idleQueue.pollLast(); if (bs != null && bs.markPicked()) { boolean accepted = setBusy(bs); if (!accepted) { // shutdown in the meantime bs.shutdown(true); return CREATING; } return bs; } //else optimistically retry (implicit continue here) } else if (a < parent.maxThreads) { //try to build a new resource if (compareAndSet(a, a + 1)) { ScheduledExecutorService s = Schedulers.decorateExecutorService(parent, parent.createBoundedExecutorService()); BoundedState newState = new BoundedState(this, s); if (newState.markPicked()) { boolean accepted = setBusy(newState); if (!accepted) { // shutdown in the meantime newState.shutdown(true); return CREATING; } return newState; } } //else optimistically retry (implicit continue here) } else { BoundedState s = choseOneBusy(); if (s != null && s.markPicked()) { return s; } //else optimistically retry (implicit continue here) } } } private @Nullable BoundedState choseOneBusy() { BoundedState[] arr = busyStates.array; int len = arr.length; if (len == 0) { return null; //implicit retry in the pick() loop } if (len == 1) { return arr[0]; } BoundedState choice = arr[0]; int leastBusy = Integer.MAX_VALUE; for (int i = 0; i < arr.length; i++) { BoundedState state = arr[i]; int busy = state.markCount; if (busy < leastBusy) { leastBusy = busy; choice = state; } } return choice; } public BoundedState[] dispose() { BusyStates current; for (;;) { current = busyStates; if (current.shutdown) { return current.array; } if (BUSY_STATES.compareAndSet(this, current, new BusyStates(current.array, true))) { break; } // the race can happen also with scheduled tasks and eviction // so we need to retry if shutdown transition fails } BoundedState[] arr = current.array; // The idleQueue must be drained first as concurrent removals // by evictor or additions by finished tasks can invalidate the size // used if a regular array was created here. // In case of concurrent calls, it is not needed to atomically drain the // queue, nor guarantee same BoundedStates are read, as long as the caller // shuts down the returned BoundedStates. Also, idle ones should easily // shut down, it's not necessary to distinguish graceful from forceful. ArrayList<BoundedState> toAwait = new ArrayList<>(idleQueue.size() + arr.length); BoundedState bs; while ((bs = idleQueue.pollLast()) != null) { toAwait.add(bs); } Collections.addAll(toAwait, arr); return toAwait.toArray(new BoundedState[0]); } } /** * A
BusyStates
java
micronaut-projects__micronaut-core
http/src/main/java/io/micronaut/http/body/stream/StreamPair.java
{ "start": 993, "end": 1181 }
class ____ a single stream into two, based on configured * {@link io.micronaut.http.body.ByteBody.SplitBackpressureMode}. * * @since 4.6.0 * @author Jonas Konrad */ @Internal final
splits
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/IdentifierNameTest.java
{ "start": 1608, "end": 1947 }
class ____ { private int fooBar; int get() { return fooBar; } } """) .doTest(); } @Test public void nameWithUnderscores_findingEmphasisesInitialism() { helper .addSourceLines( "Test.java", """
Test
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/tool/schema/extract/internal/SequenceInformationExtractorMariaDBDatabaseImpl.java
{ "start": 609, "end": 3372 }
class ____ extends SequenceInformationExtractorLegacyImpl { /** * Singleton access */ public static final SequenceInformationExtractorMariaDBDatabaseImpl INSTANCE = new SequenceInformationExtractorMariaDBDatabaseImpl(); // SQL to get metadata from individual sequence private static final String SQL_SEQUENCE_QUERY = "SELECT '%1$s' as sequence_name, minimum_value, maximum_value, start_value, increment, cache_size FROM %2$s "; private static final String UNION_ALL = "UNION ALL "; @Override public Iterable<SequenceInformation> extractMetadata(ExtractionContext extractionContext) throws SQLException { final String lookupSql = extractionContext.getJdbcEnvironment().getDialect().getQuerySequencesString(); // *should* never happen, but to be safe in the interest of performance... if ( lookupSql == null ) { return SequenceInformationExtractorNoOpImpl.INSTANCE.extractMetadata(extractionContext); } final List<String> sequenceNames = extractionContext.getQueryResults( lookupSql, null, resultSet -> { final List<String> sequences = new ArrayList<>(); while ( resultSet.next() ) { sequences.add( resultSetSequenceName( resultSet ) ); } return sequences; }); if ( sequenceNames.isEmpty() ) { return emptyList(); } else { final var sequenceInfoQueryBuilder = new StringBuilder(); for ( String sequenceName : sequenceNames ) { if ( !sequenceInfoQueryBuilder.isEmpty() ) { sequenceInfoQueryBuilder.append( UNION_ALL ); } sequenceInfoQueryBuilder.append( String.format( SQL_SEQUENCE_QUERY, sequenceName, Identifier.toIdentifier( sequenceName ) ) ); } return extractionContext.getQueryResults( sequenceInfoQueryBuilder.toString(), null, resultSet -> { final List<SequenceInformation> sequenceInformationList = new ArrayList<>(); final var identifierHelper = extractionContext.getJdbcEnvironment().getIdentifierHelper(); while ( resultSet.next() ) { sequenceInformationList.add( new SequenceInformationImpl( new QualifiedSequenceName( null, null, identifierHelper.toIdentifier( resultSetSequenceName( resultSet ) ) ), resultSetStartValueSize( resultSet ), resultSetMinValue( resultSet ), resultSetMaxValue( resultSet ), resultSetIncrementValue( resultSet ) ) ); } return sequenceInformationList; }); } } protected String resultSetSequenceName(ResultSet resultSet) throws SQLException { return resultSet.getString(1); } @Override protected String sequenceCatalogColumn() { return null; } @Override protected String sequenceSchemaColumn() { return null; } }
SequenceInformationExtractorMariaDBDatabaseImpl
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/termsenum/TermsEnumRequestTests.java
{ "start": 1392, "end": 6731 }
class ____ extends AbstractXContentSerializingTestCase<TermsEnumRequest> { private NamedXContentRegistry xContentRegistry; private NamedWriteableRegistry namedWriteableRegistry; public void setUp() throws Exception { super.setUp(); SearchModule searchModule = new SearchModule(Settings.EMPTY, Collections.emptyList()); List<NamedWriteableRegistry.Entry> entries = new ArrayList<>(); entries.addAll(IndicesModule.getNamedWriteables()); entries.addAll(searchModule.getNamedWriteables()); namedWriteableRegistry = new NamedWriteableRegistry(entries); xContentRegistry = new NamedXContentRegistry(searchModule.getNamedXContents()); } @Override protected TermsEnumRequest createTestInstance() { TermsEnumRequest request = new TermsEnumRequest(); request.size(randomIntBetween(1, 20)); request.field(randomAlphaOfLengthBetween(3, 10)); request.caseInsensitive(randomBoolean()); if (randomBoolean()) { request.indexFilter(QueryBuilders.termQuery("field", randomAlphaOfLength(5))); } String[] randomIndices = new String[randomIntBetween(1, 5)]; for (int i = 0; i < randomIndices.length; i++) { randomIndices[i] = randomAlphaOfLengthBetween(5, 10); } request.indices(randomIndices); if (randomBoolean()) { request.indicesOptions(randomBoolean() ? IndicesOptions.strictExpand() : IndicesOptions.lenientExpandOpen()); } return request; } @Override protected TermsEnumRequest createXContextTestInstance(XContentType xContentType) { return createTestInstance() // these options are outside of the xcontent .indices("test") .indicesOptions(TermsEnumRequest.DEFAULT_INDICES_OPTIONS); } @Override protected NamedWriteableRegistry getNamedWriteableRegistry() { return namedWriteableRegistry; } @Override protected NamedXContentRegistry xContentRegistry() { return xContentRegistry; } @Override protected Writeable.Reader<TermsEnumRequest> instanceReader() { return TermsEnumRequest::new; } @Override protected TermsEnumRequest doParseInstance(XContentParser parser) throws IOException { return TermsEnumAction.fromXContent(parser, "test"); } @Override protected TermsEnumRequest mutateInstance(TermsEnumRequest instance) throws IOException { List<Consumer<TermsEnumRequest>> mutators = new ArrayList<>(); mutators.add(request -> { request.field(randomValueOtherThan(request.field(), () -> randomAlphaOfLengthBetween(3, 10))); }); mutators.add(request -> { String[] indices = ArrayUtils.concat(instance.indices(), generateRandomStringArray(5, 10, false, false)); request.indices(indices); }); mutators.add(request -> { IndicesOptions indicesOptions = randomValueOtherThan( request.indicesOptions(), () -> IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean()) ); request.indicesOptions(indicesOptions); }); mutators.add( request -> request.indexFilter(request.indexFilter() != null ? request.indexFilter().boost(2) : QueryBuilders.matchAllQuery()) ); TermsEnumRequest mutatedInstance = copyInstance(instance); Consumer<TermsEnumRequest> mutator = randomFrom(mutators); mutator.accept(mutatedInstance); return mutatedInstance; } public void testValidation() { TermsEnumRequest request = new TermsEnumRequest(); ActionRequestValidationException validationException = request.validate(); assertEquals(1, validationException.validationErrors().size()); assertEquals("field cannot be null", validationException.validationErrors().get(0)); request.field("field"); validationException = request.validate(); assertNull(validationException); request.timeout(null); validationException = request.validate(); assertEquals(1, validationException.validationErrors().size()); assertEquals("Timeout cannot be null", validationException.validationErrors().get(0)); request.timeout(TimeValue.timeValueSeconds(61)); validationException = request.validate(); assertEquals(1, validationException.validationErrors().size()); assertEquals("Timeout cannot be > 1 minute", validationException.validationErrors().get(0)); request.timeout(TimeValue.timeValueSeconds(10)); request.string(randomAlphaOfLengthBetween(1, IndexWriter.MAX_TERM_LENGTH)); validationException = request.validate(); assertNull(validationException); request.string(randomAlphaOfLengthBetween(IndexWriter.MAX_TERM_LENGTH + 1, IndexWriter.MAX_TERM_LENGTH + 100)); validationException = request.validate(); assertEquals(1, validationException.validationErrors().size()); assertEquals( "prefix string larger than 32766 characters, which is the maximum allowed term length for keyword fields.", validationException.validationErrors().get(0) ); } }
TermsEnumRequestTests
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/contracts/exceptions/KeyProviderException.java
{ "start": 1082, "end": 1441 }
class ____ extends AzureBlobFileSystemException { private static final long serialVersionUID = 1L; public KeyProviderException(String message) { super(message); } public KeyProviderException(String message, Throwable cause) { super(message); } public KeyProviderException(Throwable t) { super(t.getMessage()); } }
KeyProviderException