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
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/function/NamedSqmSetReturningFunctionDescriptor.java
{ "start": 947, "end": 1067 }
class ____ provide details required for processing of the associated * function. * * @since 7.0 */ @Incubating public
to
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/DefaultRolesAllowedJaxRsTest.java
{ "start": 541, "end": 3745 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(PermitAllResource.class, UnsecuredResource.class, TestIdentityProvider.class, UnsecuredResourceInterface.class, TestIdentityController.class, UnsecuredSubResource.class, HelloResource.class, UnsecuredParentResource.class) .addAsResource(new StringAsset("quarkus.security.jaxrs.default-roles-allowed=admin\n"), "application.properties")); @BeforeAll public static void setupUsers() { TestIdentityController.resetRoles() .add("admin", "admin", "admin") .add("user", "user", "user"); } @Test public void shouldDenyUnannotated() { String path = "/unsecured/defaultSecurity"; assertStatus(path, 200, 403, 401); } @Test public void shouldDenyUnannotatedParent() { String path = "/unsecured/defaultSecurityParent"; assertStatus(path, 200, 403, 401); } @Test public void shouldDenyUnannotatedInterface() { String path = "/unsecured/defaultSecurityInterface"; assertStatus(path, 200, 403, 401); } @Test public void shouldDenyDenyAllMethod() { String path = "/unsecured/denyAll"; assertStatus(path, 403, 403, 401); } @Test public void shouldDenyUnannotatedNonBlocking() { String path = "/unsecured/defaultSecurityNonBlocking"; assertStatus(path, 200, 403, 401); } @Test public void shouldPermitPermitAllMethodNonBlocking() { String path = "/permitAll/defaultSecurityNonBlocking"; assertStatus(path, 200, 200, 200); } @Test public void shouldPermitPermitAllMethod() { assertStatus("/unsecured/permitAll", 200, 200, 200); } @Test public void shouldDenySubResource() { String path = "/unsecured/sub/subMethod"; assertStatus(path, 200, 403, 401); } @Test public void shouldAllowPermitAllSubResource() { String path = "/unsecured/permitAllSub/subMethod"; assertStatus(path, 200, 200, 200); } @Test public void shouldAllowPermitAllClass() { String path = "/permitAll/sub/subMethod"; assertStatus(path, 200, 200, 200); } @Test public void testServerExceptionMapper() { given() .get("/hello") .then() .statusCode(200) .body(Matchers.equalTo("unauthorizedExceptionMapper")); } private void assertStatus(String path, int adminStatus, int userStatus, int anonStatus) { given().auth().preemptive() .basic("admin", "admin").get(path) .then() .statusCode(adminStatus); given().auth().preemptive() .basic("user", "user").get(path) .then() .statusCode(userStatus); when().get(path) .then() .statusCode(anonStatus); } }
DefaultRolesAllowedJaxRsTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/view/InfoBlock.java
{ "start": 1656, "end": 2920 }
class ____ extends HtmlBlock { final ResponseInfo info; @Inject InfoBlock(ResponseInfo info) { this.info = info; } @Override protected void render(Block html) { TABLE<DIV<Hamlet>> table = html. div(_INFO_WRAP). table(_INFO). tr(). th().$class(C_TH).$colspan(2).__(info.about()).__().__(); int i = 0; for (ResponseInfo.Item item : info) { TR<TABLE<DIV<Hamlet>>> tr = table. tr((++i % 2 != 0) ? _ODD : _EVEN). th(item.key); String value = String.valueOf(item.value); if (item.url == null) { if (!item.isRaw) { TD<TR<TABLE<DIV<Hamlet>>>> td = tr.td(); if ( value.lastIndexOf('\n') > 0) { String []lines = value.split("\n"); DIV<TD<TR<TABLE<DIV<Hamlet>>>>> singleLineDiv; for ( String line :lines) { singleLineDiv = td.div(); singleLineDiv.__(line); singleLineDiv.__(); } } else { td.__(value); } td.__(); } else { tr.td()._r(value).__(); } } else { tr. td(). a(url(item.url), value).__(); } tr.__(); } table.__().__(); } }
InfoBlock
java
google__guava
guava-testlib/src/com/google/common/collect/testing/testers/MapForEachTester.java
{ "start": 2008, "end": 3371 }
class ____<K, V> extends AbstractMapTester<K, V> { @CollectionFeature.Require(KNOWN_ORDER) public void testForEachKnownOrder() { List<Entry<K, V>> entries = new ArrayList<>(); getMap().forEach((k, v) -> entries.add(entry(k, v))); assertEquals(getOrderedElements(), entries); } @CollectionFeature.Require(absent = KNOWN_ORDER) public void testForEachUnknownOrder() { List<Entry<K, V>> entries = new ArrayList<>(); getMap().forEach((k, v) -> entries.add(entry(k, v))); assertEqualIgnoringOrder(getSampleEntries(), entries); } @MapFeature.Require(ALLOWS_NULL_KEYS) @CollectionSize.Require(absent = ZERO) public void testForEach_nullKeys() { initMapWithNullKey(); List<Entry<K, V>> expectedEntries = asList(createArrayWithNullKey()); List<Entry<K, V>> entries = new ArrayList<>(); getMap().forEach((k, v) -> entries.add(entry(k, v))); assertEqualIgnoringOrder(expectedEntries, entries); } @MapFeature.Require(ALLOWS_NULL_VALUES) @CollectionSize.Require(absent = ZERO) public void testForEach_nullValues() { initMapWithNullValue(); List<Entry<K, V>> expectedEntries = asList(createArrayWithNullValue()); List<Entry<K, V>> entries = new ArrayList<>(); getMap().forEach((k, v) -> entries.add(entry(k, v))); assertEqualIgnoringOrder(expectedEntries, entries); } }
MapForEachTester
java
apache__flink
flink-datastream-api/src/main/java/org/apache/flink/datastream/api/extension/window/context/WindowContext.java
{ "start": 1576, "end": 1731 }
interface ____ a context for window operations and provides methods to interact with * state that is scoped to the window. */ @Experimental public
represents
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest89.java
{ "start": 893, "end": 1497 }
class ____ extends TestCase { public void test_true() throws Exception { WallProvider provider = new MySqlWallProvider(); provider.getConfig().setSelectHavingAlwayTrueCheck(true); assertTrue(provider.checkValid(// "select login('', '', 'guest', '47ea3937793101011caaa5dd88d3bcae926526624796b8a26a9615e8d3bea6b4', 'iPad3,4', 'unknown'), '', (select max(num) from accounts) + @@auto_increment_increment")); assertEquals(1, provider.getTableStats().size()); assertTrue(provider.getTableStats().containsKey("accounts")); } }
MySqlWallTest89
java
elastic__elasticsearch
x-pack/plugin/autoscaling/src/main/java/org/elasticsearch/xpack/autoscaling/existence/FrozenExistenceDeciderService.java
{ "start": 3212, "end": 5319 }
class ____ implements AutoscalingDeciderResult.Reason { private final List<String> indices; public FrozenExistenceReason(List<String> indices) { this.indices = indices; } public FrozenExistenceReason(StreamInput in) throws IOException { this.indices = in.readStringCollectionAsList(); } @Override public String summary() { return "indices " + indices; } public List<String> indices() { return indices; } @Override public String getWriteableName() { return NAME; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeStringCollection(indices); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("indices", indices); builder.endObject(); return builder; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FrozenExistenceReason that = (FrozenExistenceReason) o; return indices.equals(that.indices); } @Override public int hashCode() { return Objects.hash(indices); } } // this is only here to support isFrozenPhase, TimeseriesLifecycleType.FROZEN_PHASE is the canonical source for this static String FROZEN_PHASE = "frozen"; // visible for testing /** * Return true if this index is in the frozen phase, false if not controlled by ILM or not in frozen. * @param indexMetadata the metadata of the index to retrieve phase from. * @return true if frozen phase, false otherwise. */ // visible for testing static boolean isFrozenPhase(IndexMetadata indexMetadata) { return FROZEN_PHASE.equals(indexMetadata.getLifecycleExecutionState().phase()); } }
FrozenExistenceReason
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/path/JSONPath_list_multi.java
{ "start": 194, "end": 1457 }
class ____ extends TestCase { List list = new ArrayList(); public JSONPath_list_multi(){ list.add(new Object()); list.add(new Object()); list.add(new Object()); list.add(new Object()); list.add(new Object()); list.add(new Object()); list.add(new Object()); list.add(new Object()); list.add(new Object()); list.add(new Object()); } public void test_list_multi() throws Exception { List<Object> result = (List<Object>) new JSONPath("$[2,4,5,8,100]").eval(list); Assert.assertEquals(5, result.size()); Assert.assertSame(list.get(2), result.get(0)); Assert.assertSame(list.get(4), result.get(1)); Assert.assertSame(list.get(5), result.get(2)); Assert.assertSame(list.get(8), result.get(3)); Assert.assertNull(result.get(4)); } public void test_list_multi_negative() throws Exception { List<Object> result = (List<Object>) new JSONPath("$[-1,-2,-100]").eval(list); Assert.assertEquals(3, result.size()); Assert.assertSame(list.get(9), result.get(0)); Assert.assertSame(list.get(8), result.get(1)); Assert.assertNull(result.get(2)); } }
JSONPath_list_multi
java
apache__dubbo
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/IdleSensible.java
{ "start": 1190, "end": 1559 }
interface ____ { /** * Whether the implementation can sense and handle the idle connection. By default, it's false, the implementation * relies on dedicated timer to take care of idle connection. * * @return whether it has the ability to handle idle connection */ default boolean canHandleIdle() { return false; } }
IdleSensible
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/tls/TlsServerWithP12Test.java
{ "start": 811, "end": 1660 }
class ____ { @TestHTTPResource(value = "/tls", tls = true) URL url; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(MyBean.class) .addAsResource(new File("target/certs/ssl-test-keystore.p12"), "server-keystore.pkcs12")) .overrideConfigKey("quarkus.tls.key-store.p12.path", "server-keystore.pkcs12") .overrideConfigKey("quarkus.tls.key-store.p12.password", "secret"); @Test public void testSslServerWithPkcs12() { RestAssured .given() .trustStore(new File("target/certs/ssl-test-truststore.jks"), "secret") .get(url).then().statusCode(200).body(is("ssl")); } @ApplicationScoped static
TlsServerWithP12Test
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelExceptionTests.java
{ "start": 1261, "end": 4942 }
class ____ { @Test void spelExpressionMapNullVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aMap.containsKey('one')"); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( spelExpression::getValue); } @Test void spelExpressionMapIndexAccessNullVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aMap['one'] eq 1"); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( spelExpression::getValue); } @Test @SuppressWarnings("serial") public void spelExpressionMapWithVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aMap['one'] eq 1"); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariables(new HashMap<>() { { put("aMap", new HashMap<String, Integer>() { { put("one", 1); put("two", 2); put("three", 3); } }); } }); boolean result = spelExpression.getValue(ctx, Boolean.class); assertThat(result).isTrue(); } @Test void spelExpressionListNullVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aList.contains('one')"); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( spelExpression::getValue); } @Test void spelExpressionListIndexAccessNullVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aList[0] eq 'one'"); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( spelExpression::getValue); } @Test @SuppressWarnings("serial") public void spelExpressionListWithVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aList.contains('one')"); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariables(new HashMap<>() { { put("aList", new ArrayList<String>() { { add("one"); add("two"); add("three"); } }); } }); boolean result = spelExpression.getValue(ctx, Boolean.class); assertThat(result).isTrue(); } @Test @SuppressWarnings("serial") public void spelExpressionListIndexAccessWithVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#aList[0] eq 'one'"); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariables(new HashMap<>() { { put("aList", new ArrayList<String>() { { add("one"); add("two"); add("three"); } }); } }); boolean result = spelExpression.getValue(ctx, Boolean.class); assertThat(result).isTrue(); } @Test void spelExpressionArrayIndexAccessNullVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#anArray[0] eq 1"); assertThatExceptionOfType(SpelEvaluationException.class).isThrownBy( spelExpression::getValue); } @Test @SuppressWarnings("serial") public void spelExpressionArrayWithVariables() { ExpressionParser parser = new SpelExpressionParser(); Expression spelExpression = parser.parseExpression("#anArray[0] eq 1"); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariables(new HashMap<>() { { put("anArray", new int[] {1,2,3}); } }); boolean result = spelExpression.getValue(ctx, Boolean.class); assertThat(result).isTrue(); } }
SpelExceptionTests
java
apache__flink
flink-end-to-end-tests/flink-parent-child-classloading-test-program/src/main/java/org/apache/flink/streaming/tests/ClassLoaderTestProgram.java
{ "start": 1635, "end": 4854 }
class ____ { public static void main(String[] args) throws Exception { final ParameterTool params = ParameterTool.fromArgs(args); final StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(); env.fromData("Hello") .map( (MapFunction<String, String>) value -> { String messageFromPropsFile; try (InputStream propFile = ClassLoaderTestProgram.class .getClassLoader() .getResourceAsStream( "parent-child-test.properties")) { Properties properties = new Properties(); properties.load(propFile); messageFromPropsFile = properties.getProperty("message"); } // Enumerate all properties files we can find and store the // messages in the // order we find them. The order will be different between // parent-first and // child-first classloader mode. Enumeration<URL> resources = ClassLoaderTestProgram.class .getClassLoader() .getResources("parent-child-test.properties"); StringBuilder orderedProperties = new StringBuilder(); while (resources.hasMoreElements()) { URL url = resources.nextElement(); try (InputStream in = url.openStream()) { Properties properties = new Properties(); properties.load(in); String messageFromEnumeratedPropsFile = properties.getProperty("message"); orderedProperties.append( messageFromEnumeratedPropsFile); } } String message = ParentChildTestingVehicle.getMessage(); return message + ":" + messageFromPropsFile + ":" + orderedProperties; }) .sinkTo(new DiscardingSink<>()); env.execute("ClassLoader Test Program"); } }
ClassLoaderTestProgram
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/client/UnknownContentTypeException.java
{ "start": 1121, "end": 4258 }
class ____ extends RestClientException { private static final long serialVersionUID = 2759516676367274084L; private final transient Type targetType; private final MediaType contentType; private final HttpStatusCode statusCode; private final String statusText; private final byte[] responseBody; private final HttpHeaders responseHeaders; /** * Construct a new instance of with the given response data. * @param targetType the expected target type * @param contentType the content type of the response * @param statusCode the raw status code value * @param statusText the status text * @param responseHeaders the response headers (may be {@code null}) * @param responseBody the response body content (may be {@code null}) */ public UnknownContentTypeException(Type targetType, MediaType contentType, int statusCode, String statusText, HttpHeaders responseHeaders, byte[] responseBody) { this(targetType, contentType, HttpStatusCode.valueOf(statusCode), statusText, responseHeaders, responseBody); } /** * Construct a new instance of with the given response data. * @param targetType the expected target type * @param contentType the content type of the response * @param statusCode the raw status code value * @param statusText the status text * @param responseHeaders the response headers (may be {@code null}) * @param responseBody the response body content (may be {@code null}) * @since 6.0 */ public UnknownContentTypeException(Type targetType, MediaType contentType, HttpStatusCode statusCode, String statusText, HttpHeaders responseHeaders, byte[] responseBody) { super("Could not extract response: no suitable HttpMessageConverter found " + "for response type [" + targetType + "] and content type [" + contentType + "]"); this.targetType = targetType; this.contentType = contentType; this.statusCode = statusCode; this.statusText = statusText; this.responseHeaders = responseHeaders; this.responseBody = responseBody; } /** * Return the target type expected for the response. */ public Type getTargetType() { return this.targetType; } /** * Return the content type of the response, or "application/octet-stream". */ public MediaType getContentType() { return this.contentType; } /** * Return the HTTP status code value. */ public HttpStatusCode getStatusCode() { return this.statusCode; } /** * Return the HTTP status text. */ public String getStatusText() { return this.statusText; } /** * Return the HTTP response headers. */ public @Nullable HttpHeaders getResponseHeaders() { return this.responseHeaders; } /** * Return the response body as a byte array. */ public byte[] getResponseBody() { return this.responseBody; } /** * Return the response body converted to String using the charset from the * response "Content-Type" or {@code "UTF-8"} otherwise. */ public String getResponseBodyAsString() { return new String(this.responseBody, this.contentType.getCharset() != null ? this.contentType.getCharset() : StandardCharsets.UTF_8); } }
UnknownContentTypeException
java
apache__dubbo
dubbo-cluster/src/test/java/org/apache/dubbo/rpc/cluster/configurator/parser/ConfigParserTest.java
{ "start": 1771, "end": 12872 }
class ____ { private String streamToString(InputStream stream) throws IOException { byte[] bytes = new byte[stream.available()]; stream.read(bytes); return new String(bytes); } @Test void snakeYamlBasicTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml")) { Yaml yaml = new Yaml(new SafeConstructor(new LoaderOptions())); Map<String, Object> map = yaml.load(yamlStream); ConfiguratorConfig config = ConfiguratorConfig.parseFromMap(map); Assertions.assertNotNull(config); } } @Test void parseConfiguratorsServiceNoAppTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoApp.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(2, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1:20880", url.getAddress()); Assertions.assertEquals(222, url.getParameter(WEIGHT_KEY, 0)); } } @Test void parseConfiguratorsServiceGroupVersionTest() throws Exception { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceGroupVersion.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("testgroup", url.getGroup()); Assertions.assertEquals("1.0.0", url.getVersion()); } } @Test void parseConfiguratorsServiceMultiAppsTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceMultiApps.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(4, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertNotNull(url.getApplication()); } } @Test void parseConfiguratorsServiceNoRuleTest() { Assertions.assertThrows(IllegalStateException.class, () -> { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ServiceNoRule.yml")) { ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.fail(); } }); } @Test void parseConfiguratorsAppMultiServicesTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppMultiServices.yml")) { String yamlFile = streamToString(yamlStream); List<URL> urls = ConfigParser.parseConfigurators(yamlFile); Assertions.assertNotNull(urls); Assertions.assertEquals(4, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("service1", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals("demo-consumer", url.getApplication()); } } @Test void parseConfiguratorsAppAnyServicesTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppAnyServices.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(2, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals("demo-consumer", url.getApplication()); } } @Test void parseConfiguratorsAppNoServiceTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/AppNoService.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals("demo-consumer", url.getApplication()); } } @Test void parseConsumerSpecificProvidersTest() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConsumerSpecificProviders.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("127.0.0.1", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); Assertions.assertEquals("random", url.getParameter(LOADBALANCE_KEY)); Assertions.assertEquals("127.0.0.1:20880", url.getParameter(OVERRIDE_PROVIDERS_KEY)); Assertions.assertEquals("demo-consumer", url.getApplication()); } } @Test void parseProviderConfigurationV3() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConfiguratorV3.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("0.0.0.0", url.getAddress()); Assertions.assertEquals("*", url.getServiceInterface()); Assertions.assertEquals(200, url.getParameter(WEIGHT_KEY, 0)); Assertions.assertEquals("demo-provider", url.getApplication()); URL matchURL1 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1"); URL matchURL2 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService2?match_key1=value1"); URL notMatchURL1 = URL.valueOf("dubbo://10.0.0.2:20880/DemoService?match_key1=value1"); // address not match URL notMatchURL2 = URL.valueOf("dubbo://10.0.0.1:20880/DemoServiceNotMatch?match_key1=value1"); // service not match URL notMatchURL3 = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION); Assertions.assertTrue(matcher.isMatch(matchURL1.getAddress(), matchURL1)); Assertions.assertTrue(matcher.isMatch(matchURL2.getAddress(), matchURL2)); Assertions.assertFalse(matcher.isMatch(notMatchURL1.getAddress(), notMatchURL1)); Assertions.assertFalse(matcher.isMatch(notMatchURL2.getAddress(), notMatchURL2)); Assertions.assertFalse(matcher.isMatch(notMatchURL3.getAddress(), notMatchURL3)); } } @Test void parseProviderConfigurationV3Compatibility() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConfiguratorV3Compatibility.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("10.0.0.1:20880", url.getAddress()); Assertions.assertEquals("DemoService", url.getServiceInterface()); Assertions.assertEquals(200, url.getParameter(WEIGHT_KEY, 0)); Assertions.assertEquals("demo-provider", url.getApplication()); URL matchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1"); URL notMatchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION); Assertions.assertTrue(matcher.isMatch(matchURL.getAddress(), matchURL)); Assertions.assertFalse(matcher.isMatch(notMatchURL.getAddress(), notMatchURL)); } } @Test void parseProviderConfigurationV3Conflict() throws IOException { try (InputStream yamlStream = this.getClass().getResourceAsStream("/ConfiguratorV3Duplicate.yml")) { List<URL> urls = ConfigParser.parseConfigurators(streamToString(yamlStream)); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("10.0.0.1:20880", url.getAddress()); Assertions.assertEquals("DemoService", url.getServiceInterface()); Assertions.assertEquals(200, url.getParameter(WEIGHT_KEY, 0)); Assertions.assertEquals("demo-provider", url.getApplication()); URL matchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value1"); URL notMatchURL = URL.valueOf("dubbo://10.0.0.1:20880/DemoService?match_key1=value_not_match"); // key not match ConditionMatch matcher = (ConditionMatch) url.getAttribute(MATCH_CONDITION); Assertions.assertTrue(matcher.isMatch(matchURL.getAddress(), matchURL)); Assertions.assertFalse(matcher.isMatch(notMatchURL.getAddress(), notMatchURL)); } } @Test void parseURLJsonArrayCompatible() { String configData = "[\"override://0.0.0.0/com.xx.Service?category=configurators&timeout=6666&disabled=true&dynamic=false&enabled=true&group=dubbo&priority=1&version=1.0\" ]"; List<URL> urls = ConfigParser.parseConfigurators(configData); Assertions.assertNotNull(urls); Assertions.assertEquals(1, urls.size()); URL url = urls.get(0); Assertions.assertEquals("0.0.0.0", url.getAddress()); Assertions.assertEquals("com.xx.Service", url.getServiceInterface()); Assertions.assertEquals(6666, url.getParameter(TIMEOUT_KEY, 0)); } }
ConfigParserTest
java
netty__netty
transport/src/test/java/io/netty/channel/SingleThreadIoEventLoopTest.java
{ "start": 1138, "end": 1219 }
class ____ { @Test void testIsIoType() {
SingleThreadIoEventLoopTest
java
dropwizard__dropwizard
dropwizard-json-logging/src/test/java/io/dropwizard/logging/json/layout/TimestampFormatterTest.java
{ "start": 165, "end": 1097 }
class ____ { private final long timestamp = 1513956631000L; @Test void testFormatTimestampAsString() { TimestampFormatter timestampFormatter = new TimestampFormatter("yyyy-MM-dd'T'HH:mm:ss.SSSZ", ZoneId.of("GMT+01:00")); assertThat(timestampFormatter.format(timestamp)).isEqualTo("2017-12-22T16:30:31.000+0100"); } @Test void testFormatTimestampFromPredefinedFormat() { TimestampFormatter timestampFormatter = new TimestampFormatter("RFC_1123_DATE_TIME", ZoneId.of("GMT+01:00")); assertThat(timestampFormatter.format(timestamp)).isEqualTo("Fri, 22 Dec 2017 16:30:31 +0100"); } @Test void testDoNotFormatTimestamp() { TimestampFormatter timestampFormatter = new TimestampFormatter(null, ZoneId.of("GMT+01:00")); assertThat(timestampFormatter.format(timestamp)).isEqualTo(timestamp); } }
TimestampFormatterTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/annotations/NamedNativeQuery.java
{ "start": 1124, "end": 5131 }
interface ____ { /** * The name of this query. Must be unique within a persistence unit. * * @see org.hibernate.SessionFactory#addNamedQuery * @see org.hibernate.Session#createNamedQuery */ String name(); /** * The text of the SQL query. */ String query(); /** * The resulting {@code Class}. * <p> * Should not be used in conjunction with {@link #resultSetMapping()} */ Class<?> resultClass() default void.class; /** * The name of a {@link jakarta.persistence.SqlResultSetMapping}. * <p> * Should not be used in conjunction with {@link #resultClass()}. */ String resultSetMapping() default ""; /** * Determines whether the session should be flushed before * executing the query. * * @see org.hibernate.query.CommonQueryContract#setQueryFlushMode(QueryFlushMode) * * @since 7.0 */ QueryFlushMode flush() default QueryFlushMode.DEFAULT; /** * The flush mode for the query. * * @see org.hibernate.query.CommonQueryContract#setFlushMode(jakarta.persistence.FlushModeType) * @see org.hibernate.jpa.HibernateHints#HINT_FLUSH_MODE * * @deprecated use {@link #flush()} */ @Deprecated(since = "7", forRemoval = true) FlushModeType flushMode() default FlushModeType.PERSISTENCE_CONTEXT; /** * Whether the query results are cacheable. * Default is {@code false}, that is, not cacheable. * * @see org.hibernate.query.SelectionQuery#setCacheable(boolean) * @see org.hibernate.jpa.HibernateHints#HINT_CACHEABLE */ boolean cacheable() default false; /** * If the query results are cacheable, the name of the query cache region. * * @see org.hibernate.query.SelectionQuery#setCacheRegion(String) * @see org.hibernate.jpa.HibernateHints#HINT_CACHE_REGION */ String cacheRegion() default ""; /** * The number of rows fetched by the JDBC driver per trip. * * @see org.hibernate.query.SelectionQuery#setFetchSize(int) * @see org.hibernate.jpa.HibernateHints#HINT_FETCH_SIZE */ int fetchSize() default -1; /** * The query timeout in seconds. * Default is no timeout. * * @see org.hibernate.query.CommonQueryContract#setTimeout(int) * @see org.hibernate.jpa.HibernateHints#HINT_TIMEOUT * @see org.hibernate.jpa.SpecHints#HINT_SPEC_QUERY_TIMEOUT */ int timeout() default -1; /** * A comment added to the SQL query. * Useful when engaging with DBA. * * @see org.hibernate.query.CommonQueryContract#setComment(String) * @see org.hibernate.jpa.HibernateHints#HINT_COMMENT */ String comment() default ""; /** * The cache storage mode for objects returned by this query. * * @see org.hibernate.query.Query#setCacheMode(CacheMode) * @see org.hibernate.jpa.SpecHints#HINT_SPEC_CACHE_STORE_MODE * * @since 6.2 */ CacheStoreMode cacheStoreMode() default CacheStoreMode.USE; /** * The cache retrieval mode for objects returned by this query. * * @see org.hibernate.query.Query#setCacheMode(CacheMode) * @see org.hibernate.jpa.SpecHints#HINT_SPEC_CACHE_RETRIEVE_MODE * * @since 6.2 */ CacheRetrieveMode cacheRetrieveMode() default CacheRetrieveMode.USE; /** * The cache interaction mode for this query. * * @see org.hibernate.query.SelectionQuery#setCacheMode(CacheMode) * @see org.hibernate.jpa.HibernateHints#HINT_CACHE_MODE */ CacheMode cacheMode() default CacheMode.NORMAL; /** * Whether the results should be loaded in read-only mode. * Default is {@code false}. * * @see org.hibernate.query.SelectionQuery#setReadOnly(boolean) * @see org.hibernate.jpa.HibernateHints#HINT_READ_ONLY */ boolean readOnly() default false; /** * The {@linkplain org.hibernate.query.SynchronizeableQuery query spaces} * involved in this query. * <p> * Typically, the names of tables which are referenced by the query. * * @see org.hibernate.query.SynchronizeableQuery#addSynchronizedQuerySpace * @see org.hibernate.jpa.HibernateHints#HINT_NATIVE_SPACES * @see Synchronize */ String[] querySpaces() default {}; }
NamedNativeQuery
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/config/arbiters/DefaultArbiter.java
{ "start": 1592, "end": 1851 }
class ____ implements org.apache.logging.log4j.core.util.Builder<DefaultArbiter> { public Builder asBuilder() { return this; } public DefaultArbiter build() { return new DefaultArbiter(); } } }
Builder
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/UserEntity.java
{ "start": 575, "end": 1246 }
class ____ implements Serializable{ private static final long serialVersionUID = 1L; @Id @GeneratedValue @Column(name = "user_id") private Long id; @OneToMany(mappedBy="user", fetch = EAGER, cascade = ALL, orphanRemoval = true) private Set<UserConfEntity> confs = new HashSet<UserConfEntity>(); private String name; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Set<UserConfEntity> getConfs() { return confs; } public void setConfs(Set<UserConfEntity> confs) { this.confs = confs; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
UserEntity
java
google__guava
android/guava-testlib/src/com/google/common/collect/testing/google/ListMultimapTestSuiteBuilder.java
{ "start": 2159, "end": 4621 }
class ____ @Override protected List<Class<? extends AbstractTester>> getTesters() { List<Class<? extends AbstractTester>> testers = copyToList(super.getTesters()); testers.add(ListMultimapAsMapTester.class); testers.add(ListMultimapEqualsTester.class); testers.add(ListMultimapPutTester.class); testers.add(ListMultimapPutAllTester.class); testers.add(ListMultimapRemoveTester.class); testers.add(ListMultimapReplaceValuesTester.class); return testers; } @Override TestSuite computeMultimapGetTestSuite( FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<ListMultimap<K, V>, Entry<K, V>>> parentBuilder) { return ListTestSuiteBuilder.using( new MultimapGetGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(computeMultimapGetFeatures(parentBuilder.getFeatures())) .named(parentBuilder.getName() + ".get[key]") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite(); } @Override TestSuite computeMultimapAsMapGetTestSuite( FeatureSpecificTestSuiteBuilder< ?, ? extends OneSizeTestContainerGenerator<ListMultimap<K, V>, Entry<K, V>>> parentBuilder) { Set<Feature<?>> features = computeMultimapAsMapGetFeatures(parentBuilder.getFeatures()); if (Collections.disjoint(features, EnumSet.allOf(CollectionSize.class))) { return new TestSuite(); } else { return ListTestSuiteBuilder.using( new MultimapAsMapGetGenerator<K, V>(parentBuilder.getSubjectGenerator())) .withFeatures(features) .named(parentBuilder.getName() + ".asMap[].get[key]") .suppressing(parentBuilder.getSuppressedTests()) .createTestSuite(); } } @Override Set<Feature<?>> computeMultimapGetFeatures(Set<Feature<?>> multimapFeatures) { Set<Feature<?>> derivedFeatures = super.computeMultimapGetFeatures(multimapFeatures); if (derivedFeatures.contains(CollectionFeature.SUPPORTS_ADD)) { derivedFeatures.add(ListFeature.SUPPORTS_ADD_WITH_INDEX); } if (derivedFeatures.contains(CollectionFeature.SUPPORTS_REMOVE)) { derivedFeatures.add(ListFeature.SUPPORTS_REMOVE_WITH_INDEX); } if (derivedFeatures.contains(CollectionFeature.GENERAL_PURPOSE)) { derivedFeatures.add(ListFeature.GENERAL_PURPOSE); } return derivedFeatures; } private static final
literals
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/sql/internal/NamedNativeOrdinalEnumDdlTypeImpl.java
{ "start": 815, "end": 1508 }
class ____ implements DdlType { private final Dialect dialect; public NamedNativeOrdinalEnumDdlTypeImpl(Dialect dialect) { this.dialect = dialect; } @Override public int getSqlTypeCode() { return NAMED_ORDINAL_ENUM; } @Override @SuppressWarnings("unchecked") public String getTypeName(Size columnSize, Type type, DdlTypeRegistry ddlTypeRegistry) { return dialect.getEnumTypeDeclaration( (Class<? extends Enum<?>>) type.getReturnedClass() ); } @Override public String getRawTypeName() { return "enum"; } @Override public String getTypeName(Long size, Integer precision, Integer scale) { throw new UnsupportedOperationException( "native
NamedNativeOrdinalEnumDdlTypeImpl
java
apache__camel
components/camel-caffeine/src/generated/java/org/apache/camel/component/caffeine/load/CaffeineLoadCacheProducerInvokeOnHeaderFactory.java
{ "start": 419, "end": 1680 }
class ____ implements InvokeOnHeaderStrategy { @Override public Object invoke(Object obj, String key, Exchange exchange, AsyncCallback callback) throws Exception { org.apache.camel.component.caffeine.load.CaffeineLoadCacheProducer target = (org.apache.camel.component.caffeine.load.CaffeineLoadCacheProducer) obj; switch (key) { case "as_map": case "AS_MAP": target.onAsMap(exchange.getMessage()); return null; case "cleanup": case "CLEANUP": target.onCleanUp(exchange.getMessage()); return null; case "get": case "GET": target.onGet(exchange.getMessage()); return null; case "get_all": case "GET_ALL": target.onGetAll(exchange.getMessage()); return null; case "invalidate": case "INVALIDATE": target.onInvalidate(exchange.getMessage()); return null; case "invalidate_all": case "INVALIDATE_ALL": target.onInvalidateAll(exchange.getMessage()); return null; case "put": case "PUT": target.onPut(exchange.getMessage()); return null; case "put_all": case "PUT_ALL": target.onPutAll(exchange.getMessage()); return null; default: return null; } } }
CaffeineLoadCacheProducerInvokeOnHeaderFactory
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/ast/tree/from/VirtualTableGroup.java
{ "start": 280, "end": 431 }
interface ____ extends TableGroup { TableGroup getUnderlyingTableGroup(); @Override default boolean isVirtual() { return true; } }
VirtualTableGroup
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/index/mapper/RoutingPathFieldsTests.java
{ "start": 868, "end": 4039 }
class ____ extends ESTestCase { public void testWithBuilder() throws Exception { IndexSettings settings = new IndexSettings( IndexMetadata.builder("test") .settings( indexSettings(IndexVersion.current(), 1, 1).put( Settings.builder().put("index.mode", "time_series").put("index.routing_path", "path.*").build() ) ) .build(), Settings.EMPTY ); IndexRouting.ExtractFromSource.ForRoutingPath routing = (IndexRouting.ExtractFromSource.ForRoutingPath) settings.getIndexRouting(); var routingPathFields = new RoutingPathFields(routing.builder()); BytesReference current, previous; routingPathFields.addString("path.string_name", randomAlphaOfLengthBetween(1, 10)); current = previous = routingPathFields.buildHash(); assertNotNull(current); routingPathFields.addBoolean("path.boolean_name", randomBoolean()); current = routingPathFields.buildHash(); assertTrue(current.length() > previous.length()); previous = current; routingPathFields.addLong("path.long_name", randomLong()); current = routingPathFields.buildHash(); assertTrue(current.length() > previous.length()); previous = current; routingPathFields.addIp("path.ip_name", randomIp(randomBoolean())); current = routingPathFields.buildHash(); assertTrue(current.length() > previous.length()); previous = current; routingPathFields.addUnsignedLong("path.unsigned_long_name", randomLongBetween(0, Long.MAX_VALUE)); current = routingPathFields.buildHash(); assertTrue(current.length() > previous.length()); assertArrayEquals(current.array(), routingPathFields.buildHash().array()); } public void testWithoutBuilder() throws Exception { var routingPathFields = new RoutingPathFields(null); BytesReference current, previous; routingPathFields.addString("path.string_name", randomAlphaOfLengthBetween(1, 10)); current = previous = routingPathFields.buildHash(); assertNotNull(current); routingPathFields.addBoolean("path.boolean_name", randomBoolean()); current = routingPathFields.buildHash(); assertTrue(current.length() > previous.length()); previous = current; routingPathFields.addLong("path.long_name", randomLong()); current = routingPathFields.buildHash(); assertTrue(current.length() > previous.length()); previous = current; routingPathFields.addIp("path.ip_name", randomIp(randomBoolean())); current = routingPathFields.buildHash(); assertTrue(current.length() > previous.length()); previous = current; routingPathFields.addUnsignedLong("path.unsigned_long_name", randomLongBetween(0, Long.MAX_VALUE)); current = routingPathFields.buildHash(); assertTrue(current.length() > previous.length()); assertArrayEquals(current.array(), routingPathFields.buildHash().array()); } }
RoutingPathFieldsTests
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ext/javatime/deser/key/ZonedDateTimeKeyDeserializer.java
{ "start": 231, "end": 886 }
class ____ extends Jsr310KeyDeserializer { public static final ZonedDateTimeKeyDeserializer INSTANCE = new ZonedDateTimeKeyDeserializer(); protected ZonedDateTimeKeyDeserializer() { // singleton } @Override protected ZonedDateTime deserialize(String key, DeserializationContext ctxt) throws JacksonException { try { // Not supplying a formatter allows the use of all supported formats return ZonedDateTime.parse(key); } catch (DateTimeException e) { return _handleDateTimeException(ctxt, ZonedDateTime.class, e, key); } } }
ZonedDateTimeKeyDeserializer
java
quarkusio__quarkus
extensions/netty/runtime/src/main/java/io/quarkus/netty/runtime/graal/NettySubstitutions.java
{ "start": 26161, "end": 26483 }
class ____ implements BooleanSupplier { @Override public boolean getAsBoolean() { try { NettySubstitutions.class.getClassLoader().loadClass("org.bouncycastle.openssl.PEMParser"); return false; } catch (Exception e) { return true; } } }
IsBouncyNotThere
java
apache__maven
its/core-it-suite/src/test/resources/mng-2289/issue/src/main/java/mng/Issue2289.java
{ "start": 863, "end": 1030 }
class ____ { public static void main(final String[] args) { TestCase tc = new TestCase("Dummy") {}; System.exit(tc == null ? -1 : 0); } }
Issue2289
java
spring-projects__spring-boot
module/spring-boot-jackson2/src/main/java/org/springframework/boot/jackson2/JsonMixinModuleEntries.java
{ "start": 4322, "end": 4903 }
class ____ */ public void doWithEntry(@Nullable ClassLoader classLoader, BiConsumer<Class<?>, Class<?>> action) { this.entries.forEach((type, mixin) -> action.accept(resolveClassNameIfNecessary(type, classLoader), resolveClassNameIfNecessary(mixin, classLoader))); } private Class<?> resolveClassNameIfNecessary(Object nameOrType, @Nullable ClassLoader classLoader) { return (nameOrType instanceof Class<?> type) ? type : ClassUtils.resolveClassName((String) nameOrType, classLoader); } /** * Builder for {@link JsonMixinModuleEntries}. */ public static
entry
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/constructor/visibility/SimpleWithPublicParameterlessConstructorAndDefaultAnnotatedMapper.java
{ "start": 422, "end": 721 }
interface ____ { SimpleWithPublicParameterlessConstructorAndDefaultAnnotatedMapper INSTANCE = Mappers.getMapper( SimpleWithPublicParameterlessConstructorAndDefaultAnnotatedMapper.class ); Person map(PersonDto dto);
SimpleWithPublicParameterlessConstructorAndDefaultAnnotatedMapper
java
google__error-prone
core/src/test/java/com/google/errorprone/refaster/UEnhancedForLoopTest.java
{ "start": 967, "end": 2426 }
class ____ { @Test public void equality() { new EqualsTester() .addEqualityGroup( UEnhancedForLoop.create( UVariableDecl.create("c", UPrimitiveTypeTree.CHAR, null), UMethodInvocation.create( UMemberSelect.create( ULiteral.stringLit("foo"), "toCharArray", UMethodType.create(UArrayType.create(UPrimitiveType.CHAR)))), USkip.INSTANCE)) .addEqualityGroup( UEnhancedForLoop.create( UVariableDecl.create("c", UClassIdent.create("java.lang.Character"), null), UMethodInvocation.create( UMemberSelect.create( ULiteral.stringLit("foo"), "toCharArray", UMethodType.create(UArrayType.create(UPrimitiveType.CHAR)))), USkip.INSTANCE)) .testEquals(); } @Test public void serialization() { SerializableTester.reserializeAndAssert( UEnhancedForLoop.create( UVariableDecl.create("c", UPrimitiveTypeTree.CHAR, null), UMethodInvocation.create( UMemberSelect.create( ULiteral.stringLit("foo"), "toCharArray", UMethodType.create(UArrayType.create(UPrimitiveType.CHAR)))), USkip.INSTANCE)); } }
UEnhancedForLoopTest
java
apache__camel
components/camel-hl7/src/main/java/org/apache/camel/component/hl7/HL7.java
{ "start": 1274, "end": 2791 }
class ____ { private HL7() { // Helper class } public static ValueBuilder hl7terser(String expression) { return new ValueBuilder(new Hl7TerserExpression(expression)); } public static ValueBuilder ack() { return new ValueBuilder(new AckExpression()); } public static ValueBuilder ack(AcknowledgmentCode code) { return new ValueBuilder(new AckExpression(code)); } public static ValueBuilder convertLFToCR() { return new ValueBuilder(new ExpressionAdapter() { @Override public Object evaluate(Exchange exchange) { String s = exchange.getIn().getBody(String.class); return s != null ? s.replace('\n', '\r') : null; } }); } public static ValueBuilder ack(AcknowledgmentCode code, String errorMessage, ErrorCode errorCode) { return new ValueBuilder(new AckExpression(code, errorMessage, errorCode)); } public static Predicate messageConforms() { return new ValidationContextPredicate(); } public static Predicate messageConformsTo(HapiContext hapiContext) { return new ValidationContextPredicate(hapiContext); } public static Predicate messageConformsTo(ValidationContext validationContext) { return new ValidationContextPredicate(validationContext); } public static Predicate messageConformsTo(Expression expression) { return new ValidationContextPredicate(expression); } }
HL7
java
spring-projects__spring-data-jpa
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/JpqlDtoQueryTransformerUnitTests.java
{ "start": 932, "end": 1455 }
class ____ extends AbstractDtoQueryTransformerUnitTests<JpaQueryEnhancer.JpqlQueryParser> { @Override JpaQueryEnhancer.JpqlQueryParser parse(String query) { return JpaQueryEnhancer.JpqlQueryParser.parseQuery(query); } @Override ParseTreeVisitor<QueryTokenStream> getTransformer(JpaQueryEnhancer.JpqlQueryParser parser, QueryMethod method) { return new JpqlSortedQueryTransformer(Sort.unsorted(), parser.getQueryInformation(), method.getResultProcessor().getReturnedType()); } }
JpqlDtoQueryTransformerUnitTests
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/ReadTimeoutTestCase.java
{ "start": 527, "end": 2875 }
class ____ { @RegisterExtension static QuarkusUnitTest runner = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addAsResource(new StringAsset("quarkus.http.read-timeout=0.5S"), "application.properties") .addClasses(PostEndpoint.class)); @TestHTTPResource URL url; @Test public void testReadTimesOut() throws Exception { PostEndpoint.invoked = false; //make sure incomplete writes do not block threads //and that incomplete data is not delivered to the endpoint Socket socket = new Socket(url.getHost(), url.getPort()); socket.getOutputStream().write( "POST /post HTTP/1.1\r\nHost: localhost\r\nContent-length:9\r\n\r\n12345".getBytes(StandardCharsets.UTF_8)); socket.getOutputStream().flush(); Thread.sleep(1200); socket.getOutputStream().write( "6789".getBytes(StandardCharsets.UTF_8)); socket.getOutputStream().flush(); Thread.sleep(600); //make sure the read timed out and the endpoint was not invoked Assertions.assertFalse(PostEndpoint.invoked); socket.close(); } @Test public void testReadSuccess() throws Exception { PostEndpoint.invoked = false; //make sure incomplete writes do not block threads //and that incomplete data is not delivered to the endpoint Socket socket = new Socket(url.getHost(), url.getPort()); socket.getOutputStream().write( "POST /post HTTP/1.1\r\nHost: localhost\r\nContent-length:9\r\n\r\n12345".getBytes(StandardCharsets.UTF_8)); socket.getOutputStream().flush(); Thread.sleep(1); socket.getOutputStream().write( "6789".getBytes(StandardCharsets.UTF_8)); socket.getOutputStream().flush(); Awaitility.await().atMost(20, TimeUnit.SECONDS).pollInterval(50, TimeUnit.MILLISECONDS) .untilAsserted(new ThrowingRunnable() { @Override public void run() throws Throwable { //make sure the read timed out and the endpoint was invoked Assertions.assertTrue(PostEndpoint.invoked); } }); socket.close(); } }
ReadTimeoutTestCase
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/io/buffer/ByteBufferFactory.java
{ "start": 793, "end": 2889 }
interface ____<T, B> { /** * @return The native allocator */ T getNativeAllocator(); /** * Allocate a {@link ByteBuffer}. If it is a direct or heap buffer depends on the actual implementation. * * @return The buffer */ ByteBuffer<B> buffer(); /** * Allocate a {@link ByteBuffer} with the given initial capacity. If it is a direct or heap buffer depends on the * actual implementation. * * @param initialCapacity The initial capacity * @return the buffer */ ByteBuffer<B> buffer(int initialCapacity); /** * Allocate a {@link ByteBuffer} with the given initial capacity and the given maximal capacity. If it is a direct * or heap buffer depends on the actual implementation. * * @param initialCapacity The initial capacity * @param maxCapacity The maximum capacity * @return The buffer */ ByteBuffer<B> buffer(int initialCapacity, int maxCapacity); /** * Creates a new big-endian buffer whose content is a copy of the specified {@code array}'s sub-region. The new * buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and the specified {@code length} respectively. * * @param bytes The bytes * @return The buffer */ ByteBuffer<B> copiedBuffer(byte[] bytes); /** * Creates a new big-endian buffer whose content is a copy of the specified NIO buffer. The new buffer's * {@code readerIndex} and {@code writerIndex} are {@code 0} and the specified {@code length} respectively. * * @param nioBuffer The nioBuffer * @return The buffer */ ByteBuffer<B> copiedBuffer(java.nio.ByteBuffer nioBuffer); /** * Wrap an existing buffer. * * @param existing The buffer to wrap * @return The wrapped {@link ByteBuffer} */ ByteBuffer<B> wrap(B existing); /** * Wrap an existing buffer. * * @param existing The bytes to wrap * @return The wrapped {@link ByteBuffer} */ ByteBuffer<B> wrap(byte[] existing); }
ByteBufferFactory
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/issues/JmsGetHeaderKeyFormatIssueTest.java
{ "start": 1523, "end": 3822 }
class ____ extends AbstractJMSTest { @Order(2) @RegisterExtension public static CamelContextExtension camelContextExtension = new DefaultCamelContextExtension(); protected CamelContext context; protected ProducerTemplate template; protected ConsumerTemplate consumer; private final String uri = "activemq:queue:JmsGetHeaderKeyFormatIssueTest?jmsKeyFormatStrategy=default"; @Test public void testSendWithHeaders() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.message(0).body().isEqualTo("Hello World"); mock.message(0).header("HEADER_1").isEqualTo("VALUE_2"); template.sendBodyAndHeader(uri, "Hello World", "HEADER_1", "VALUE_1"); MockEndpoint.assertIsSatisfied(context); } @Override protected String getComponentName() { return "activemq"; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from(uri) .process(exchange -> { Map<String, Object> headers = exchange.getIn().getHeaders(); assertEquals("VALUE_1", headers.get("HEADER_1")); assertEquals("VALUE_1", exchange.getIn().getHeader("HEADER_1")); }) .setHeader("HEADER_1", constant("VALUE_2")) .process(exchange -> { Map<String, Object> headers = exchange.getIn().getHeaders(); assertEquals("VALUE_2", headers.get("HEADER_1")); assertEquals("VALUE_2", exchange.getIn().getHeader("HEADER_1")); }) .to("mock:result"); } }; } @Override public CamelContextExtension getCamelContextExtension() { return camelContextExtension; } @BeforeEach void setUpRequirements() { context = camelContextExtension.getContext(); template = camelContextExtension.getProducerTemplate(); consumer = camelContextExtension.getConsumerTemplate(); } }
JmsGetHeaderKeyFormatIssueTest
java
hibernate__hibernate-orm
tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/reactive/ReactiveTest.java
{ "start": 519, "end": 1555 }
class ____ { @Test @WithClasses({ Publisher.class, Author.class, Address.class, Book.class, Library.class, Library2.class, RepoWithPrimary.class }) void test() { System.out.println( getMetaModelSourceAsString( Author.class ) ); System.out.println( getMetaModelSourceAsString( Book.class ) ); System.out.println( getMetaModelSourceAsString( Author.class, true ) ); System.out.println( getMetaModelSourceAsString( Book.class, true ) ); System.out.println( getMetaModelSourceAsString( Library.class ) ); System.out.println( getMetaModelSourceAsString( Library2.class ) ); assertMetamodelClassGeneratedFor( Author.class, true ); assertMetamodelClassGeneratedFor( Book.class, true ); assertMetamodelClassGeneratedFor( Publisher.class, true ); assertMetamodelClassGeneratedFor( Author.class ); assertMetamodelClassGeneratedFor( Book.class ); assertMetamodelClassGeneratedFor( Publisher.class ); assertMetamodelClassGeneratedFor( Library.class ); assertMetamodelClassGeneratedFor( Library2.class ); } }
ReactiveTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/manytoone/ManyToOneMapsIdFlushModeTest.java
{ "start": 3090, "end": 3480 }
class ____ { @Id private Long id; @MapsId @ManyToOne(optional = false, targetEntity = ParentEntity.class) private ParentEntity parent; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public ParentEntity getParent() { return parent; } public void setParent(ParentEntity parent) { this.parent = parent; } } }
ChildEntity
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/metrics/utils/SystemResourcesCounterTest.java
{ "start": 1147, "end": 2816 }
class ____ { private static final double EPSILON = 0.01; @Test void testObtainAnyMetrics() throws InterruptedException { SystemResourcesCounter systemResources = new SystemResourcesCounter(Duration.ofMillis(10)); double initialCpuIdle = systemResources.getCpuIdle(); systemResources.start(); // wait for stats to update/calculate try { double cpuIdle; do { Thread.sleep(1); cpuIdle = systemResources.getCpuIdle(); } while (systemResources.isAlive() && (initialCpuIdle == cpuIdle || Double.isNaN(cpuIdle) || cpuIdle == 0.0)); } finally { systemResources.shutdown(); systemResources.join(); } double totalCpuUsage = systemResources.getCpuIrq() + systemResources.getCpuNice() + systemResources.getCpuSoftIrq() + systemResources.getCpuSys() + systemResources.getCpuUser() + systemResources.getIOWait() + systemResources.getCpuSteal(); assertThat(systemResources.getProcessorsCount()) .withFailMessage("There should be at least one processor") .isGreaterThan(0); assertThat(systemResources.getNetworkInterfaceNames().length) .withFailMessage("There should be at least one network interface") .isGreaterThan(0); assertThat(totalCpuUsage + systemResources.getCpuIdle()).isCloseTo(100.0, within(EPSILON)); } }
SystemResourcesCounterTest
java
apache__camel
components/camel-aws/camel-aws2-timestream/src/main/java/org/apache/camel/component/aws2/timestream/client/impl/Timestream2ClientStandardImpl.java
{ "start": 2110, "end": 7824 }
class ____ implements Timestream2InternalClient { private static final Logger LOG = LoggerFactory.getLogger(Timestream2ClientStandardImpl.class); private Timestream2Configuration configuration; /** * Constructor that uses the config file. */ public Timestream2ClientStandardImpl(Timestream2Configuration configuration) { LOG.trace("Creating an AWS Timestream manager using static credentials."); this.configuration = configuration; } /** * Getting the TimestreamWrite AWS client that is used. * * @return Amazon TimestreamWrite Client. */ @Override public TimestreamWriteClient getTimestreamWriteClient() { TimestreamWriteClient client = null; TimestreamWriteClientBuilder clientBuilder = TimestreamWriteClient.builder(); ProxyConfiguration.Builder proxyConfig = null; ApacheHttpClient.Builder httpClientBuilder = null; boolean isClientConfigFound = false; if (ObjectHelper.isNotEmpty(configuration.getProxyHost()) && ObjectHelper.isNotEmpty(configuration.getProxyPort())) { proxyConfig = ProxyConfiguration.builder(); URI proxyEndpoint = URI.create(configuration.getProxyProtocol() + "://" + configuration.getProxyHost() + ":" + configuration.getProxyPort()); proxyConfig.endpoint(proxyEndpoint); httpClientBuilder = ApacheHttpClient.builder().proxyConfiguration(proxyConfig.build()); isClientConfigFound = true; } if (configuration.getAccessKey() != null && configuration.getSecretKey() != null) { AwsBasicCredentials cred = AwsBasicCredentials.create(configuration.getAccessKey(), configuration.getSecretKey()); if (isClientConfigFound) { clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder) .credentialsProvider(StaticCredentialsProvider.create(cred)); } else { clientBuilder = clientBuilder.credentialsProvider(StaticCredentialsProvider.create(cred)); } } else { if (!isClientConfigFound) { clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder); } } if (ObjectHelper.isNotEmpty(configuration.getRegion())) { clientBuilder = clientBuilder.region(Region.of(configuration.getRegion())); } if (configuration.isOverrideEndpoint()) { clientBuilder.endpointOverride(URI.create(configuration.getUriEndpointOverride())); } if (configuration.isTrustAllCertificates()) { SdkHttpClient ahc = ApacheHttpClient.builder().buildWithDefaults(AttributeMap .builder() .put( SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, Boolean.TRUE) .build()); clientBuilder.httpClient(ahc); } client = clientBuilder.build(); return client; } /** * Getting the TimestreamQuery AWS client that is used. * * @return Amazon TimestreamQuery Client. */ @Override public TimestreamQueryClient getTimestreamQueryClient() { TimestreamQueryClient client = null; TimestreamQueryClientBuilder clientBuilder = TimestreamQueryClient.builder(); ProxyConfiguration.Builder proxyConfig = null; ApacheHttpClient.Builder httpClientBuilder = null; boolean isClientConfigFound = false; if (ObjectHelper.isNotEmpty(configuration.getProxyHost()) && ObjectHelper.isNotEmpty(configuration.getProxyPort())) { proxyConfig = ProxyConfiguration.builder(); URI proxyEndpoint = URI.create(configuration.getProxyProtocol() + "://" + configuration.getProxyHost() + ":" + configuration.getProxyPort()); proxyConfig.endpoint(proxyEndpoint); httpClientBuilder = ApacheHttpClient.builder().proxyConfiguration(proxyConfig.build()); isClientConfigFound = true; } if (configuration.getAccessKey() != null && configuration.getSecretKey() != null) { AwsBasicCredentials cred = AwsBasicCredentials.create(configuration.getAccessKey(), configuration.getSecretKey()); if (isClientConfigFound) { clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder) .credentialsProvider(StaticCredentialsProvider.create(cred)); } else { clientBuilder = clientBuilder.credentialsProvider(StaticCredentialsProvider.create(cred)); } } else { if (!isClientConfigFound) { clientBuilder = clientBuilder.httpClientBuilder(httpClientBuilder); } } if (ObjectHelper.isNotEmpty(configuration.getRegion())) { clientBuilder = clientBuilder.region(Region.of(configuration.getRegion())); } if (configuration.isOverrideEndpoint()) { clientBuilder.endpointOverride(URI.create(configuration.getUriEndpointOverride())); } if (configuration.isTrustAllCertificates()) { SdkHttpClient ahc = ApacheHttpClient.builder().buildWithDefaults(AttributeMap .builder() .put( SdkHttpConfigurationOption.TRUST_ALL_CERTIFICATES, Boolean.TRUE) .build()); clientBuilder.httpClient(ahc); } client = clientBuilder.build(); return client; } }
Timestream2ClientStandardImpl
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/mistral/MistralUnifiedChatCompletionResponseHandlerTests.java
{ "start": 1314, "end": 6171 }
class ____ extends ESTestCase { private final MistralUnifiedChatCompletionResponseHandler responseHandler = new MistralUnifiedChatCompletionResponseHandler( "chat completions", (a, b) -> mock() ); public void testFailNotFound() throws IOException { var responseJson = XContentHelper.stripWhitespace(""" { "detail": "Not Found" } """); var errorJson = invalidResponseJson(responseJson, 404); assertThat(errorJson, is(XContentHelper.stripWhitespace(""" { "error" : { "code" : "not_found", "message" : "Resource not found at [https://api.mistral.ai/v1/chat/completions] for request from inference entity id [id] \ status [404]. Error message: [{\\"detail\\":\\"Not Found\\"}]", "type" : "mistral_error" } }"""))); } public void testFailUnauthorized() throws IOException { var responseJson = XContentHelper.stripWhitespace(""" { "message": "Unauthorized", "request_id": "a580d263fb1521778782b22104efb415" } """); var errorJson = invalidResponseJson(responseJson, 401); assertThat(errorJson, is(XContentHelper.stripWhitespace(""" { "error" : { "code" : "unauthorized", "message" : "Received an authentication error status code for request from inference entity id [id] status [401]. Error \ message: [{\\"message\\":\\"Unauthorized\\",\\"request_id\\":\\"a580d263fb1521778782b22104efb415\\"}]", "type" : "mistral_error" } }"""))); } public void testFailBadRequest() throws IOException { var responseJson = XContentHelper.stripWhitespace(""" { "object": "error", "message": "Invalid model: mistral-small-l2atest", "type": "invalid_model", "param": null, "code": "1500" } """); var errorJson = invalidResponseJson(responseJson, 400); assertThat(errorJson, is(XContentHelper.stripWhitespace(""" { "error" : { "code" : "bad_request", "message" : "Received a bad request status code for request from inference entity id [id] status [400]. Error message: \ [{\\"object\\":\\"error\\",\\"message\\":\\"Invalid model: mistral-small-l2atest\\",\\"type\\":\\"invalid_model\\",\\"par\ am\\":null,\\"code\\":\\"1500\\"}]", "type" : "mistral_error" } }"""))); } private String invalidResponseJson(String responseJson, int statusCode) throws IOException { var exception = invalidResponse(responseJson, statusCode); assertThat(exception, isA(RetryException.class)); assertThat(unwrapCause(exception), isA(UnifiedChatCompletionException.class)); return toJson((UnifiedChatCompletionException) unwrapCause(exception)); } private Exception invalidResponse(String responseJson, int statusCode) { return expectThrows( RetryException.class, () -> responseHandler.validateResponse( mock(), mock(), mockRequest(), new HttpResult(mockErrorResponse(statusCode), responseJson.getBytes(StandardCharsets.UTF_8)) ) ); } private static Request mockRequest() throws URISyntaxException { var request = mock(Request.class); when(request.getInferenceEntityId()).thenReturn("id"); when(request.isStreaming()).thenReturn(true); when(request.getURI()).thenReturn(new URI("https://api.mistral.ai/v1/chat/completions")); return request; } private static HttpResponse mockErrorResponse(int statusCode) { var statusLine = mock(StatusLine.class); when(statusLine.getStatusCode()).thenReturn(statusCode); var response = mock(HttpResponse.class); when(response.getStatusLine()).thenReturn(statusLine); return response; } private String toJson(UnifiedChatCompletionException e) throws IOException { try (var builder = XContentFactory.jsonBuilder()) { e.toXContentChunked(EMPTY_PARAMS).forEachRemaining(xContent -> { try { xContent.toXContent(builder, EMPTY_PARAMS); } catch (IOException ex) { throw new RuntimeException(ex); } }); return XContentHelper.convertToJson(BytesReference.bytes(builder), false, builder.contentType()); } } }
MistralUnifiedChatCompletionResponseHandlerTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java
{ "start": 106276, "end": 107409 }
class ____ { volatile int v = 0; public int foo(Suit suit) { int z = 3; int x = v; x = switch (suit) { case HEART, DIAMOND -> ((z + 1) * (z * z)) << 1; case SPADE -> throw new RuntimeException(); default -> throw new NullPointerException(); }; return x; } } """) .setArgs( "-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion", "-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion=false") .setFixChooser(StatementSwitchToExpressionSwitchTest::assertOneFixAndChoose) .doTest(TEXT_MATCH); } @Test public void switchByEnum_assignmentSwitchMixedReferences_error() { // Must deduce that "x" and "this.x" refer to same thing // Note that suggested fix uses the style of the first case (in source order). refactoringHelper .addInputLines( "Test.java", """
Test
java
spring-projects__spring-boot
smoke-test/spring-boot-smoke-test-hibernate/src/test/java/smoketest/jpa/repository/JpaNoteRepositoryIntegrationTests.java
{ "start": 1124, "end": 1404 }
class ____ { @Autowired JpaNoteRepository repository; @Test void findsAllNotes() { List<Note> notes = this.repository.findAll(); assertThat(notes).hasSize(4); for (Note note : notes) { assertThat(note.getTags()).isNotEmpty(); } } }
JpaNoteRepositoryIntegrationTests
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/intercept/InterceptSimpleRouteStopTest.java
{ "start": 983, "end": 1885 }
class ____ extends ContextTestSupport { @Test public void testInterceptWithStop() throws Exception { getMockEndpoint("mock:foo").expectedMessageCount(0); getMockEndpoint("mock:bar").expectedMessageCount(0); getMockEndpoint("mock:result").expectedMessageCount(0); getMockEndpoint("mock:intercepted").expectedMessageCount(1); template.sendBody("direct:start", "Hello World"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // START SNIPPET: e1 intercept().to("mock:intercepted").stop(); from("direct:start").to("mock:foo", "mock:bar", "mock:result"); // END SNIPPET: e1 } }; } }
InterceptSimpleRouteStopTest
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_212_alias.java
{ "start": 910, "end": 2026 }
class ____ extends MysqlTest { public void test_2() throws Exception { String sql = "SELECT count(1) from information_schema.tables;"; System.out.println(sql); MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.SelectItemGenerateAlias); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); SQLStatement stmt = statementList.get(0); assertEquals("SELECT count(1) AS `count(1)`\n" + "FROM information_schema.tables;", stmt.toString()); } public void test_3() throws Exception { String sql = "select count(Distinct id) from t"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.SelectItemGenerateAlias); List<SQLStatement> statementList = parser.parseStatementList(); assertEquals(1, statementList.size()); String text = output(statementList); assertEquals("SELECT count(DISTINCT id) AS `count(Distinct id)`\n" + "FROM t", text); } }
MySqlSelectTest_212_alias
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/CriteriaMutationQueryTableTest.java
{ "start": 4534, "end": 4717 }
class ____ extends Animal { private String name; public Person() { } public Person(Integer id, String name, int age) { super( id, age ); this.name = name; } } }
Person
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/StreamMultipleInputProcessorFactory.java
{ "start": 3619, "end": 7488 }
class ____ { @SuppressWarnings({"unchecked", "rawtypes"}) public static StreamMultipleInputProcessor create( TaskInvokable ownerTask, CheckpointedInputGate[] checkpointedInputGates, StreamConfig.InputConfig[] configuredInputs, IOManager ioManager, MemoryManager memoryManager, TaskIOMetricGroup ioMetricGroup, Counter mainOperatorRecordsIn, MultipleInputStreamOperator<?> mainOperator, WatermarkGauge[] inputWatermarkGauges, StreamConfig streamConfig, Configuration taskManagerConfig, Configuration jobConfig, ExecutionConfig executionConfig, ClassLoader userClassloader, OperatorChain<?, ?> operatorChain, InflightDataRescalingDescriptor inflightDataRescalingDescriptor, Function<Integer, StreamPartitioner<?>> gatePartitioners, TaskInfo taskInfo, CanEmitBatchOfRecordsChecker canEmitBatchOfRecords) { checkNotNull(operatorChain); List<Input> operatorInputs = mainOperator.getInputs(); int inputsCount = operatorInputs.size(); StreamOneInputProcessor<?>[] inputProcessors = new StreamOneInputProcessor[inputsCount]; Counter networkRecordsIn = new SimpleCounter(); ioMetricGroup.reuseRecordsInputCounter(networkRecordsIn); checkState( configuredInputs.length == inputsCount, "Number of configured inputs in StreamConfig [%s] doesn't match the main operator's number of inputs [%s]", configuredInputs.length, inputsCount); StreamTaskInput[] inputs = new StreamTaskInput[inputsCount]; for (int i = 0; i < inputsCount; i++) { StreamConfig.InputConfig configuredInput = configuredInputs[i]; if (configuredInput instanceof StreamConfig.NetworkInputConfig) { StreamConfig.NetworkInputConfig networkInput = (StreamConfig.NetworkInputConfig) configuredInput; inputs[i] = StreamTaskNetworkInputFactory.create( checkpointedInputGates[networkInput.getInputGateIndex()], networkInput.getTypeSerializer(), ioManager, new StatusWatermarkValve( checkpointedInputGates[networkInput.getInputGateIndex()]), i, inflightDataRescalingDescriptor, gatePartitioners, taskInfo, canEmitBatchOfRecords, streamConfig.getWatermarkDeclarations(userClassloader)); } else if (configuredInput instanceof StreamConfig.SourceInputConfig) { StreamConfig.SourceInputConfig sourceInput = (StreamConfig.SourceInputConfig) configuredInput; inputs[i] = operatorChain.getSourceTaskInput(sourceInput); } else { throw new UnsupportedOperationException("Unknown input type: " + configuredInput); } } InputSelectable inputSelectable = mainOperator instanceof InputSelectable ? (InputSelectable) mainOperator : null; StreamConfig.InputConfig[] inputConfigs = streamConfig.getInputs(userClassloader); boolean anyRequiresSorting = Arrays.stream(inputConfigs).anyMatch(StreamConfig::requiresSorting); if (anyRequiresSorting) { if (inputSelectable != null) { throw new IllegalStateException( "The InputSelectable
StreamMultipleInputProcessorFactory
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/param/MySqlParameterizedOutputVisitorTest_restore_1.java
{ "start": 170, "end": 3637 }
class ____ extends TestCase { public void test_for_parameterize() throws Exception { String sqlTemplate = "SELECT `buyer_resource`.`RESOURCE_ID`, `buyer_resource`.`RESOURCE_PROVIDER`, `buyer_resource`.`BUYER_ID`, `buyer_resource`.`RESOURCE_TYPE`, `buyer_resource`.`SUB_RESOURCE_TYPE`\n" + "\t, `buyer_resource`.`STATUS`, `buyer_resource`.`START_TIME`, `buyer_resource`.`END_TIME`, `buyer_resource`.`FEATURE`, `buyer_resource`.`GMT_CREATED`\n" + "\t, `buyer_resource`.`GMT_MODIFIED`, `buyer_resource`.`source`, `buyer_resource`.`seller_id`, `buyer_resource`.`original_Resource_Id`, `buyer_resource`.`business_unit`\n" + "\t, `buyer_resource`.`resource_code`, `buyer_resource`.`OPTIONS`, `buyer_resource`.`AVAILABLE_COUNT`, `buyer_resource`.`TOTAL_COUNT`, `buyer_resource`.`OUT_INSTANCE_ID`\n" + "\t, `buyer_resource`.`CONSUME_ID`, `buyer_resource`.`GROUP_ID`, `buyer_resource`.`BUSINESS_ID`, `buyer_resource`.`rule`, `buyer_resource`.`market_place`\n" + "\t, `buyer_resource`.`VERSION`\n" + "FROM buyer_resource `buyer_resource`\n" + "WHERE `buyer_resource`.`BUYER_ID` = ?\n" + "\tAND `buyer_resource`.`STATUS` = ?\n" + "\tAND `buyer_resource`.`START_TIME` <= ?\n" + "\tAND `buyer_resource`.`END_TIME` >= ?\n" + "\tAND `buyer_resource`.`seller_id` = ?\n" + "\tAND (`buyer_resource`.`AVAILABLE_COUNT` IS ?)\n" + "LIMIT ?, ?"; String params = "[1957025290,1,\"2017-10-16 23:34:28.519\",\"2017-10-16 23:34:28.519\",2933220011,[0,-1],0,20]"; params = params.replaceAll("''", "'"); sqlTemplate = SQLUtils.formatMySql(sqlTemplate); String formattedSql = ParseUtil.restore(sqlTemplate, null, params); assertEquals("SELECT `buyer_resource`.`RESOURCE_ID`, `buyer_resource`.`RESOURCE_PROVIDER`, `buyer_resource`.`BUYER_ID`, `buyer_resource`.`RESOURCE_TYPE`, `buyer_resource`.`SUB_RESOURCE_TYPE`\n" + "\t, `buyer_resource`.`STATUS`, `buyer_resource`.`START_TIME`, `buyer_resource`.`END_TIME`, `buyer_resource`.`FEATURE`, `buyer_resource`.`GMT_CREATED`\n" + "\t, `buyer_resource`.`GMT_MODIFIED`, `buyer_resource`.`source`, `buyer_resource`.`seller_id`, `buyer_resource`.`original_Resource_Id`, `buyer_resource`.`business_unit`\n" + "\t, `buyer_resource`.`resource_code`, `buyer_resource`.`OPTIONS`, `buyer_resource`.`AVAILABLE_COUNT`, `buyer_resource`.`TOTAL_COUNT`, `buyer_resource`.`OUT_INSTANCE_ID`\n" + "\t, `buyer_resource`.`CONSUME_ID`, `buyer_resource`.`GROUP_ID`, `buyer_resource`.`BUSINESS_ID`, `buyer_resource`.`rule`, `buyer_resource`.`market_place`\n" + "\t, `buyer_resource`.`VERSION`\n" + "FROM buyer_resource `buyer_resource`\n" + "WHERE `buyer_resource`.`BUYER_ID` = 1957025290\n" + "\tAND `buyer_resource`.`STATUS` = 1\n" + "\tAND `buyer_resource`.`START_TIME` <= '2017-10-16 23:34:28.519'\n" + "\tAND `buyer_resource`.`END_TIME` >= '2017-10-16 23:34:28.519'\n" + "\tAND `buyer_resource`.`seller_id` = 2933220011\n" + "\tAND ((`buyer_resource`.`AVAILABLE_COUNT` = 0 OR `buyer_resource`.`AVAILABLE_COUNT` = -1))\n" + "LIMIT 0, 20", formattedSql); } }
MySqlParameterizedOutputVisitorTest_restore_1
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/AttributeMetadata.java
{ "start": 386, "end": 920 }
interface ____ { PropertyAccess getPropertyAccess(); MutabilityPlan getMutabilityPlan(); boolean isNullable(); boolean isInsertable(); boolean isUpdatable(); boolean isSelectable(); boolean isIncludedInDirtyChecking(); boolean isIncludedInOptimisticLocking(); default CascadeStyle getCascadeStyle() { // todo (6.0) - implement in each subclass. // For now return a default NONE value for all contributors since this isn't // to be supported as a part of Alpha1. return CascadeStyles.NONE; } }
AttributeMetadata
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/conditions/Conditions_assertDoesNotHave_Test.java
{ "start": 1427, "end": 2284 }
class ____ extends ConditionsBaseTest { @Test void should_throw_error_if_Condition_is_null() { assertThatNullPointerException().isThrownBy(() -> conditions.assertDoesNotHave(someInfo(), actual, null)) .withMessage("The condition to evaluate should not be null"); } @Test void should_pass_if_Condition_is_not_met() { condition.shouldMatch(false); conditions.assertDoesNotHave(someInfo(), actual, condition); } @Test void should_fail_if_Condition_is_met() { condition.shouldMatch(true); AssertionInfo info = someInfo(); Throwable error = catchThrowable(() -> conditions.assertDoesNotHave(info, actual, condition)); assertThat(error).isInstanceOf(AssertionError.class); verify(failures).failure(info, shouldNotHave(actual, condition)); } }
Conditions_assertDoesNotHave_Test
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/bug/Bug_for_issue_291.java
{ "start": 1035, "end": 1103 }
class ____ { public int id; public int value; } }
V1
java
dropwizard__dropwizard
dropwizard-lifecycle/src/main/java/io/dropwizard/lifecycle/ExecutorServiceManager.java
{ "start": 181, "end": 1671 }
class ____ implements Managed { @SuppressWarnings("Slf4jLoggerShouldBeNonStatic") private static final Logger LOG = LoggerFactory.getLogger(ExecutorServiceManager.class); private final ExecutorService executor; private final Duration shutdownPeriod; private final String poolName; public ExecutorServiceManager(ExecutorService executor, Duration shutdownPeriod, String poolName) { this.executor = executor; this.shutdownPeriod = shutdownPeriod; this.poolName = poolName; } /** * {@inheritDoc} * * @throws InterruptedException * This is thrown if the thread executing this method is * interrupted while awaiting executor tasks to complete. */ @Override public void stop() throws InterruptedException, Exception { executor.shutdown(); final boolean success = executor.awaitTermination(shutdownPeriod.getQuantity(), shutdownPeriod.getUnit()); if (!success && LOG.isDebugEnabled()) { LOG.debug("Timeout has elapsed before termination completed for executor {}", executor); } } @Override public String toString() { return super.toString() + '(' + poolName + ')'; } public ExecutorService getExecutor() { return executor; } public Duration getShutdownPeriod() { return shutdownPeriod; } public String getPoolName() { return poolName; } }
ExecutorServiceManager
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/startup/StartupAnnotationTest.java
{ "start": 1052, "end": 4253 }
class ____ { static final List<String> LOG = new CopyOnWriteArrayList<String>(); @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(StartMe.class, SingletonStartMe.class, DependentStartMe.class, ProducerStartMe.class, StartupMethods.class)) .addBuildChainCustomizer(buildCustomizer()); static Consumer<BuildChainBuilder> buildCustomizer() { return new Consumer<BuildChainBuilder>() { @Override public void accept(BuildChainBuilder builder) { builder.addBuildStep(new BuildStep() { @Override public void execute(BuildContext context) { context.produce(new AnnotationsTransformerBuildItem(new AnnotationsTransformer() { @Override public boolean appliesTo(Kind kind) { return AnnotationTarget.Kind.CLASS.equals(kind); } @Override public void transform(TransformationContext context) { if (context.getTarget().asClass().name().toString().endsWith("SingletonStartMe")) { context.transform().add(Startup.class).done(); } } })); } }).produces(AnnotationsTransformerBuildItem.class).build(); } }; } @Test public void testStartup() { // StartMe, SingletonStartMe, ProducerStartMe, StartupMethods, DependentStartMe assertEquals(23, LOG.size(), "Unexpected number of log messages: " + LOG); assertEquals("startMe_c", LOG.get(0)); assertEquals("startMe_c", LOG.get(1)); assertEquals("startMe_pc", LOG.get(2)); assertEquals("singleton_c", LOG.get(3)); assertEquals("singleton_pc", LOG.get(4)); assertEquals("producer_pc", LOG.get(5)); assertEquals("produce_long", LOG.get(6)); assertEquals("producer_pd", LOG.get(7)); assertEquals("producer_pc", LOG.get(8)); assertEquals("dispose_long", LOG.get(9)); assertEquals("producer_pd", LOG.get(10)); assertEquals("producer_pc", LOG.get(11)); assertEquals("produce_string", LOG.get(12)); assertEquals("producer_pd", LOG.get(13)); assertEquals("producer_pc", LOG.get(14)); assertEquals("dispose_string", LOG.get(15)); assertEquals("producer_pd", LOG.get(16)); assertEquals("startup_pc", LOG.get(17)); assertEquals("startup_first", LOG.get(18)); assertEquals("startup_second", LOG.get(19)); assertEquals("dependent_c", LOG.get(20)); assertEquals("dependent_pc", LOG.get(21)); assertEquals("dependent_pd", LOG.get(22)); } // This component should be started first @Startup(ObserverMethod.DEFAULT_PRIORITY - 1) // @ApplicationScoped is added automatically static
StartupAnnotationTest
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/customexceptions/ImplClassExceptionMapperTest.java
{ "start": 2655, "end": 2870 }
class ____ implements GlobalCustomResource { public String throwsException() { throw removeStackTrace(new RuntimeException()); } } @Path("stock") public
GlobalCustomResourceImpl
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemamanager/SchemaManagerDefaultSchemaTest.java
{ "start": 2685, "end": 2929 }
class ____ { @Id String isbn = "xyz123"; String title = "Hibernate in Action"; @ManyToOne(cascade = CascadeType.PERSIST) Author author = new Author(); { author.favoriteBook = this; } } @Entity(name="AuthorForTesting") static
Book
java
apache__camel
components/camel-jgroups/src/test/java/org/apache/camel/component/jgroups/JGroupsClusterTest.java
{ "start": 1328, "end": 1631 }
class ____ { // Tested state String master; int nominationCount; // Routing fixtures String jgroupsEndpoint = format("jgroups:%s?enableViewMessages=true", randomUUID()); DefaultCamelContext firstCamelContext; DefaultCamelContext secondCamelContext;
JGroupsClusterTest
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/test/disruption/SlowClusterStateProcessing.java
{ "start": 922, "end": 5156 }
class ____ extends SingleNodeDisruption { volatile boolean disrupting; volatile Thread worker; final long intervalBetweenDelaysMin; final long intervalBetweenDelaysMax; final long delayDurationMin; final long delayDurationMax; public SlowClusterStateProcessing(Random random) { this(null, random); } public SlowClusterStateProcessing(String disruptedNode, Random random) { this(disruptedNode, random, 100, 200, 300, 20000); } public SlowClusterStateProcessing( String disruptedNode, Random random, long intervalBetweenDelaysMin, long intervalBetweenDelaysMax, long delayDurationMin, long delayDurationMax ) { this(random, intervalBetweenDelaysMin, intervalBetweenDelaysMax, delayDurationMin, delayDurationMax); this.disruptedNode = disruptedNode; } public SlowClusterStateProcessing( Random random, long intervalBetweenDelaysMin, long intervalBetweenDelaysMax, long delayDurationMin, long delayDurationMax ) { super(random); this.intervalBetweenDelaysMin = intervalBetweenDelaysMin; this.intervalBetweenDelaysMax = intervalBetweenDelaysMax; this.delayDurationMin = delayDurationMin; this.delayDurationMax = delayDurationMax; } @Override public void startDisrupting() { disrupting = true; worker = new Thread(new BackgroundWorker()); worker.setDaemon(true); worker.start(); } @Override public void stopDisrupting() { if (worker == null) { return; } logger.info("stopping to slow down cluster state processing on [{}]", disruptedNode); disrupting = false; worker.interrupt(); try { worker.join(2 * (intervalBetweenDelaysMax + delayDurationMax)); } catch (InterruptedException e) { logger.info("background thread failed to stop"); } worker = null; } private boolean interruptClusterStateProcessing(final TimeValue duration) throws InterruptedException { final String disruptionNodeCopy = disruptedNode; if (disruptionNodeCopy == null) { return false; } logger.info("delaying cluster state updates on node [{}] for [{}]", disruptionNodeCopy, duration); final CountDownLatch countDownLatch = new CountDownLatch(1); ClusterService clusterService = cluster.getInstance(ClusterService.class, disruptionNodeCopy); if (clusterService == null) { return false; } final AtomicBoolean stopped = new AtomicBoolean(false); clusterService.getClusterApplierService().runOnApplierThread("service_disruption_delay", Priority.IMMEDIATE, currentState -> { try { long count = duration.millis() / 200; // wait while checking for a stopped for (; count > 0 && stopped.get() == false; count--) { Thread.sleep(200); } if (stopped.get() == false) { Thread.sleep(duration.millis() % 200); } countDownLatch.countDown(); } catch (InterruptedException e) { ExceptionsHelper.reThrowIfNotNull(e); } }, new ActionListener<>() { @Override public void onResponse(Void unused) {} @Override public void onFailure(Exception e) { countDownLatch.countDown(); } }); try { countDownLatch.await(); } catch (InterruptedException e) { stopped.set(true); // try to wait again, we really want the cluster state thread to be freed up when stopping disruption countDownLatch.await(); } return true; } @Override public void removeAndEnsureHealthy(InternalTestCluster cluster) { removeFromCluster(cluster); ensureNodeCount(cluster); } @Override public TimeValue expectedTimeToHeal() { return TimeValue.timeValueMillis(0); }
SlowClusterStateProcessing
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/leaderelection/ZooKeeperLeaderElectionDriverFactory.java
{ "start": 1054, "end": 1611 }
class ____ implements LeaderElectionDriverFactory { private final CuratorFramework curatorFramework; public ZooKeeperLeaderElectionDriverFactory(CuratorFramework curatorFramework) { this.curatorFramework = Preconditions.checkNotNull(curatorFramework); } @Override public ZooKeeperLeaderElectionDriver create( LeaderElectionDriver.Listener leaderElectionListener) throws Exception { return new ZooKeeperLeaderElectionDriver(curatorFramework, leaderElectionListener); } }
ZooKeeperLeaderElectionDriverFactory
java
apache__hadoop
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/TaskInfo.java
{ "start": 854, "end": 3165 }
class ____ { private final long bytesIn; private final int recsIn; private final long bytesOut; private final int recsOut; private final long maxMemory; private final long maxVcores; private final ResourceUsageMetrics metrics; public TaskInfo(long bytesIn, int recsIn, long bytesOut, int recsOut, long maxMemory) { this(bytesIn, recsIn, bytesOut, recsOut, maxMemory, 1, new ResourceUsageMetrics()); } public TaskInfo(long bytesIn, int recsIn, long bytesOut, int recsOut, long maxMemory, ResourceUsageMetrics metrics) { this(bytesIn, recsIn, bytesOut, recsOut, maxMemory, 1, metrics); } public TaskInfo(long bytesIn, int recsIn, long bytesOut, int recsOut, long maxMemory, long maxVcores) { this(bytesIn, recsIn, bytesOut, recsOut, maxMemory, maxVcores, new ResourceUsageMetrics()); } public TaskInfo(long bytesIn, int recsIn, long bytesOut, int recsOut, long maxMemory, long maxVcores, ResourceUsageMetrics metrics) { this.bytesIn = bytesIn; this.recsIn = recsIn; this.bytesOut = bytesOut; this.recsOut = recsOut; this.maxMemory = maxMemory; this.maxVcores = maxVcores; this.metrics = metrics; } /** * @return Raw bytes read from the FileSystem into the task. Note that this * may not always match the input bytes to the task. */ public long getInputBytes() { return bytesIn; } /** * @return Number of records input to this task. */ public int getInputRecords() { return recsIn; } /** * @return Raw bytes written to the destination FileSystem. Note that this may * not match output bytes. */ public long getOutputBytes() { return bytesOut; } /** * @return Number of records output from this task. */ public int getOutputRecords() { return recsOut; } /** * @return Memory used by the task leq the heap size. */ public long getTaskMemory() { return maxMemory; } /** * @return Vcores used by the task. */ public long getTaskVCores() { return maxVcores; } /** * @return Resource usage metrics */ public ResourceUsageMetrics getResourceUsageMetrics() { return metrics; } }
TaskInfo
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurer.java
{ "start": 2934, "end": 11464 }
class ____<H extends HttpSecurityBuilder<H>> extends AbstractAuthenticationFilterConfigurer<H, FormLoginConfigurer<H>, UsernamePasswordAuthenticationFilter> { /** * Creates a new instance * @see HttpSecurity#formLogin(Customizer) */ public FormLoginConfigurer() { super(new UsernamePasswordAuthenticationFilter(), null); usernameParameter("username"); passwordParameter("password"); } /** * <p> * Specifies the URL to send users to if login is required. If used with * {@link EnableWebSecurity} a default login page will be generated when this * attribute is not specified. * </p> * * <p> * If a URL is specified or this is not being used in conjunction with * {@link EnableWebSecurity}, users are required to process the specified URL to * generate a login page. In general, the login page should create a form that submits * a request with the following requirements to work with * {@link UsernamePasswordAuthenticationFilter}: * </p> * * <ul> * <li>It must be an HTTP POST</li> * <li>It must be submitted to {@link #loginProcessingUrl(String)}</li> * <li>It should include the username as an HTTP parameter by the name of * {@link #usernameParameter(String)}</li> * <li>It should include the password as an HTTP parameter by the name of * {@link #passwordParameter(String)}</li> * </ul> * * <h2>Example login.jsp</h2> * * Login pages can be rendered with any technology you choose so long as the rules * above are followed. Below is an example login.jsp that can be used as a quick start * when using JSP's or as a baseline to translate into another view technology. * * <pre> * <!-- loginProcessingUrl should correspond to FormLoginConfigurer#loginProcessingUrl. Don't forget to perform a POST --> * &lt;c:url value="/login" var="loginProcessingUrl"/&gt; * &lt;form action="${loginProcessingUrl}" method="post"&gt; * &lt;fieldset&gt; * &lt;legend&gt;Please Login&lt;/legend&gt; * &lt;!-- use param.error assuming FormLoginConfigurer#failureUrl contains the query parameter error --&gt; * &lt;c:if test="${param.error != null}"&gt; * &lt;div&gt; * Failed to login. * &lt;c:if test="${SPRING_SECURITY_LAST_EXCEPTION != null}"&gt; * Reason: &lt;c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" /&gt; * &lt;/c:if&gt; * &lt;/div&gt; * &lt;/c:if&gt; * &lt;!-- the configured LogoutConfigurer#logoutSuccessUrl is /login?logout and contains the query param logout --&gt; * &lt;c:if test="${param.logout != null}"&gt; * &lt;div&gt; * You have been logged out. * &lt;/div&gt; * &lt;/c:if&gt; * &lt;p&gt; * &lt;label for="username"&gt;Username&lt;/label&gt; * &lt;input type="text" id="username" name="username"/&gt; * &lt;/p&gt; * &lt;p&gt; * &lt;label for="password"&gt;Password&lt;/label&gt; * &lt;input type="password" id="password" name="password"/&gt; * &lt;/p&gt; * &lt;!-- if using RememberMeConfigurer make sure remember-me matches RememberMeConfigurer#rememberMeParameter --&gt; * &lt;p&gt; * &lt;label for="remember-me"&gt;Remember Me?&lt;/label&gt; * &lt;input type="checkbox" id="remember-me" name="remember-me"/&gt; * &lt;/p&gt; * &lt;div&gt; * &lt;button type="submit" class="btn"&gt;Log in&lt;/button&gt; * &lt;/div&gt; * &lt;/fieldset&gt; * &lt;/form&gt; * </pre> * * <h2>Impact on other defaults</h2> * * Updating this value, also impacts a number of other default values. For example, * the following are the default values when only formLogin() was specified. * * <ul> * <li>/login GET - the login form</li> * <li>/login POST - process the credentials and if valid authenticate the user</li> * <li>/login?error GET - redirect here for failed authentication attempts</li> * <li>/login?logout GET - redirect here after successfully logging out</li> * </ul> * * If "/authenticate" was passed to this method it update the defaults as shown below: * * <ul> * <li>/authenticate GET - the login form</li> * <li>/authenticate POST - process the credentials and if valid authenticate the user * </li> * <li>/authenticate?error GET - redirect here for failed authentication attempts</li> * <li>/authenticate?logout GET - redirect here after successfully logging out</li> * </ul> * @param loginPage the login page to redirect to if authentication is required (i.e. * "/login") * @return the {@link FormLoginConfigurer} for additional customization */ @Override public FormLoginConfigurer<H> loginPage(String loginPage) { return super.loginPage(loginPage); } /** * The HTTP parameter to look for the username when performing authentication. Default * is "username". * @param usernameParameter the HTTP parameter to look for the username when * performing authentication * @return the {@link FormLoginConfigurer} for additional customization */ public FormLoginConfigurer<H> usernameParameter(String usernameParameter) { getAuthenticationFilter().setUsernameParameter(usernameParameter); return this; } /** * The HTTP parameter to look for the password when performing authentication. Default * is "password". * @param passwordParameter the HTTP parameter to look for the password when * performing authentication * @return the {@link FormLoginConfigurer} for additional customization */ public FormLoginConfigurer<H> passwordParameter(String passwordParameter) { getAuthenticationFilter().setPasswordParameter(passwordParameter); return this; } /** * Forward Authentication Failure Handler * @param forwardUrl the target URL in case of failure * @return the {@link FormLoginConfigurer} for additional customization */ public FormLoginConfigurer<H> failureForwardUrl(String forwardUrl) { failureHandler(new ForwardAuthenticationFailureHandler(forwardUrl)); return this; } /** * Forward Authentication Success Handler * @param forwardUrl the target URL in case of success * @return the {@link FormLoginConfigurer} for additional customization */ public FormLoginConfigurer<H> successForwardUrl(String forwardUrl) { successHandler(new ForwardAuthenticationSuccessHandler(forwardUrl)); return this; } @Override public void init(H http) { super.init(http); initDefaultLoginFilter(http); ExceptionHandlingConfigurer<H> exceptions = http.getConfigurer(ExceptionHandlingConfigurer.class); if (exceptions != null) { AuthenticationEntryPoint entryPoint = getAuthenticationEntryPoint(); RequestMatcher requestMatcher = getAuthenticationEntryPointMatcher(http); exceptions.defaultDeniedHandlerForMissingAuthority((ep) -> ep.addEntryPointFor(entryPoint, requestMatcher), FactorGrantedAuthority.PASSWORD_AUTHORITY); } } @Override protected RequestMatcher createLoginProcessingUrlMatcher(String loginProcessingUrl) { return getRequestMatcherBuilder().matcher(HttpMethod.POST, loginProcessingUrl); } /** * Gets the HTTP parameter that is used to submit the username. * @return the HTTP parameter that is used to submit the username */ private String getUsernameParameter() { return getAuthenticationFilter().getUsernameParameter(); } /** * Gets the HTTP parameter that is used to submit the password. * @return the HTTP parameter that is used to submit the password */ private String getPasswordParameter() { return getAuthenticationFilter().getPasswordParameter(); } /** * If available, initializes the {@link DefaultLoginPageGeneratingFilter} shared * object. * @param http the {@link HttpSecurityBuilder} to use */ private void initDefaultLoginFilter(H http) { DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http .getSharedObject(DefaultLoginPageGeneratingFilter.class); if (loginPageGeneratingFilter != null && !isCustomLoginPage()) { loginPageGeneratingFilter.setFormLoginEnabled(true); loginPageGeneratingFilter.setUsernameParameter(getUsernameParameter()); loginPageGeneratingFilter.setPasswordParameter(getPasswordParameter()); loginPageGeneratingFilter.setLoginPageUrl(getLoginPage()); loginPageGeneratingFilter.setFailureUrl(getFailureUrl()); loginPageGeneratingFilter.setAuthenticationUrl(getLoginProcessingUrl()); } } }
FormLoginConfigurer
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conditional/qualifier/ConditionalQualifierTest.java
{ "start": 623, "end": 4515 }
class ____ { @ProcessorTest @WithClasses({ ConditionalMethodWithSourceParameterMapper.class }) public void conditionalMethodWithSourceParameter() { ConditionalMethodWithSourceParameterMapper mapper = ConditionalMethodWithSourceParameterMapper.INSTANCE; EmployeeDto dto = new EmployeeDto(); dto.setName( "Tester" ); dto.setUniqueIdNumber( "SSID-001" ); dto.setCountry( null ); Employee employee = mapper.map( dto ); assertThat( employee.getNin() ).isNull(); assertThat( employee.getSsid() ).isNull(); dto.setCountry( "UK" ); employee = mapper.map( dto ); assertThat( employee.getNin() ).isEqualTo( "SSID-001" ); assertThat( employee.getSsid() ).isNull(); dto.setCountry( "US" ); employee = mapper.map( dto ); assertThat( employee.getNin() ).isNull(); assertThat( employee.getSsid() ).isEqualTo( "SSID-001" ); dto.setCountry( "CH" ); employee = mapper.map( dto ); assertThat( employee.getNin() ).isNull(); assertThat( employee.getSsid() ).isNull(); } @ProcessorTest @WithClasses({ ConditionalMethodWithClassQualifiersMapper.class }) public void conditionalClassQualifiers() { ConditionalMethodWithClassQualifiersMapper mapper = ConditionalMethodWithClassQualifiersMapper.INSTANCE; EmployeeDto dto = new EmployeeDto(); dto.setName( "Tester" ); dto.setUniqueIdNumber( "SSID-001" ); dto.setCountry( null ); Employee employee = mapper.map( dto ); assertThat( employee.getNin() ).isNull(); assertThat( employee.getSsid() ).isNull(); dto.setCountry( "UK" ); employee = mapper.map( dto ); assertThat( employee.getNin() ).isEqualTo( "SSID-001" ); assertThat( employee.getSsid() ).isNull(); dto.setCountry( "US" ); employee = mapper.map( dto ); assertThat( employee.getNin() ).isNull(); assertThat( employee.getSsid() ).isEqualTo( "SSID-001" ); dto.setCountry( "CH" ); employee = mapper.map( dto ); assertThat( employee.getNin() ).isNull(); assertThat( employee.getSsid() ).isNull(); } @ProcessorTest @WithClasses({ ConditionalMethodWithSourceToTargetMapper.class }) @IssueKey("2666") public void conditionalQualifiersForSourceToTarget() { ConditionalMethodWithSourceToTargetMapper mapper = ConditionalMethodWithSourceToTargetMapper.INSTANCE; ConditionalMethodWithSourceToTargetMapper.OrderDTO orderDto = new ConditionalMethodWithSourceToTargetMapper.OrderDTO(); ConditionalMethodWithSourceToTargetMapper.Order order = mapper.convertToOrder( orderDto ); assertThat( order ).isNotNull(); assertThat( order.getCustomer() ).isNull(); orderDto = new ConditionalMethodWithSourceToTargetMapper.OrderDTO(); orderDto.setCustomerName( "Tester" ); order = mapper.convertToOrder( orderDto ); assertThat( order ).isNotNull(); assertThat( order.getCustomer() ).isNotNull(); assertThat( order.getCustomer().getName() ).isEqualTo( "Tester" ); assertThat( order.getCustomer().getAddress() ).isNull(); orderDto = new ConditionalMethodWithSourceToTargetMapper.OrderDTO(); orderDto.setLine1( "Line 1" ); order = mapper.convertToOrder( orderDto ); assertThat( order ).isNotNull(); assertThat( order.getCustomer() ).isNotNull(); assertThat( order.getCustomer().getName() ).isNull(); assertThat( order.getCustomer().getAddress() ).isNotNull(); assertThat( order.getCustomer().getAddress().getLine1() ).isEqualTo( "Line 1" ); assertThat( order.getCustomer().getAddress().getLine2() ).isNull(); } }
ConditionalQualifierTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/SynchronizeableQuery.java
{ "start": 3867, "end": 3991 }
class ____ the entity. * * @return {@code this}, for method chaining * * @throws MappingException Indicates the given
of
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/PrinterEndpointBuilderFactory.java
{ "start": 13031, "end": 13736 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final PrinterHeaderNameBuilder INSTANCE = new PrinterHeaderNameBuilder(); /** * The name of the job. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code PrinterJobName}. */ public String printerJobName() { return "PrinterJobName"; } } static PrinterEndpointBuilder endpointBuilder(String componentName, String path) {
PrinterHeaderNameBuilder
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/DisabledIfTests.java
{ "start": 3591, "end": 3837 }
class ____ { @Test void foo() { fail("This test must be disabled"); } @Test @DisabledIf("false") void bar() { fail("This test must be disabled due to class-level condition"); } } @Configuration static
DisabledIfOnClassTests
java
spring-projects__spring-boot
test-support/spring-boot-test-support/src/main/java/org/springframework/boot/testsupport/classpath/resources/ResourceContent.java
{ "start": 1130, "end": 1282 }
interface ____ { /** * The name of the resource whose content should be injected. * @return the resource name */ String value(); }
ResourceContent
java
elastic__elasticsearch
modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/JsonProcessor.java
{ "start": 8324, "end": 11320 }
class ____ implements Processor.Factory { @Override public JsonProcessor create( Map<String, Processor.Factory> registry, String processorTag, String description, Map<String, Object> config, ProjectId projectId ) throws Exception { String field = ConfigurationUtils.readStringProperty(TYPE, processorTag, config, "field"); String targetField = ConfigurationUtils.readOptionalStringProperty(TYPE, processorTag, config, "target_field"); boolean addToRoot = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "add_to_root", false); boolean allowDuplicateKeys = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, "allow_duplicate_keys", false); String conflictStrategyString = ConfigurationUtils.readOptionalStringProperty( TYPE, processorTag, config, "add_to_root_conflict_strategy" ); boolean hasConflictStrategy = conflictStrategyString != null; if (conflictStrategyString == null) { conflictStrategyString = ConflictStrategy.REPLACE.name(); } ConflictStrategy addToRootConflictStrategy; try { addToRootConflictStrategy = ConflictStrategy.fromString(conflictStrategyString); } catch (IllegalArgumentException e) { throw newConfigurationException( TYPE, processorTag, "add_to_root_conflict_strategy", "conflict strategy [" + conflictStrategyString + "] not supported, cannot convert field." ); } if (addToRoot && targetField != null) { throw newConfigurationException( TYPE, processorTag, "target_field", "Cannot set a target field while also setting `add_to_root` to true" ); } if (addToRoot == false && hasConflictStrategy) { throw newConfigurationException( TYPE, processorTag, "add_to_root_conflict_strategy", "Cannot set `add_to_root_conflict_strategy` if `add_to_root` is false" ); } boolean strictParsing = ConfigurationUtils.readBooleanProperty(TYPE, processorTag, config, STRICT_JSON_PARSING_PARAMETER, true); if (targetField == null) { targetField = field; } return new JsonProcessor( processorTag, description, field, targetField, addToRoot, addToRootConflictStrategy, allowDuplicateKeys, strictParsing ); } } }
Factory
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/util/ReflectionTestUtils.java
{ "start": 20881, "end": 21581 }
class ____ in search of the desired * method. In addition, an attempt will be made to make non-{@code public} * methods <em>accessible</em>, thus allowing one to invoke {@code protected}, * {@code private}, and <em>package-private</em> methods. * <p>As of Spring Framework 6.2, if the supplied target object is a CGLIB * proxy which does not intercept the method, the proxy will be * {@linkplain AopTestUtils#getUltimateTargetObject unwrapped} allowing the * method to be invoked directly on the ultimate target of the proxy. * @param targetObject the target object on which to invoke the method; may * be {@code null} if the method is static * @param targetClass the target
hierarchy
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/utils/ClassHelper.java
{ "start": 1596, "end": 1903 }
class ____ */ public static ClassLoader getClassLoader(Class<?> clazz) { return ClassUtils.getClassLoader(clazz); } /** * Return the default ClassLoader to use: typically the thread context * ClassLoader, if available; the ClassLoader that loaded the ClassUtils *
loader
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/service/hadoop/FileSystemAccessService.java
{ "start": 3298, "end": 9742 }
class ____ { private FileSystem fs; private long lastUse; private long timeout; private int count; public CachedFileSystem(long timeout) { this.timeout = timeout; lastUse = -1; count = 0; } synchronized FileSystem getFileSystem(Configuration conf) throws IOException { if (fs == null) { fs = FileSystem.get(conf); } lastUse = -1; count++; return fs; } synchronized void release() throws IOException { count--; if (count == 0) { if (timeout == 0) { fs.close(); fs = null; lastUse = -1; } else { lastUse = System.currentTimeMillis(); } } } // to avoid race conditions in the map cache adding removing entries // an entry in the cache remains forever, it just closes/opens filesystems // based on their utilization. Worse case scenario, the penalty we'll // pay is that the amount of entries in the cache will be the total // number of users in HDFS (which seems a resonable overhead). synchronized boolean purgeIfIdle() throws IOException { boolean ret = false; if (count == 0 && lastUse != -1 && (System.currentTimeMillis() - lastUse) > timeout) { fs.close(); fs = null; lastUse = -1; ret = true; } return ret; } } public FileSystemAccessService() { super(PREFIX); } private Collection<String> nameNodeWhitelist; Configuration serviceHadoopConf; private Configuration fileSystemConf; private AtomicInteger unmanagedFileSystems = new AtomicInteger(); private ConcurrentHashMap<String, CachedFileSystem> fsCache = new ConcurrentHashMap<String, CachedFileSystem>(); private long purgeTimeout; @Override protected void init() throws ServiceException { LOG.info("Using FileSystemAccess JARs version [{}]", VersionInfo.getVersion()); String security = getServiceConfig().get(AUTHENTICATION_TYPE, "simple").trim(); if (security.equals("kerberos")) { String defaultName = getServer().getName(); String keytab = System.getProperty("user.home") + "/" + defaultName + ".keytab"; keytab = getServiceConfig().get(KERBEROS_KEYTAB, keytab).trim(); if (keytab.length() == 0) { throw new ServiceException(FileSystemAccessException.ERROR.H01, KERBEROS_KEYTAB); } String principal = defaultName + "/localhost@LOCALHOST"; principal = getServiceConfig().get(KERBEROS_PRINCIPAL, principal).trim(); if (principal.length() == 0) { throw new ServiceException(FileSystemAccessException.ERROR.H01, KERBEROS_PRINCIPAL); } Configuration conf = new Configuration(); conf.set(HADOOP_SECURITY_AUTHENTICATION, "kerberos"); UserGroupInformation.setConfiguration(conf); try { UserGroupInformation.loginUserFromKeytab(principal, keytab); } catch (IOException ex) { throw new ServiceException(FileSystemAccessException.ERROR.H02, ex.getMessage(), ex); } LOG.info("Using FileSystemAccess Kerberos authentication, principal [{}] keytab [{}]", principal, keytab); } else if (security.equals("simple")) { Configuration conf = new Configuration(); conf.set(HADOOP_SECURITY_AUTHENTICATION, "simple"); UserGroupInformation.setConfiguration(conf); LOG.info("Using FileSystemAccess simple/pseudo authentication, principal [{}]", System.getProperty("user.name")); } else { throw new ServiceException(FileSystemAccessException.ERROR.H09, security); } String hadoopConfDirProp = getServiceConfig().get(HADOOP_CONF_DIR, getServer().getConfigDir()); File hadoopConfDir = new File(hadoopConfDirProp).getAbsoluteFile(); if (!hadoopConfDir.exists()) { hadoopConfDir = new File(getServer().getConfigDir()).getAbsoluteFile(); } if (!hadoopConfDir.exists()) { throw new ServiceException(FileSystemAccessException.ERROR.H10, hadoopConfDir); } try { serviceHadoopConf = loadHadoopConf(hadoopConfDir); fileSystemConf = getNewFileSystemConfiguration(); } catch (IOException ex) { throw new ServiceException(FileSystemAccessException.ERROR.H11, ex.toString(), ex); } if (LOG.isDebugEnabled()) { LOG.debug("FileSystemAccess FileSystem configuration:"); for (Map.Entry entry : serviceHadoopConf) { LOG.debug(" {} = {}", entry.getKey(), entry.getValue()); } } setRequiredServiceHadoopConf(serviceHadoopConf); nameNodeWhitelist = toLowerCase(getServiceConfig().getTrimmedStringCollection(NAME_NODE_WHITELIST)); } private Configuration loadHadoopConf(File dir) throws IOException { Configuration hadoopConf = new Configuration(false); for (String file : HADOOP_CONF_FILES) { File f = new File(dir, file); if (f.exists()) { hadoopConf.addResource(new Path(f.getAbsolutePath())); } } return hadoopConf; } private Configuration getNewFileSystemConfiguration() { Configuration conf = new Configuration(true); ConfigurationUtils.copy(serviceHadoopConf, conf); conf.setBoolean(FILE_SYSTEM_SERVICE_CREATED, true); // Force-clear server-side umask to make HttpFS match WebHDFS behavior conf.set(FsPermission.UMASK_LABEL, "000"); return conf; } @Override public void postInit() throws ServiceException { super.postInit(); Instrumentation instrumentation = getServer().get(Instrumentation.class); instrumentation.addVariable(INSTRUMENTATION_GROUP, "unmanaged.fs", new Instrumentation.Variable<Integer>() { @Override public Integer getValue() { return unmanagedFileSystems.get(); } }); instrumentation.addSampler(INSTRUMENTATION_GROUP, "unmanaged.fs", 60, new Instrumentation.Variable<Long>() { @Override public Long getValue() { return (long) unmanagedFileSystems.get(); } }); Scheduler scheduler = getServer().get(Scheduler.class); int purgeInterval = getServiceConfig().getInt(FS_CACHE_PURGE_FREQUENCY, 60); purgeTimeout = getServiceConfig().getLong(FS_CACHE_PURGE_TIMEOUT, 60); purgeTimeout = (purgeTimeout > 0) ? purgeTimeout : 0; if (purgeTimeout > 0) { scheduler.schedule(new FileSystemCachePurger(), purgeInterval, purgeInterval, TimeUnit.SECONDS); } } private
CachedFileSystem
java
alibaba__nacos
api/src/main/java/com/alibaba/nacos/api/config/ConfigService.java
{ "start": 1793, "end": 9655 }
interface ____ * * @param dataId dataId * @param group group * @param timeoutMs read timeout * @param listener {@link Listener} * @return config value * @throws NacosException NacosException */ String getConfigAndSignListener(String dataId, String group, long timeoutMs, Listener listener) throws NacosException; /** * Add a listener to the configuration, after the server modified the configuration, the client will use the * incoming listener callback. Recommended asynchronous processing, the application can implement the getExecutor * method in the ManagerListener, provide a thread pool of execution. If not provided, use the main thread callback, May * block other configurations or be blocked by other configurations. * * @param dataId dataId * @param group group * @param listener listener * @throws NacosException NacosException */ void addListener(String dataId, String group, Listener listener) throws NacosException; /** * Publish config. * * @param dataId dataId * @param group group * @param content content * @return Whether publish * @throws NacosException NacosException */ boolean publishConfig(String dataId, String group, String content) throws NacosException; /** * Publish config. * * @param dataId dataId * @param group group * @param content content * @param type config type {@link ConfigType} * @return Whether publish * @throws NacosException NacosException */ boolean publishConfig(String dataId, String group, String content, String type) throws NacosException; /** * Cas Publish config. * * @param dataId dataId * @param group group * @param content content * @param casMd5 casMd5 prev content's md5 to cas. * @return Whether publish * @throws NacosException NacosException */ boolean publishConfigCas(String dataId, String group, String content, String casMd5) throws NacosException; /** * Cas Publish config. * * @param dataId dataId * @param group group * @param content content * @param casMd5 casMd5 prev content's md5 to cas. * @param type config type {@link ConfigType} * @return Whether publish * @throws NacosException NacosException */ boolean publishConfigCas(String dataId, String group, String content, String casMd5, String type) throws NacosException; /** * Remove config. * * @param dataId dataId * @param group group * @return whether remove * @throws NacosException NacosException */ boolean removeConfig(String dataId, String group) throws NacosException; /** * Remove listener. * * @param dataId dataId * @param group group * @param listener listener */ void removeListener(String dataId, String group, Listener listener); /** * Get server status. * * @return whether health */ String getServerStatus(); /** * add config filter. * It is recommended to use {@link com.alibaba.nacos.api.config.filter.AbstractConfigFilter} to expand the filter. * * @param configFilter filter * @since 2.3.0 */ void addConfigFilter(IConfigFilter configFilter); /** * Shutdown the resource service. * * @throws NacosException exception. */ void shutDown() throws NacosException; /** * Add a fuzzy listener to the configuration. After the server modifies the configuration matching the specified * fixed group name, the client will utilize the incoming fuzzy listener callback. Fuzzy listeners allow for * pattern-based subscription to configurations, where the fixed group name represents the group and dataId patterns * specified for subscription. * * @param groupNamePattern The group name pattern representing the group and dataId patterns to subscribe to. * @param watcher The fuzzy watcher to be added. * @throws NacosException NacosException * @since 3.0 */ void fuzzyWatch(String groupNamePattern, FuzzyWatchEventWatcher watcher) throws NacosException; /** * Add a fuzzy listener to the configuration. After the server modifies the configuration matching the specified * dataId pattern and fixed group name, the client will utilize the incoming fuzzy listener callback. Fuzzy * listeners allow for pattern-based subscription to configurations. * * @param dataIdPattern The pattern to match dataIds for subscription. * @param groupNamePattern The pattern to match group name representing the group and dataId patterns to subscribe to. * @param watcher The fuzzy listener to be added. * @throws NacosException NacosException * @since 3.0 */ void fuzzyWatch(String dataIdPattern, String groupNamePattern, FuzzyWatchEventWatcher watcher) throws NacosException; /** * Add a fuzzy listener to the configuration and retrieve all configs that match the specified fixed group name. * Fuzzy listeners allow for pattern-based subscription to configs, where the fixed group name represents the group * and dataId patterns specified for subscription. * * @param groupNamePattern The group name pattern representing the group and dataId patterns to subscribe to. * @param watcher The fuzzy watcher to be added. * @return CompletableFuture containing collection of configs that match the specified fixed group name. * @throws NacosException NacosException * @since 3.0 */ Future<Set<String>> fuzzyWatchWithGroupKeys(String groupNamePattern, FuzzyWatchEventWatcher watcher) throws NacosException; /** * Add a fuzzy listener to the configuration and retrieve all configs that match the specified dataId pattern and * fixed group name. Fuzzy listeners allow for pattern-based subscription to configs. * * @param dataIdPattern The pattern to match dataIds for subscription. * @param groupNamePattern The group name pattern representing the group and dataId patterns to subscribe to. * @param watcher The fuzzy watcher to be added. * @return CompletableFuture containing collection of configs that match the specified dataId pattern and fixed * group name. * @throws NacosException NacosException * @since 3.0 */ Future<Set<String>> fuzzyWatchWithGroupKeys(String dataIdPattern, String groupNamePattern, FuzzyWatchEventWatcher watcher) throws NacosException; /** * Cancel fuzzy listen and remove the event listener for a specified fixed group name. * * @param groupNamePattern The group name pattern for fuzzy watch. * @param watcher The event watcher to be removed. * @throws NacosException If an error occurs during the cancellation process. * @since 3.0 */ void cancelFuzzyWatch(String groupNamePattern, FuzzyWatchEventWatcher watcher) throws NacosException; /** * Cancel fuzzy listen and remove the event listener for a specified service name pattern and fixed group name. * * @param dataIdPattern The pattern to match dataId for fuzzy watch. * @param groupNamePattern The group name pattern for fuzzy watch. * @param watcher The event listener to be removed. * @throws NacosException If an error occurs during the cancellation process. * @since 3.0 */ void cancelFuzzyWatch(String dataIdPattern, String groupNamePattern, FuzzyWatchEventWatcher watcher) throws NacosException; }
directly
java
apache__kafka
connect/transforms/src/test/java/org/apache/kafka/connect/transforms/SetSchemaMetadataTest.java
{ "start": 1750, "end": 8956 }
class ____ { private final SetSchemaMetadata<SinkRecord> xform = new SetSchemaMetadata.Value<>(); public static Stream<Arguments> data() { return Stream.of( Arguments.of(false, null), Arguments.of(true, "default") ); } @AfterEach public void teardown() { xform.close(); } @Test public void schemaNameUpdate() { xform.configure(Map.of("schema.name", "foo")); final SinkRecord record = new SinkRecord("", 0, null, null, SchemaBuilder.struct().build(), null, 0); final SinkRecord updatedRecord = xform.apply(record); assertEquals("foo", updatedRecord.valueSchema().name()); } @Test public void schemaVersionUpdate() { xform.configure(Map.of("schema.version", 42)); final SinkRecord record = new SinkRecord("", 0, null, null, SchemaBuilder.struct().build(), null, 0); final SinkRecord updatedRecord = xform.apply(record); assertEquals(42, updatedRecord.valueSchema().version()); } @Test public void schemaNameAndVersionUpdate() { final Map<String, String> props = new HashMap<>(); props.put("schema.name", "foo"); props.put("schema.version", "42"); xform.configure(props); final SinkRecord record = new SinkRecord("", 0, null, null, SchemaBuilder.struct().build(), null, 0); final SinkRecord updatedRecord = xform.apply(record); assertEquals("foo", updatedRecord.valueSchema().name()); assertEquals(42, updatedRecord.valueSchema().version()); } @Test public void schemaNameAndVersionUpdateWithStruct() { final String fieldName1 = "f1"; final String fieldName2 = "f2"; final String fieldValue1 = "value1"; final int fieldValue2 = 1; final Schema schema = SchemaBuilder.struct() .name("my.orig.SchemaDefn") .field(fieldName1, Schema.STRING_SCHEMA) .field(fieldName2, Schema.INT32_SCHEMA) .build(); final Struct value = new Struct(schema).put(fieldName1, fieldValue1).put(fieldName2, fieldValue2); final Map<String, String> props = new HashMap<>(); props.put("schema.name", "foo"); props.put("schema.version", "42"); xform.configure(props); final SinkRecord record = new SinkRecord("", 0, null, null, schema, value, 0); final SinkRecord updatedRecord = xform.apply(record); assertEquals("foo", updatedRecord.valueSchema().name()); assertEquals(42, updatedRecord.valueSchema().version()); // Make sure the struct's schema and fields all point to the new schema assertMatchingSchema((Struct) updatedRecord.value(), updatedRecord.valueSchema()); } @ParameterizedTest @MethodSource("data") public void schemaNameAndVersionUpdateWithStructAndNullField(boolean replaceNullWithDefault, Object expectedValue) { final String fieldName1 = "f1"; final String fieldName2 = "f2"; final int fieldValue2 = 1; final Schema schema = SchemaBuilder.struct() .name("my.orig.SchemaDefn") .field(fieldName1, SchemaBuilder.string().defaultValue("default").optional().build()) .field(fieldName2, Schema.INT32_SCHEMA) .build(); final Struct value = new Struct(schema).put(fieldName1, null).put(fieldName2, fieldValue2); final Map<String, Object> props = new HashMap<>(); props.put("schema.name", "foo"); props.put("schema.version", "42"); props.put("replace.null.with.default", replaceNullWithDefault); xform.configure(props); final SinkRecord record = new SinkRecord("", 0, null, null, schema, value, 0); final SinkRecord updatedRecord = xform.apply(record); assertEquals("foo", updatedRecord.valueSchema().name()); assertEquals(42, updatedRecord.valueSchema().version()); // Make sure the struct's schema and fields all point to the new schema assertMatchingSchema((Struct) updatedRecord.value(), updatedRecord.valueSchema()); assertEquals(expectedValue, ((Struct) updatedRecord.value()).getWithoutDefault(fieldName1)); } @Test public void valueSchemaRequired() { final SinkRecord record = new SinkRecord("", 0, null, null, null, 42, 0); assertThrows(DataException.class, () -> xform.apply(record)); } @Test public void ignoreRecordWithNullValue() { final SinkRecord record = new SinkRecord("", 0, null, null, null, null, 0); final SinkRecord updatedRecord = xform.apply(record); assertNull(updatedRecord.key()); assertNull(updatedRecord.keySchema()); assertNull(updatedRecord.value()); assertNull(updatedRecord.valueSchema()); } @Test public void updateSchemaOfStruct() { final String fieldName1 = "f1"; final String fieldName2 = "f2"; final String fieldValue1 = "value1"; final int fieldValue2 = 1; final Schema schema = SchemaBuilder.struct() .name("my.orig.SchemaDefn") .field(fieldName1, Schema.STRING_SCHEMA) .field(fieldName2, Schema.INT32_SCHEMA) .build(); final Struct value = new Struct(schema).put(fieldName1, fieldValue1).put(fieldName2, fieldValue2); final Schema newSchema = SchemaBuilder.struct() .name("my.updated.SchemaDefn") .field(fieldName1, Schema.STRING_SCHEMA) .field(fieldName2, Schema.INT32_SCHEMA) .build(); Struct newValue = (Struct) xform.updateSchemaIn(value, newSchema); assertMatchingSchema(newValue, newSchema); } @Test public void updateSchemaOfNonStruct() { Object value = 1; Object updatedValue = xform.updateSchemaIn(value, Schema.INT32_SCHEMA); assertSame(value, updatedValue); } @Test public void updateSchemaOfNull() { Object updatedValue = xform.updateSchemaIn(null, Schema.INT32_SCHEMA); assertNull(updatedValue); } @Test public void testSchemaMetadataVersionRetrievedFromAppInfoParser() { assertEquals(AppInfoParser.getVersion(), xform.version()); } protected void assertMatchingSchema(Struct value, Schema schema) { assertSame(schema, value.schema()); assertEquals(schema.name(), value.schema().name()); for (Field field : schema.fields()) { String fieldName = field.name(); assertEquals(schema.field(fieldName).name(), value.schema().field(fieldName).name()); assertEquals(schema.field(fieldName).index(), value.schema().field(fieldName).index()); assertSame(schema.field(fieldName).schema(), value.schema().field(fieldName).schema()); } } }
SetSchemaMetadataTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/rest/LoggingChunkedRestResponseBodyPart.java
{ "start": 771, "end": 2061 }
class ____ implements ChunkedRestResponseBodyPart { private final ChunkedRestResponseBodyPart inner; private final OutputStream loggerStream; public LoggingChunkedRestResponseBodyPart(ChunkedRestResponseBodyPart inner, OutputStream loggerStream) { this.inner = inner; this.loggerStream = loggerStream; } @Override public boolean isPartComplete() { return inner.isPartComplete(); } @Override public boolean isLastPart() { return inner.isLastPart(); } @Override public void getNextPart(ActionListener<ChunkedRestResponseBodyPart> listener) { inner.getNextPart(listener.map(continuation -> new LoggingChunkedRestResponseBodyPart(continuation, loggerStream))); } @Override public ReleasableBytesReference encodeChunk(int sizeHint, Recycler<BytesRef> recycler) throws IOException { var chunk = inner.encodeChunk(sizeHint, recycler); try { chunk.writeTo(loggerStream); } catch (Exception e) { assert false : e; // nothing really to go wrong here } return chunk; } @Override public String getResponseContentTypeString() { return inner.getResponseContentTypeString(); } }
LoggingChunkedRestResponseBodyPart
java
apache__avro
lang/java/ipc/src/test/java/org/apache/avro/io/Perf.java
{ "start": 56057, "end": 57315 }
class ____ extends BasicTest { GenericRecord[] sourceData = null; Schema writeSchema; private static String mkSchema(String subschema) { return ("{ \"type\": \"record\", \"name\": \"R\", \"fields\": [\n" + "{ \"name\": \"f\", \"type\": " + subschema + "}\n" + "] }"); } public ResolvingTest(String name, String r, String w) throws IOException { super(name, mkSchema(r)); isWriteTest = false; this.writeSchema = new Schema.Parser().parse(mkSchema(w)); } @Override protected Decoder getDecoder() throws IOException { return new ResolvingDecoder(writeSchema, schema, super.getDecoder()); } @Override void readInternal(Decoder d) throws IOException { GenericDatumReader<Object> reader = new GenericDatumReader<>(schema); for (int i = 0; i < count; i++) { reader.read(null, d); } } @Override void writeInternal(Encoder e) throws IOException { GenericDatumWriter<Object> writer = new GenericDatumWriter<>(writeSchema); for (GenericRecord sourceDatum : sourceData) { writer.write(sourceDatum, e); } } @Override void reset() { sourceData = null; data = null; } } static
ResolvingTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/injection/guice/TypeConverterBindingProcessor.java
{ "start": 1353, "end": 1569 }
class ____ extends AbstractProcessor { TypeConverterBindingProcessor(Errors errors) { super(errors); } /** * Installs default converters for primitives, enums, and
TypeConverterBindingProcessor
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/NullType.java
{ "start": 2772, "end": 3157 }
class ____ supported return !clazz.isPrimitive(); } @Override public Class<?> getDefaultConversion() { return DEFAULT_CONVERSION; } @Override public List<LogicalType> getChildren() { return Collections.emptyList(); } @Override public <R> R accept(LogicalTypeVisitor<R> visitor) { return visitor.visit(this); } }
is
java
quarkusio__quarkus
extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/VolumeItemConfig.java
{ "start": 90, "end": 364 }
interface ____ { /** * The path where the file will be mounted. */ String path(); /** * It must be a value between 0000 and 0777. If not specified, the volume defaultMode will be used. */ @WithDefault("-1") int mode(); }
VolumeItemConfig
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/connector/syncjob/action/DeleteConnectorSyncJobActionTests.java
{ "start": 859, "end": 2247 }
class ____ extends ESTestCase { public void testValidate_WhenConnectorSyncJobIdIsPresent_ExpectNoValidationError() { DeleteConnectorSyncJobAction.Request request = ConnectorSyncJobTestUtils.getRandomDeleteConnectorSyncJobActionRequest(); ActionRequestValidationException exception = request.validate(); assertThat(exception, nullValue()); } public void testValidate_WhenConnectorSyncJobIdIsEmpty_ExpectValidationError() { DeleteConnectorSyncJobAction.Request requestWithMissingConnectorId = new DeleteConnectorSyncJobAction.Request(""); ActionRequestValidationException exception = requestWithMissingConnectorId.validate(); assertThat(exception, notNullValue()); assertThat(exception.getMessage(), containsString(ConnectorSyncJobConstants.EMPTY_CONNECTOR_SYNC_JOB_ID_ERROR_MESSAGE)); } public void testValidate_WhenConnectorSyncJobIdIsNull_ExpectValidationError() { DeleteConnectorSyncJobAction.Request requestWithMissingConnectorId = new DeleteConnectorSyncJobAction.Request(NULL_STRING); ActionRequestValidationException exception = requestWithMissingConnectorId.validate(); assertThat(exception, notNullValue()); assertThat(exception.getMessage(), containsString(ConnectorSyncJobConstants.EMPTY_CONNECTOR_SYNC_JOB_ID_ERROR_MESSAGE)); } }
DeleteConnectorSyncJobActionTests
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafeCheckerTest.java
{ "start": 12955, "end": 13453 }
class ____ { // BUG: Diagnostic contains: final Map<String, String> a = null; } """) .doTest(); } @Test public void deeplyMutableTypeArguments() { compilationHelper .addSourceLines( "Test.java", """ import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.ThreadSafe; import java.util.Map; @ThreadSafe
Test
java
jhy__jsoup
src/test/java11/org/jsoup/integration/HttpClientConnectTest.java
{ "start": 167, "end": 431 }
class ____ extends ConnectTest { @BeforeAll static void useHttpClient() { HttpClientExecutorTest.enableHttpClient(); } @AfterAll static void resetClient() { HttpClientExecutorTest.disableHttpClient(); } }
HttpClientConnectTest
java
apache__flink
flink-core/src/main/java/org/apache/flink/configuration/TaskManagerOptions.java
{ "start": 3216, "end": 3543 }
interface ____ the TaskManager is exposed." + " Because different TaskManagers need different values for this option, usually it is specified in an" + " additional non-shared TaskManager-specific config file."); /** The local address of the network
where
java
google__auto
common/src/main/java/com/google/auto/common/MoreTypes.java
{ "start": 33852, "end": 36133 }
class ____ type parameters, TypeElement#getSuperclass gives // SuperClass<T> rather than SuperClass<Foo>, so use Types#directSupertypes instead. The javadoc // for Types#directSupertypes guarantees that a super class, if it exists, comes before any // interfaces. Thus, we can just get the first element in the list. return Optional.of(asDeclared(types.directSupertypes(type).get(0))); } private static boolean isObjectType(DeclaredType type) { return asTypeElement(type).getQualifiedName().contentEquals("java.lang.Object"); } /** * Resolves a {@link VariableElement} parameter to a method or constructor based on the given * container, or a member of a class. For parameters to a method or constructor, the variable's * enclosing element must be a supertype of the container type. For example, given a {@code * container} of type {@code Set<String>}, and a variable corresponding to the {@code E e} * parameter in the {@code Set.add(E e)} method, this will return a TypeMirror for {@code String}. */ public static TypeMirror asMemberOf( Types types, DeclaredType container, VariableElement variable) { if (variable.getKind().equals(ElementKind.PARAMETER)) { ExecutableElement methodOrConstructor = MoreElements.asExecutable(variable.getEnclosingElement()); ExecutableType resolvedMethodOrConstructor = MoreTypes.asExecutable(types.asMemberOf(container, methodOrConstructor)); List<? extends VariableElement> parameters = methodOrConstructor.getParameters(); List<? extends TypeMirror> parameterTypes = resolvedMethodOrConstructor.getParameterTypes(); checkState(parameters.size() == parameterTypes.size()); for (int i = 0; i < parameters.size(); i++) { // We need to capture the parameter type of the variable we're concerned about, // for later printing. This is the only way to do it since we can't use // types.asMemberOf on variables of methods. if (parameters.get(i).equals(variable)) { return parameterTypes.get(i); } } throw new IllegalStateException("Could not find variable: " + variable); } else { return types.asMemberOf(container, variable); } } private abstract static
has
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inject/dagger/ScopeOnModuleTest.java
{ "start": 1351, "end": 1752 }
class ____ { @Provides @Singleton Object provideObject() { return new Object(); } } """) .addOutputLines( "out/Test.java", """ import dagger.Module; import dagger.Provides; import javax.inject.Singleton; @Module
Test
java
apache__logging-log4j2
log4j-jpa/src/test/java/org/apache/logging/log4j/core/appender/db/jpa/converter/StackTraceElementAttributeConverterTest.java
{ "start": 5910, "end": 6757 }
class ____ is not correct."); assertEquals("testConvert04", reversed.getMethodName(), "The method name is not correct."); assertNull(reversed.getFileName(), "The file name is not correct."); assertEquals(-2, reversed.getLineNumber(), "The line number is not correct."); assertTrue(reversed.isNativeMethod(), "The native flag should be true."); } @Test void testConvertNullToDatabaseColumn() { assertNull(this.converter.convertToDatabaseColumn(null), "The converted value should be null."); } @Test void testConvertNullOrBlankToEntityAttribute() { assertNull(this.converter.convertToEntityAttribute(null), "The converted attribute should be null (1)."); assertNull(this.converter.convertToEntityAttribute(""), "The converted attribute should be null (2)."); } }
name
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/erasurecode/BufferAllocator.java
{ "start": 1453, "end": 2020 }
class ____ extends BufferAllocator { public SimpleBufferAllocator(boolean usingDirect) { super(usingDirect); } @Override public ByteBuffer allocate(int bufferLen) { return isUsingDirect() ? ByteBuffer.allocateDirect(bufferLen) : ByteBuffer.allocate(bufferLen); } } /** * A buffer allocator that allocates a buffer from an existing large buffer by * slice calling, but if no available space just degrades as * SimpleBufferAllocator. So please ensure enough space for it. */ public static
SimpleBufferAllocator
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/Skip.java
{ "start": 1010, "end": 1160 }
interface ____ { /** * Do we have a match to the underlying condition? * * @return True/false ;) */ public boolean isMatch(); }
Matcher
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/action/TransportDeleteExpiredDataAction.java
{ "start": 2782, "end": 13590 }
class ____ extends HandledTransportAction< DeleteExpiredDataAction.Request, DeleteExpiredDataAction.Response> { private static final Logger logger = LogManager.getLogger(TransportDeleteExpiredDataAction.class); private final ThreadPool threadPool; private final Executor executor; private final OriginSettingClient client; private final ClusterService clusterService; private final Clock clock; private final JobConfigProvider jobConfigProvider; private final JobResultsProvider jobResultsProvider; private final AnomalyDetectionAuditor auditor; @Inject public TransportDeleteExpiredDataAction( ThreadPool threadPool, TransportService transportService, ActionFilters actionFilters, Client client, ClusterService clusterService, JobConfigProvider jobConfigProvider, JobResultsProvider jobResultsProvider, AnomalyDetectionAuditor auditor ) { this( threadPool, threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME), transportService, actionFilters, client, clusterService, jobConfigProvider, jobResultsProvider, auditor, Clock.systemUTC() ); } TransportDeleteExpiredDataAction( ThreadPool threadPool, Executor executor, TransportService transportService, ActionFilters actionFilters, Client client, ClusterService clusterService, JobConfigProvider jobConfigProvider, JobResultsProvider jobResultsProvider, AnomalyDetectionAuditor auditor, Clock clock ) { super(DeleteExpiredDataAction.NAME, transportService, actionFilters, DeleteExpiredDataAction.Request::new, executor); this.threadPool = threadPool; this.executor = executor; this.client = new OriginSettingClient(client, ClientHelper.ML_ORIGIN); this.clusterService = clusterService; this.clock = clock; this.jobConfigProvider = jobConfigProvider; this.jobResultsProvider = jobResultsProvider; this.auditor = auditor; } @Override protected void doExecute( Task task, DeleteExpiredDataAction.Request request, ActionListener<DeleteExpiredDataAction.Response> listener ) { logger.info("Deleting expired data"); Instant timeoutTime = Instant.now(clock) .plus( request.getTimeout() == null ? Duration.ofMillis(MlDataRemover.DEFAULT_MAX_DURATION.getMillis()) : Duration.ofMillis(request.getTimeout().millis()) ); TaskId taskId = new TaskId(clusterService.localNode().getId(), task.getId()); BooleanSupplier isTimedOutSupplier = () -> Instant.now(clock).isAfter(timeoutTime); if (Strings.isNullOrEmpty(request.getJobId()) || Strings.isAllOrWildcard(request.getJobId())) { List<MlDataRemover> dataRemovers = createDataRemovers(client, taskId, auditor); threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME) .execute(ActionRunnable.wrap(listener, l -> deleteExpiredData(request, dataRemovers, l, isTimedOutSupplier))); } else { jobConfigProvider.expandJobs( request.getJobId(), false, true, null, listener.delegateFailureAndWrap( (delegate, jobBuilders) -> threadPool.executor(MachineLearning.UTILITY_THREAD_POOL_NAME) .execute(ActionRunnable.wrap(delegate, l -> { List<Job> jobs = jobBuilders.stream().map(Job.Builder::build).collect(Collectors.toList()); String[] jobIds = jobs.stream().map(Job::getId).toArray(String[]::new); request.setExpandedJobIds(jobIds); List<MlDataRemover> dataRemovers = createDataRemovers(jobs, taskId, auditor); deleteExpiredData(request, dataRemovers, l, isTimedOutSupplier); })) ) ); } } private void deleteExpiredData( DeleteExpiredDataAction.Request request, List<MlDataRemover> dataRemovers, ActionListener<DeleteExpiredDataAction.Response> listener, BooleanSupplier isTimedOutSupplier ) { Iterator<MlDataRemover> dataRemoversIterator = new VolatileCursorIterator<>(dataRemovers); // If there is no throttle provided, default to none float requestsPerSec = request.getRequestsPerSecond() == null ? Float.POSITIVE_INFINITY : request.getRequestsPerSecond(); int numberOfDatanodes = Math.max(clusterService.state().getNodes().getDataNodes().size(), 1); if (requestsPerSec == -1.0f) { // With DEFAULT_SCROLL_SIZE = 1000 and a single data node this implies we spread deletion of // 1 million documents over 5000 seconds ~= 83 minutes. // If we have > 5 data nodes, we don't set our throttling. requestsPerSec = numberOfDatanodes < 5 ? (float) (AbstractBulkByScrollRequest.DEFAULT_SCROLL_SIZE / 5) * numberOfDatanodes : Float.POSITIVE_INFINITY; } deleteExpiredData(request, dataRemoversIterator, requestsPerSec, listener, isTimedOutSupplier, true); } void deleteExpiredData( DeleteExpiredDataAction.Request request, Iterator<MlDataRemover> mlDataRemoversIterator, float requestsPerSecond, ActionListener<DeleteExpiredDataAction.Response> listener, BooleanSupplier isTimedOutSupplier, boolean haveAllPreviousDeletionsCompleted ) { if (haveAllPreviousDeletionsCompleted && mlDataRemoversIterator.hasNext()) { MlDataRemover remover = mlDataRemoversIterator.next(); ActionListener<Boolean> nextListener = listener.delegateFailureAndWrap( (delegate, booleanResponse) -> deleteExpiredData( request, mlDataRemoversIterator, requestsPerSecond, delegate, isTimedOutSupplier, booleanResponse ) ); // Removing expired ML data and artifacts requires multiple operations. // These are queued up and executed sequentially in the action listener, // the chained calls must all run the ML utility thread pool NOT the thread // the previous action returned in which in the case of a transport_client_boss // thread is a disaster. remover.remove(requestsPerSecond, new ThreadedActionListener<>(executor, nextListener), isTimedOutSupplier); } else { if (haveAllPreviousDeletionsCompleted) { logger.info("Completed deletion of expired ML data"); } else { if (isTimedOutSupplier.getAsBoolean()) { TimeValue timeoutPeriod = request.getTimeout() == null ? MlDataRemover.DEFAULT_MAX_DURATION : request.getTimeout(); String msg = "Deleting expired ML data was cancelled after the timeout period of [" + timeoutPeriod + "] was exceeded. The setting [xpack.ml.nightly_maintenance_requests_per_second] " + "controls the deletion rate, consider increasing the value to assist in pruning old data"; logger.warn(msg); if (Strings.isNullOrEmpty(request.getJobId()) || Strings.isAllOrWildcard(request.getJobId()) || request.getExpandedJobIds() == null) { auditor.warning(AbstractAuditor.All_RESOURCES_ID, msg); } else { for (String jobId : request.getExpandedJobIds()) { auditor.warning(jobId, msg); } } } else { logger.info("Halted deletion of expired ML data until next invocation"); } } listener.onResponse(new DeleteExpiredDataAction.Response(haveAllPreviousDeletionsCompleted)); } } private List<MlDataRemover> createDataRemovers( OriginSettingClient originClient, TaskId parentTaskId, AnomalyDetectionAuditor anomalyDetectionAuditor ) { return Arrays.asList( new ExpiredResultsRemover( originClient, new WrappedBatchedJobsIterator(new SearchAfterJobsIterator(originClient)), parentTaskId, anomalyDetectionAuditor, threadPool ), new ExpiredForecastsRemover(originClient, threadPool, parentTaskId), new ExpiredModelSnapshotsRemover( originClient, new WrappedBatchedJobsIterator(new SearchAfterJobsIterator(originClient)), parentTaskId, threadPool, jobResultsProvider, anomalyDetectionAuditor ), new UnusedStateRemover(originClient, parentTaskId), new EmptyStateIndexRemover(originClient, parentTaskId), new UnusedStatsRemover(originClient, parentTaskId), new ExpiredAnnotationsRemover( originClient, new WrappedBatchedJobsIterator(new SearchAfterJobsIterator(originClient)), parentTaskId, anomalyDetectionAuditor, threadPool ) ); } private List<MlDataRemover> createDataRemovers(List<Job> jobs, TaskId parentTaskId, AnomalyDetectionAuditor anomalyDetectionAuditor) { return Arrays.asList( new ExpiredResultsRemover(client, new VolatileCursorIterator<>(jobs), parentTaskId, anomalyDetectionAuditor, threadPool), new ExpiredForecastsRemover(client, threadPool, parentTaskId), new ExpiredModelSnapshotsRemover( client, new VolatileCursorIterator<>(jobs), parentTaskId, threadPool, jobResultsProvider, anomalyDetectionAuditor ), new UnusedStateRemover(client, parentTaskId), new EmptyStateIndexRemover(client, parentTaskId), new UnusedStatsRemover(client, parentTaskId), new ExpiredAnnotationsRemover(client, new VolatileCursorIterator<>(jobs), parentTaskId, anomalyDetectionAuditor, threadPool) ); } }
TransportDeleteExpiredDataAction
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/resolver/order/AvailableSpaceResolver.java
{ "start": 2182, "end": 5420 }
class ____ extends RouterResolver<String, SubclusterAvailableSpace> { private static final Logger LOG = LoggerFactory .getLogger(AvailableSpaceResolver.class); /** Increases chance of files on subcluster with more available space. */ public static final String BALANCER_PREFERENCE_KEY = RBFConfigKeys.FEDERATION_ROUTER_PREFIX + "available-space-resolver.balanced-space-preference-fraction"; public static final float BALANCER_PREFERENCE_DEFAULT = 0.6f; /** Random instance used in the subcluster comparison. */ private static final Random RAND = new Random(); /** Customized comparator for SubclusterAvailableSpace. */ private SubclusterSpaceComparator comparator; public AvailableSpaceResolver(final Configuration conf, final Router routerService) { super(conf, routerService); float balancedPreference = conf.getFloat(BALANCER_PREFERENCE_KEY, BALANCER_PREFERENCE_DEFAULT); if (balancedPreference < 0.5) { LOG.warn("The balancer preference value is less than 0.5. That means more" + " files will be allocated in cluster with lower available space."); } this.comparator = new SubclusterSpaceComparator(balancedPreference); } /** * Get the mapping from NamespaceId to subcluster space info. It gets this * mapping from the subclusters through expensive calls (e.g., RPC) and uses * caching to avoid too many calls. The cache might be updated asynchronously * to reduce latency. * * @return NamespaceId to {@link SubclusterAvailableSpace}. */ @Override protected Map<String, SubclusterAvailableSpace> getSubclusterInfo( MembershipStore membershipStore) { Map<String, SubclusterAvailableSpace> mapping = new HashMap<>(); try { // Get the Namenode's available space info from the subclusters // from the Membership store. GetNamenodeRegistrationsRequest request = GetNamenodeRegistrationsRequest .newInstance(); GetNamenodeRegistrationsResponse response = membershipStore .getNamenodeRegistrations(request); final List<MembershipState> nns = response.getNamenodeMemberships(); for (MembershipState nn : nns) { try { String nsId = nn.getNameserviceId(); long availableSpace = nn.getStats().getAvailableSpace(); mapping.put(nsId, new SubclusterAvailableSpace(nsId, availableSpace)); } catch (Exception e) { LOG.error("Cannot get stats info for {}: {}.", nn, e.getMessage()); } } } catch (IOException ioe) { LOG.error("Cannot get Namenodes from the State Store.", ioe); } return mapping; } @Override protected String chooseFirstNamespace(String path, PathLocation loc) { Map<String, SubclusterAvailableSpace> subclusterInfo = getSubclusterMapping(); List<SubclusterAvailableSpace> subclusterList = new LinkedList<>(); for (RemoteLocation dest : loc.getDestinations()) { subclusterList.add(subclusterInfo.get(dest.getNameserviceId())); } Collections.sort(subclusterList, comparator); return subclusterList.size() > 0 ? subclusterList.get(0).getNameserviceId() : null; } /** * Inner
AvailableSpaceResolver
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/apidiff/Java8ApiChecker.java
{ "start": 1625, "end": 1672 }
class ____", severity = ERROR) public
libraries
java
apache__camel
core/camel-main/src/test/java/org/apache/camel/main/MainIoCBeanConfigInjectPropertiesTest.java
{ "start": 2396, "end": 2927 }
class ____ extends RouteBuilder { @BindToRegistry("bar") public MyBar createBar(@BeanConfigInject("bar") Properties config) { assertEquals(2, config.size()); assertNull(config.get("foo")); String text = config.getProperty("Name") + " (minimum age: " + config.getProperty("AGE") + ")"; return new MyBar(text); } @Override public void configure() { from("direct:start").bean("bar").to("mock:results"); } } }
MyRouteBuilder
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/TypeNameShadowingTest.java
{ "start": 2961, "end": 3078 }
class ____ { // BUG: Diagnostic contains: Type parameter T shadows visible type foo.bar.T
Foo
java
apache__maven
compat/maven-model/src/test/java/org/apache/maven/model/PluginContainerTest.java
{ "start": 1104, "end": 1692 }
class ____ { @Test void testHashCodeNullSafe() { new PluginContainer().hashCode(); } @Test void testEqualsNullSafe() { assertFalse(new PluginContainer().equals(null)); new PluginContainer().equals(new PluginContainer()); } @Test void testEqualsIdentity() { PluginContainer thing = new PluginContainer(); assertTrue(thing.equals(thing), "Expected " + thing + " to equal " + thing); } @Test void testToStringNullSafe() { assertNotNull(new PluginContainer().toString()); } }
PluginContainerTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/idgenerator/SequenceGeneratorsTest.java
{ "start": 1486, "end": 2720 }
class ____ { @Test public void testSequenceIsGenerated( DomainModelScope modelScope, @TempDir File tmpDir) throws Exception { final var scriptFile = new File( tmpDir, "update_script.sql" ); final var metadata = modelScope.getDomainModel(); metadata.orderColumns( false ); metadata.validate(); new SchemaExport() .setOutputFile( scriptFile.getAbsolutePath() ) .create( EnumSet.of( TargetType.SCRIPT ), metadata ); var commands = Files.readAllLines( scriptFile.toPath() ); MatcherAssert.assertThat( isCommandGenerated( commands, "CREATE TABLE TEST_ENTITY \\(ID .*, PRIMARY KEY \\(ID\\)\\);" ), is( true ) ); MatcherAssert.assertThat( isCommandGenerated( commands, "CREATE SEQUENCE SEQUENCE_GENERATOR START WITH 5 INCREMENT BY 3;" ), is( true ) ); } private boolean isCommandGenerated(List<String> commands, String expectedCommnad) { final Pattern pattern = Pattern.compile( expectedCommnad.toLowerCase() ); for ( String command : commands ) { Matcher matcher = pattern.matcher( command.toLowerCase() ); if ( matcher.matches() ) { return true; } } return false; } @Entity(name = "TestEntity") @Table(name = "TEST_ENTITY") public static
SequenceGeneratorsTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/assumptions/BDDAssumptionsTest.java
{ "start": 7511, "end": 7903 }
class ____ { private final int[] actual = { 1, 2 }; @Test void should_run_test_when_assumption_passes() { thenCode(() -> given(actual).contains(1)).doesNotThrowAnyException(); } @Test void should_ignore_test_when_assumption_fails() { expectAssumptionNotMetException(() -> given(actual).contains(0)); } } @Nested
BDDAssumptions_given_int_array_Test
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/AbstractStyleNameConverter.java
{ "start": 7520, "end": 8415 }
class ____ extends AbstractStyleNameConverter { /** Magenta */ protected static final String NAME = "magenta"; /** * Constructs the converter. This constructor must be public. * * @param formatters The PatternFormatters to generate the text to manipulate. * @param styling The styling that should encapsulate the pattern. */ public Magenta(final List<PatternFormatter> formatters, final String styling) { super(NAME, formatters, styling); } /** * Gets an instance of the class (called via reflection). * * @param config The current Configuration. * @param options The pattern options, may be null. If the first element is "short", only the first line of the * throwable will be formatted. * @return new instance of
Magenta
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/composite/InternalComposite.java
{ "start": 12943, "end": 22426 }
class ____ extends InternalMultiBucketAggregation.InternalBucketWritable implements CompositeAggregation.Bucket { private final CompositeKey key; private final long docCount; private final InternalAggregations aggregations; private final transient List<String> sourceNames; private final transient List<DocValueFormat> formats; InternalBucket( List<String> sourceNames, List<DocValueFormat> formats, CompositeKey key, long docCount, InternalAggregations aggregations ) { this.key = key; this.docCount = docCount; this.aggregations = aggregations; this.sourceNames = sourceNames; this.formats = formats; } InternalBucket(StreamInput in, List<String> sourceNames, List<DocValueFormat> formats) throws IOException { this.key = new CompositeKey(in); this.docCount = in.readVLong(); this.aggregations = InternalAggregations.readFrom(in); this.sourceNames = sourceNames; this.formats = formats; } @Override public void writeTo(StreamOutput out) throws IOException { key.writeTo(out); out.writeVLong(docCount); aggregations.writeTo(out); } @Override public int hashCode() { return Objects.hash(getClass(), docCount, key, aggregations); } @Override public boolean equals(Object obj) { if (obj == null || getClass() != obj.getClass()) { return false; } InternalBucket that = (InternalBucket) obj; return Objects.equals(docCount, that.docCount) && Objects.equals(key, that.key) && Objects.equals(aggregations, that.aggregations); } @Override public Map<String, Object> getKey() { // returns the formatted key in a map return new ArrayMap(sourceNames, formats, key.values()); } // get the raw key (without formatting to preserve the natural order). // visible for testing CompositeKey getRawKey() { return key; } @Override public String getKeyAsString() { StringBuilder builder = new StringBuilder(); builder.append('{'); for (int i = 0; i < key.size(); i++) { if (i > 0) { builder.append(", "); } builder.append(sourceNames.get(i)); builder.append('='); builder.append(formatObject(key.get(i), formats.get(i))); } builder.append('}'); return builder.toString(); } @Override public long getDocCount() { return docCount; } @Override public InternalAggregations getAggregations() { return aggregations; } /** * The formats used when writing the keys. Package private for testing. */ List<DocValueFormat> getFormats() { return formats; } int compareKey(InternalBucket other, int[] reverseMuls, MissingOrder[] missingOrders) { for (int i = 0; i < key.size(); i++) { if (key.get(i) == null) { if (other.key.get(i) == null) { continue; } return -1 * missingOrders[i].compareAnyValueToMissing(reverseMuls[i]); } else if (other.key.get(i) == null) { return missingOrders[i].compareAnyValueToMissing(reverseMuls[i]); } assert key.get(i).getClass() == other.key.get(i).getClass(); @SuppressWarnings("unchecked") int cmp = key.get(i).compareTo(other.key.get(i)) * reverseMuls[i]; if (cmp != 0) { return cmp; } } return 0; } InternalBucket finalizeSampling(SamplingContext samplingContext) { return new InternalBucket( sourceNames, formats, key, samplingContext.scaleUp(docCount), InternalAggregations.finalizeSampling(aggregations, samplingContext) ); } } /** * Format <code>obj</code> using the provided {@link DocValueFormat}. * If the format is equals to {@link DocValueFormat#RAW}, the object is returned as is * for numbers and a string for {@link BytesRef}s. * * This method will then attempt to parse the formatted value using the specified format, * and throw an IllegalArgumentException if parsing fails. This in turn prevents us from * returning an after_key which we can't subsequently parse into the original value. */ static Object formatObject(Object obj, DocValueFormat format) { if (obj == null) { return null; } Object formatted = obj; Object parsed; if (obj.getClass() == BytesRef.class && format == DocValueFormat.TIME_SERIES_ID) { BytesRef value = (BytesRef) obj; // NOTE: formatting a tsid returns a Base64 encoding of the tsid BytesRef which we cannot use to get back the original tsid formatted = format.format(value); parsed = format.parseBytesRef(value); // NOTE: we cannot parse the Base64 encoding representation of the tsid and get back the original BytesRef if (parsed.equals(obj) == false) { throw new IllegalArgumentException( "Format [" + format + "] created output it couldn't parse for value [" + obj + "] " + "of type [" + obj.getClass() + "]. formatted value: [" + formatted + "(" + parsed.getClass() + ")]" ); } } if (obj.getClass() == BytesRef.class && format != DocValueFormat.TIME_SERIES_ID) { BytesRef value = (BytesRef) obj; if (format == DocValueFormat.RAW) { formatted = value.utf8ToString(); } else { formatted = format.format(value); } parsed = format.parseBytesRef(formatted.toString()); if (parsed.equals(obj) == false) { throw new IllegalArgumentException( "Format [" + format + "] created output it couldn't parse for value [" + obj + "] " + "of type [" + obj.getClass() + "]. parsed value: [" + parsed + "(" + parsed.getClass() + ")]" ); } } else if (obj.getClass() == Long.class) { long value = (long) obj; if (format == DocValueFormat.RAW) { formatted = value; } else { formatted = format.format(value); } parsed = format.parseLong(formatted.toString(), false, () -> { throw new UnsupportedOperationException("Using now() is not supported in after keys"); }); if (parsed.equals(((Number) obj).longValue()) == false) { throw new IllegalArgumentException( "Format [" + format + "] created output it couldn't parse for value [" + obj + "] " + "of type [" + obj.getClass() + "]. parsed value: [" + parsed + "(" + parsed.getClass() + ")]" ); } } else if (obj.getClass() == Double.class) { double value = (double) obj; if (format == DocValueFormat.RAW) { formatted = value; } else { formatted = format.format(value); } parsed = format.parseDouble(formatted.toString(), false, () -> { throw new UnsupportedOperationException("Using now() is not supported in after keys"); }); if (parsed.equals(((Number) obj).doubleValue()) == false) { throw new IllegalArgumentException( "Format [" + format + "] created output it couldn't parse for value [" + obj + "] " + "of type [" + obj.getClass() + "]. parsed value: [" + parsed + "(" + parsed.getClass() + ")]" ); } } return formatted; } static
InternalBucket
java
junit-team__junit5
junit-platform-suite-engine/src/main/java/org/junit/platform/suite/engine/SuiteLauncher.java
{ "start": 1345, "end": 2933 }
class ____ { private final EngineExecutionOrchestrator executionOrchestrator = new EngineExecutionOrchestrator(); private final EngineDiscoveryOrchestrator discoveryOrchestrator; static SuiteLauncher create() { Set<TestEngine> engines = new LinkedHashSet<>(); new ServiceLoaderTestEngineRegistry().loadTestEngines().forEach(engines::add); return new SuiteLauncher(engines); } private SuiteLauncher(Set<TestEngine> testEngines) { Preconditions.condition(hasTestEngineOtherThanSuiteEngine(testEngines), () -> "Cannot create SuiteLauncher without at least one other TestEngine; " + "consider adding an engine implementation JAR to the classpath"); this.discoveryOrchestrator = new EngineDiscoveryOrchestrator(testEngines, emptyList()); } private boolean hasTestEngineOtherThanSuiteEngine(Set<TestEngine> testEngines) { return testEngines.stream().anyMatch(testEngine -> !SuiteEngineDescriptor.ENGINE_ID.equals(testEngine.getId())); } LauncherDiscoveryResult discover(LauncherDiscoveryRequest discoveryRequest, UniqueId parentId) { return discoveryOrchestrator.discover(discoveryRequest, parentId); } TestExecutionSummary execute(LauncherDiscoveryResult discoveryResult, EngineExecutionListener executionListener, NamespacedHierarchicalStore<Namespace> requestLevelStore, CancellationToken cancellationToken) { SummaryGeneratingListener listener = new SummaryGeneratingListener(); executionOrchestrator.execute(discoveryResult, executionListener, listener, requestLevelStore, cancellationToken); return listener.getSummary(); } }
SuiteLauncher
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/handlers/VirtualThreadNonBlockingHandler.java
{ "start": 474, "end": 1793 }
class ____ implements ServerRestHandler { private Executor executor; private static volatile ConcurrentHashMap<String, Executor> eventLoops = new ConcurrentHashMap<>(); public VirtualThreadNonBlockingHandler() { } @Override public void handle(ResteasyReactiveRequestContext requestContext) throws Exception { if (BlockingOperationSupport.isBlockingAllowed()) { return; //already dispatched } if (!eventLoops.containsKey(Thread.currentThread().toString())) { var vtf = Class.forName("java.lang.ThreadBuilders").getDeclaredClasses()[0]; Constructor constructor = vtf.getDeclaredConstructors()[0]; constructor.setAccessible(true); ThreadFactory tf = (ThreadFactory) constructor.newInstance( new Object[] { requestContext.getContextExecutor(), "quarkus-virtual-factory", 0, 0, null }); var exec = (Executor) Executors.class.getMethod("newThreadPerTaskExecutor", ThreadFactory.class) .invoke(this, tf); eventLoops.put(Thread.currentThread().toString(), exec); } requestContext.suspend(); requestContext.resume(eventLoops.get(Thread.currentThread().toString())); } }
VirtualThreadNonBlockingHandler
java
apache__hadoop
hadoop-common-project/hadoop-minikdc/src/main/java/org/apache/hadoop/minikdc/MiniKdc.java
{ "start": 2628, "end": 14621 }
class ____ { public static final String JAVA_SECURITY_KRB5_CONF = "java.security.krb5.conf"; public static final String SUN_SECURITY_KRB5_DEBUG = "sun.security.krb5.debug"; public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("Arguments: <WORKDIR> <MINIKDCPROPERTIES> " + "<KEYTABFILE> [<PRINCIPALS>]+"); System.exit(1); } File workDir = new File(args[0]); if (!workDir.exists()) { throw new RuntimeException("Specified work directory does not exists: " + workDir.getAbsolutePath()); } Properties conf = createConf(); File file = new File(args[1]); if (!file.exists()) { throw new RuntimeException("Specified configuration does not exists: " + file.getAbsolutePath()); } Properties userConf = new Properties(); InputStreamReader r = null; try { r = new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8); userConf.load(r); } finally { if (r != null) { r.close(); } } for (Map.Entry<?, ?> entry : userConf.entrySet()) { conf.put(entry.getKey(), entry.getValue()); } final MiniKdc miniKdc = new MiniKdc(conf, workDir); miniKdc.start(); File krb5conf = new File(workDir, "krb5.conf"); if (miniKdc.getKrb5conf().renameTo(krb5conf)) { File keytabFile = new File(args[2]).getAbsoluteFile(); String[] principals = new String[args.length - 3]; System.arraycopy(args, 3, principals, 0, args.length - 3); miniKdc.createPrincipal(keytabFile, principals); System.out.println(); System.out.println("Standalone MiniKdc Running"); System.out.println("---------------------------------------------------"); System.out.println(" Realm : " + miniKdc.getRealm()); System.out.println(" Running at : " + miniKdc.getHost() + ":" + miniKdc.getHost()); System.out.println(" krb5conf : " + krb5conf); System.out.println(); System.out.println(" created keytab : " + keytabFile); System.out.println(" with principals : " + Arrays.asList(principals)); System.out.println(); System.out.println(" Do <CTRL-C> or kill <PID> to stop it"); System.out.println("---------------------------------------------------"); System.out.println(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { miniKdc.stop(); } }); } else { throw new RuntimeException("Cannot rename KDC's krb5conf to " + krb5conf.getAbsolutePath()); } } private static final Logger LOG = LoggerFactory.getLogger(MiniKdc.class); public static final String ORG_NAME = "org.name"; public static final String ORG_DOMAIN = "org.domain"; public static final String KDC_BIND_ADDRESS = "kdc.bind.address"; public static final String KDC_PORT = "kdc.port"; public static final String INSTANCE = "instance"; public static final String MAX_TICKET_LIFETIME = "max.ticket.lifetime"; public static final String MIN_TICKET_LIFETIME = "min.ticket.lifetime"; public static final String MAX_RENEWABLE_LIFETIME = "max.renewable.lifetime"; public static final String TRANSPORT = "transport"; public static final String DEBUG = "debug"; private static final Set<String> PROPERTIES = new HashSet<String>(); private static final Properties DEFAULT_CONFIG = new Properties(); static { PROPERTIES.add(ORG_NAME); PROPERTIES.add(ORG_DOMAIN); PROPERTIES.add(KDC_BIND_ADDRESS); PROPERTIES.add(KDC_BIND_ADDRESS); PROPERTIES.add(KDC_PORT); PROPERTIES.add(INSTANCE); PROPERTIES.add(TRANSPORT); PROPERTIES.add(MAX_TICKET_LIFETIME); PROPERTIES.add(MAX_RENEWABLE_LIFETIME); DEFAULT_CONFIG.setProperty(KDC_BIND_ADDRESS, "localhost"); DEFAULT_CONFIG.setProperty(KDC_PORT, "0"); DEFAULT_CONFIG.setProperty(INSTANCE, "DefaultKrbServer"); DEFAULT_CONFIG.setProperty(ORG_NAME, "EXAMPLE"); DEFAULT_CONFIG.setProperty(ORG_DOMAIN, "COM"); DEFAULT_CONFIG.setProperty(TRANSPORT, "TCP"); DEFAULT_CONFIG.setProperty(MAX_TICKET_LIFETIME, "86400000"); DEFAULT_CONFIG.setProperty(MAX_RENEWABLE_LIFETIME, "604800000"); DEFAULT_CONFIG.setProperty(DEBUG, "false"); } /** * Convenience method that returns MiniKdc default configuration. * <p> * The returned configuration is a copy, it can be customized before using * it to create a MiniKdc. * @return a MiniKdc default configuration. */ public static Properties createConf() { return (Properties) DEFAULT_CONFIG.clone(); } private Properties conf; private SimpleKdcServer simpleKdc; private int port; private String realm; private File workDir; private File krb5conf; private String transport; private boolean krb5Debug; public void setTransport(String transport) { this.transport = transport; } /** * Creates a MiniKdc. * * @param conf MiniKdc configuration. * @param workDir working directory, it should be the build directory. Under * this directory an ApacheDS working directory will be created, this * directory will be deleted when the MiniKdc stops. * @throws Exception thrown if the MiniKdc could not be created. */ public MiniKdc(Properties conf, File workDir) throws Exception { if (!conf.keySet().containsAll(PROPERTIES)) { Set<String> missingProperties = new HashSet<String>(PROPERTIES); missingProperties.removeAll(conf.keySet()); throw new IllegalArgumentException("Missing configuration properties: " + missingProperties); } this.workDir = new File(workDir, Long.toString(System.currentTimeMillis())); if (!this.workDir.exists() && !this.workDir.mkdirs()) { throw new RuntimeException("Cannot create directory " + this.workDir); } LOG.info("Configuration:"); LOG.info("---------------------------------------------------------------"); for (Map.Entry<?, ?> entry : conf.entrySet()) { LOG.info(" {}: {}", entry.getKey(), entry.getValue()); } LOG.info("---------------------------------------------------------------"); this.conf = conf; port = Integer.parseInt(conf.getProperty(KDC_PORT)); String orgName= conf.getProperty(ORG_NAME); String orgDomain = conf.getProperty(ORG_DOMAIN); realm = orgName.toUpperCase(Locale.ENGLISH) + "." + orgDomain.toUpperCase(Locale.ENGLISH); } /** * Returns the port of the MiniKdc. * * @return the port of the MiniKdc. */ public int getPort() { return port; } /** * Returns the host of the MiniKdc. * * @return the host of the MiniKdc. */ public String getHost() { return conf.getProperty(KDC_BIND_ADDRESS); } /** * Returns the realm of the MiniKdc. * * @return the realm of the MiniKdc. */ public String getRealm() { return realm; } public File getKrb5conf() { krb5conf = new File(System.getProperty(JAVA_SECURITY_KRB5_CONF)); return krb5conf; } /** * Starts the MiniKdc. * * @throws Exception thrown if the MiniKdc could not be started. */ public synchronized void start() throws Exception { if (simpleKdc != null) { throw new RuntimeException("Already started"); } simpleKdc = new SimpleKdcServer(); prepareKdcServer(); simpleKdc.init(); resetDefaultRealm(); simpleKdc.start(); LOG.info("MiniKdc started."); } private void resetDefaultRealm() throws IOException { InputStream templateResource = new FileInputStream( getKrb5conf().getAbsolutePath()); String content = IOUtil.readInput(templateResource); content = content.replaceAll("default_realm = .*\n", "default_realm = " + getRealm() + "\n"); IOUtil.writeFile(content, getKrb5conf()); } private void prepareKdcServer() throws Exception { // transport simpleKdc.setWorkDir(workDir); simpleKdc.setKdcHost(getHost()); simpleKdc.setKdcRealm(realm); if (transport == null) { transport = conf.getProperty(TRANSPORT); } if (port == 0) { port = NetworkUtil.getServerPort(); } if (transport != null) { if (transport.trim().equals("TCP")) { simpleKdc.setKdcTcpPort(port); simpleKdc.setAllowUdp(false); } else if (transport.trim().equals("UDP")) { simpleKdc.setKdcUdpPort(port); simpleKdc.setAllowTcp(false); } else { throw new IllegalArgumentException("Invalid transport: " + transport); } } else { throw new IllegalArgumentException("Need to set transport!"); } simpleKdc.getKdcConfig().setString(KdcConfigKey.KDC_SERVICE_NAME, conf.getProperty(INSTANCE)); if (conf.getProperty(DEBUG) != null) { krb5Debug = getAndSet(SUN_SECURITY_KRB5_DEBUG, conf.getProperty(DEBUG)); } if (conf.getProperty(MIN_TICKET_LIFETIME) != null) { simpleKdc.getKdcConfig().setLong(KdcConfigKey.MINIMUM_TICKET_LIFETIME, Long.parseLong(conf.getProperty(MIN_TICKET_LIFETIME))); } if (conf.getProperty(MAX_TICKET_LIFETIME) != null) { simpleKdc.getKdcConfig().setLong(KdcConfigKey.MAXIMUM_TICKET_LIFETIME, Long.parseLong(conf.getProperty(MiniKdc.MAX_TICKET_LIFETIME))); } } /** * Stops the MiniKdc */ public synchronized void stop() { if (simpleKdc != null) { try { simpleKdc.stop(); } catch (KrbException e) { e.printStackTrace(); } finally { if(conf.getProperty(DEBUG) != null) { System.setProperty(SUN_SECURITY_KRB5_DEBUG, Boolean.toString(krb5Debug)); } } } delete(workDir); try { // Will be fixed in next Kerby version. Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } LOG.info("MiniKdc stopped."); } private void delete(File f) { if (f.isFile()) { if (! f.delete()) { LOG.warn("WARNING: cannot delete file " + f.getAbsolutePath()); } } else { File[] fileList = f.listFiles(); if (fileList != null) { for (File c : fileList) { delete(c); } } if (! f.delete()) { LOG.warn("WARNING: cannot delete directory " + f.getAbsolutePath()); } } } /** * Creates a principal in the KDC with the specified user and password. * * @param principal principal name, do not include the domain. * @param password password. * @throws Exception thrown if the principal could not be created. */ public synchronized void createPrincipal(String principal, String password) throws Exception { simpleKdc.createPrincipal(principal, password); } /** * Creates multiple principals in the KDC and adds them to a keytab file. * * @param keytabFile keytab file to add the created principals. * @param principals principals to add to the KDC, do not include the domain. * @throws Exception thrown if the principals or the keytab file could not be * created. */ public synchronized void createPrincipal(File keytabFile, String ... principals) throws Exception { simpleKdc.createPrincipals(principals); if (keytabFile.exists() && !keytabFile.delete()) { LOG.error("Failed to delete keytab file: " + keytabFile); } for (String principal : principals) { simpleKdc.getKadmin().exportKeytab(keytabFile, principal); } } /** * Set the System property; return the old value for caching. * * @param sysprop property * @param debug true or false * @return the previous value */ private boolean getAndSet(String sysprop, String debug) { boolean old = Boolean.getBoolean(sysprop); System.setProperty(sysprop, debug); return old; } }
MiniKdc
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/client/HttpStatusCodeException.java
{ "start": 1119, "end": 4287 }
class ____ extends RestClientResponseException { private static final long serialVersionUID = 5696801857651587810L; /** * Construct a new instance with an {@link HttpStatusCode}. * @param statusCode the status code */ protected HttpStatusCodeException(HttpStatusCode statusCode) { this(statusCode, name(statusCode), null, null, null); } private static String name(HttpStatusCode statusCode) { if (statusCode instanceof HttpStatus status) { return status.name(); } else { return ""; } } /** * Construct a new instance with an {@link HttpStatusCode} and status text. * @param statusCode the status code * @param statusText the status text */ protected HttpStatusCodeException(HttpStatusCode statusCode, String statusText) { this(statusCode, statusText, null, null, null); } /** * Construct instance with an {@link HttpStatusCode}, status text, and content. * @param statusCode the status code * @param statusText the status text * @param responseBody the response body content, may be {@code null} * @param responseCharset the response body charset, may be {@code null} * @since 3.0.5 */ protected HttpStatusCodeException(HttpStatusCode statusCode, String statusText, byte @Nullable [] responseBody, @Nullable Charset responseCharset) { this(statusCode, statusText, null, responseBody, responseCharset); } /** * Construct instance with an {@link HttpStatusCode}, status text, content, and * a response charset. * @param statusCode the status code * @param statusText the status text * @param responseHeaders the response headers, may be {@code null} * @param responseBody the response body content, may be {@code null} * @param responseCharset the response body charset, may be {@code null} * @since 3.1.2 */ protected HttpStatusCodeException(HttpStatusCode statusCode, String statusText, @Nullable HttpHeaders responseHeaders, byte @Nullable [] responseBody, @Nullable Charset responseCharset) { this(getMessage(statusCode, statusText), statusCode, statusText, responseHeaders, responseBody, responseCharset); } /** * Construct instance with an {@link HttpStatusCode}, status text, content, and * a response charset. * @param message the exception message * @param statusCode the status code * @param statusText the status text * @param responseHeaders the response headers, may be {@code null} * @param responseBody the response body content, may be {@code null} * @param responseCharset the response body charset, may be {@code null} * @since 5.2.2 */ protected HttpStatusCodeException(String message, HttpStatusCode statusCode, String statusText, @Nullable HttpHeaders responseHeaders, byte @Nullable [] responseBody, @Nullable Charset responseCharset) { super(message, statusCode, statusText, responseHeaders, responseBody, responseCharset); } private static String getMessage(HttpStatusCode statusCode, String statusText) { if (!StringUtils.hasLength(statusText) && statusCode instanceof HttpStatus status) { statusText = status.getReasonPhrase(); } return statusCode.value() + " " + statusText; } }
HttpStatusCodeException
java
quarkusio__quarkus
integration-tests/reactive-messaging-context-propagation/src/test/java/io/quarkus/it/kafka/KafkaContextPropagationTest.java
{ "start": 5717, "end": 8703 }
class ____ { @Test void testNonBlocking() { given().body("rose").post("/flowers/contextual").then().statusCode(204); given().body("peony").post("/flowers/contextual").then().statusCode(204); given().body("daisy").post("/flowers/contextual").then().statusCode(204); } @Test void testNonBlockingUni() { given().body("rose").post("/flowers/contextual/uni").then().statusCode(204); given().body("peony").post("/flowers/contextual/uni").then().statusCode(204); given().body("daisy").post("/flowers/contextual/uni").then().statusCode(204); } @Test void testBlocking() { given().body("rose").post("/flowers/contextual/blocking").then().statusCode(204); given().body("peony").post("/flowers/contextual/blocking").then().statusCode(204); given().body("daisy").post("/flowers/contextual/blocking").then().statusCode(204); } @Test void testBlockingUni() { given().body("rose").post("/flowers/contextual/uni/blocking").then().statusCode(204); given().body("peony").post("/flowers/contextual/uni/blocking").then().statusCode(204); given().body("daisy").post("/flowers/contextual/uni/blocking").then().statusCode(204); } @Test void testBlockingNamed() { given().body("rose").post("/flowers/contextual/blocking-named").then().statusCode(204); given().body("peony").post("/flowers/contextual/blocking-named").then().statusCode(204); given().body("daisy").post("/flowers/contextual/blocking-named").then().statusCode(204); } @Test void testBlockingNamedUni() { given().body("rose").post("/flowers/contextual/uni/blocking-named").then().statusCode(204); given().body("peony").post("/flowers/contextual/uni/blocking-named").then().statusCode(204); given().body("daisy").post("/flowers/contextual/uni/blocking-named").then().statusCode(204); } @Test @EnabledForJreRange(min = JRE.JAVA_21) void testVirtualThread() { given().body("rose").post("/flowers/contextual/virtual-thread").then().statusCode(204); given().body("peony").post("/flowers/contextual/virtual-thread").then().statusCode(204); given().body("daisy").post("/flowers/contextual/virtual-thread").then().statusCode(204); } @Test @EnabledForJreRange(min = JRE.JAVA_21) void testVirtualThreadUni() { given().body("rose").post("/flowers/contextual/uni/virtual-thread").then().statusCode(204); given().body("peony").post("/flowers/contextual/uni/virtual-thread").then().statusCode(204); given().body("daisy").post("/flowers/contextual/uni/virtual-thread").then().statusCode(204); } } @Nested // FlowerMutinyResource
ContextPropagated
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/writing/FrameworkFieldInitializer.java
{ "start": 9249, "end": 9750 }
enum ____ { /** The field is {@code null}. */ UNINITIALIZED, /** * The field's dependencies are being set up. If the field is needed in this state, use a {@link * DelegateFactory}. */ INITIALIZING, /** * The field's dependencies are being set up, but the field can be used because it has already * been set to a {@link DelegateFactory}. */ DELEGATED, /** The field is set to an undelegated factory. */ INITIALIZED; } }
InitializationState