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
alibaba__nacos
common/src/test/java/com/alibaba/nacos/common/utils/PreconditionsTest.java
{ "start": 843, "end": 2665 }
class ____ { private static final String FORMAT = "I ate %s pies."; private static final String ARG = "one"; private static final String ERRORMSG = "A message"; @Test void testCheckArgument2Args1true() { Preconditions.checkArgument(true, ERRORMSG); } @Test void testCheckArgument2Args1false() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(false, ERRORMSG); }); } @Test void testCheckArgument2Args1true2null() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(true, null); }); } @Test void testCheckArgument2Args1false2null() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(false, null); }); } @Test void testCheckArgument3Args1true() { Preconditions.checkArgument(true, ERRORMSG, ARG); } @Test void testCheckArgument3Args1false() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(false, ERRORMSG, ARG); }); } @Test void testCheckArgument3Args1true2null() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(true, null, ARG); }); } @Test void testCheckArgument3Args1false2null() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(false, null, ARG); }); } @Test void testCheckArgument3Args1false3null() { assertThrows(IllegalArgumentException.class, () -> { Preconditions.checkArgument(false, ERRORMSG, null); }); } }
PreconditionsTest
java
spring-projects__spring-framework
spring-webflux/src/test/java/org/springframework/web/reactive/resource/ResourceWebHandlerTests.java
{ "start": 3164, "end": 3648 }
class ____ { private static final Duration TIMEOUT = Duration.ofSeconds(1); private static final ClassPathResource testResource = new ClassPathResource("test/", ResourceWebHandlerTests.class); private static final ClassPathResource testAlternatePathResource = new ClassPathResource("testalternatepath/", ResourceWebHandlerTests.class); private static final ClassPathResource webjarsResource = new ClassPathResource("META-INF/resources/webjars/"); @Nested
ResourceWebHandlerTests
java
quarkusio__quarkus
integration-tests/mtls-certificates/src/test/java/io/quarkus/it/vertx/CertificateRoleCnMappingIT.java
{ "start": 115, "end": 189 }
class ____ extends CertificateRoleCnMappingTest { }
CertificateRoleCnMappingIT
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/SetResetModeAction.java
{ "start": 423, "end": 716 }
class ____ extends ActionType<AcknowledgedResponse> { public static final SetResetModeAction INSTANCE = new SetResetModeAction(); public static final String NAME = "cluster:internal/xpack/ml/reset_mode"; private SetResetModeAction() { super(NAME); } }
SetResetModeAction
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/watcher/actions/throttler/Throttler.java
{ "start": 555, "end": 648 }
interface ____ { Result throttle(String actionId, WatchExecutionContext ctx);
Throttler
java
apache__camel
components/camel-wasm/src/main/java/org/apache/camel/language/wasm/WasmExpression.java
{ "start": 1511, "end": 5108 }
class ____ extends ExpressionAdapter implements ExpressionResultTypeAware { private final String expression; private String module; private String resultTypeName; private Class<?> resultType; private String headerName; private String propertyName; private TypeConverter typeConverter; private WasmFunction function; public WasmExpression(String expression) { this.expression = expression; } @Override public void init(CamelContext camelContext) { super.init(camelContext); if (module == null) { throw new IllegalArgumentException("Module must be configured"); } this.typeConverter = camelContext.getTypeConverter(); if (resultTypeName != null && (resultType == null || resultType == Object.class)) { resultType = camelContext.getClassResolver().resolveClass(resultTypeName); } if (resultType == null || resultType == Object.class) { resultType = byte[].class; } final ResourceLoader rl = PluginHelper.getResourceLoader(camelContext); final Resource res = rl.resolveResource(module); try (InputStream is = res.getInputStream()) { this.function = new WasmFunction(Parser.parse(is), expression); } catch (IOException e) { throw new RuntimeCamelException(e); } } @Override public String getExpressionText() { return this.expression; } @Override public Class<?> getResultType() { return this.resultType; } public void setResultType(Class<?> resultType) { this.resultType = resultType; } public String getResultTypeName() { return resultTypeName; } public void setResultTypeName(String resultTypeName) { this.resultTypeName = resultTypeName; } public String getHeaderName() { return headerName; } /** * Name of the header to use as input instead of the message body. * </p> * It has higher precedence than the propertyName if both are set. */ public void setHeaderName(String headerName) { this.headerName = headerName; } public String getPropertyName() { return propertyName; } /** * Name of the property to use as input instead of the message body. * </p> * It has lower precedence than the headerName if both are set. */ public void setPropertyName(String propertyName) { this.propertyName = propertyName; } public String getModule() { return module; } /** * Set the module (the distributable, loadable, and executable unit of code in WebAssembly) resource that provides * the expression function. */ public void setModule(String module) { this.module = module; } @Override public boolean matches(Exchange exchange) { final Object value = evaluate(exchange, Object.class); if (value instanceof BooleanNode) { return ((BooleanNode) value).asBoolean(); } if (value instanceof Collection) { return !((Collection<?>) value).isEmpty(); } return false; } @Override public Object evaluate(Exchange exchange) { try { byte[] in = WasmSupport.serialize(exchange); byte[] result = function.run(in); return this.typeConverter.convertTo(resultType, exchange, result); } catch (Exception e) { throw new RuntimeCamelException(e); } } }
WasmExpression
java
apache__dubbo
dubbo-common/src/test/java/org/apache/dubbo/common/utils/SerializeSecurityManagerTest.java
{ "start": 919, "end": 6490 }
class ____ { @Test void testPrefix() { TestAllowClassNotifyListener.setCount(0); SerializeSecurityManager ssm = new SerializeSecurityManager(); ssm.registerListener(new TestAllowClassNotifyListener()); ssm.addToAllowed("java.util.HashMap"); ssm.addToAllowed("com.example.DemoInterface"); ssm.addToAllowed("com.sun.Interface1"); ssm.addToAllowed("com.sun.Interface2"); Assertions.assertTrue(ssm.getAllowedPrefix().contains("java.util.HashMap")); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.example.DemoInterface")); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.sun.Interface1")); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.sun.Interface2")); Assertions.assertEquals(ssm.getAllowedPrefix(), TestAllowClassNotifyListener.getAllowedList()); Assertions.assertEquals(7, TestAllowClassNotifyListener.getCount()); ssm.addToDisAllowed("com.sun.Interface"); Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.sun.Interface1")); Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.sun.Interface2")); Assertions.assertEquals(ssm.getDisAllowedPrefix(), TestAllowClassNotifyListener.getDisAllowedList()); Assertions.assertEquals(9, TestAllowClassNotifyListener.getCount()); ssm.addToAllowed("com.sun.Interface3"); Assertions.assertFalse(ssm.getAllowedPrefix().contains("com.sun.Interface3")); Assertions.assertEquals(9, TestAllowClassNotifyListener.getCount()); ssm.addToAllowed("java.util.HashMap"); Assertions.assertEquals(9, TestAllowClassNotifyListener.getCount()); ssm.addToDisAllowed("com.sun.Interface"); Assertions.assertEquals(9, TestAllowClassNotifyListener.getCount()); ssm.addToAlwaysAllowed("com.sun.Interface3"); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.sun.Interface3")); Assertions.assertEquals(10, TestAllowClassNotifyListener.getCount()); ssm.addToAlwaysAllowed("com.sun.Interface3"); Assertions.assertTrue(ssm.getAllowedPrefix().contains("com.sun.Interface3")); Assertions.assertEquals(10, TestAllowClassNotifyListener.getCount()); } @Test void testStatus1() { SerializeSecurityManager ssm = new SerializeSecurityManager(); ssm.registerListener(new TestAllowClassNotifyListener()); Assertions.assertEquals(AllowClassNotifyListener.DEFAULT_STATUS, ssm.getCheckStatus()); Assertions.assertEquals(AllowClassNotifyListener.DEFAULT_STATUS, TestAllowClassNotifyListener.getStatus()); ssm.setCheckStatus(SerializeCheckStatus.STRICT); Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus()); Assertions.assertEquals(SerializeCheckStatus.STRICT, TestAllowClassNotifyListener.getStatus()); ssm.setCheckStatus(SerializeCheckStatus.WARN); Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus()); Assertions.assertEquals(SerializeCheckStatus.WARN, TestAllowClassNotifyListener.getStatus()); ssm.setCheckStatus(SerializeCheckStatus.STRICT); Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus()); Assertions.assertEquals(SerializeCheckStatus.WARN, TestAllowClassNotifyListener.getStatus()); ssm.setCheckStatus(SerializeCheckStatus.DISABLE); Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus()); Assertions.assertEquals(SerializeCheckStatus.DISABLE, TestAllowClassNotifyListener.getStatus()); ssm.setCheckStatus(SerializeCheckStatus.STRICT); Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus()); Assertions.assertEquals(SerializeCheckStatus.DISABLE, TestAllowClassNotifyListener.getStatus()); ssm.setCheckStatus(SerializeCheckStatus.WARN); Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus()); Assertions.assertEquals(SerializeCheckStatus.DISABLE, TestAllowClassNotifyListener.getStatus()); } @Test void testStatus2() { SerializeSecurityManager ssm = new SerializeSecurityManager(); ssm.setCheckStatus(SerializeCheckStatus.STRICT); ssm.registerListener(new TestAllowClassNotifyListener()); Assertions.assertEquals(ssm.getCheckStatus(), TestAllowClassNotifyListener.getStatus()); Assertions.assertEquals(SerializeCheckStatus.STRICT, TestAllowClassNotifyListener.getStatus()); } @Test void testSerializable() { SerializeSecurityManager ssm = new SerializeSecurityManager(); ssm.registerListener(new TestAllowClassNotifyListener()); Assertions.assertTrue(ssm.isCheckSerializable()); Assertions.assertTrue(TestAllowClassNotifyListener.isCheckSerializable()); ssm.setCheckSerializable(true); Assertions.assertTrue(ssm.isCheckSerializable()); Assertions.assertTrue(TestAllowClassNotifyListener.isCheckSerializable()); ssm.setCheckSerializable(false); Assertions.assertFalse(ssm.isCheckSerializable()); Assertions.assertFalse(TestAllowClassNotifyListener.isCheckSerializable()); ssm.setCheckSerializable(true); Assertions.assertFalse(ssm.isCheckSerializable()); Assertions.assertFalse(TestAllowClassNotifyListener.isCheckSerializable()); } }
SerializeSecurityManagerTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/floats/Floats_assertIsNotZero_Test.java
{ "start": 1103, "end": 2259 }
class ____ extends FloatsBaseTest { @Test void should_succeed_since_actual_is_not_zero() { floats.assertIsNotZero(someInfo(), 2.0f); } @Test void should_fail_since_actual_is_zero() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floats.assertIsNotZero(someInfo(), 0.0f)) .withMessage("%nExpecting actual:%n 0.0f%nnot to be equal to:%n 0.0f%n".formatted()); } @Test void should_succeed_since_actual_is_not_zero_whatever_custom_comparison_strategy_is() { floatsWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), 2.0f); } @Test void should_fail_since_actual_is_zero_whatever_custom_comparison_strategy_is() { assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> floatsWithAbsValueComparisonStrategy.assertIsNotZero(someInfo(), 0.0f)) .withMessage("%nExpecting actual:%n 0.0f%nnot to be equal to:%n 0.0f%n".formatted()); } }
Floats_assertIsNotZero_Test
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/config/SpringProduceInjectedSingletonBeanTest.java
{ "start": 1086, "end": 2321 }
class ____ extends SpringTestSupport { @Override protected AbstractXmlApplicationContext createApplicationContext() { return new ClassPathXmlApplicationContext("org/apache/camel/spring/config/SpringProduceInjectedSingletonBeanTest.xml"); } @Test public void testProduceInjectedOnce() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Hello World", "Bye World"); MyProduceBean bean = context.getRegistry().lookupByNameAndType("myProducerBean", MyProduceBean.class); bean.testDoSomething("Hello World"); bean.testDoSomething("Bye World"); assertMockEndpointsSatisfied(); } @Test public void testProduceInjectedTwice() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Hello World", "Bye World"); MyProduceBean bean = context.getRegistry().lookupByNameAndType("myProducerBean", MyProduceBean.class); bean.testDoSomething("Hello World"); MyProduceBean bean2 = context.getRegistry().lookupByNameAndType("myProducerBean", MyProduceBean.class); bean2.testDoSomething("Bye World"); assertMockEndpointsSatisfied(); } }
SpringProduceInjectedSingletonBeanTest
java
quarkusio__quarkus
integration-tests/hibernate-orm-tenancy/connection-resolver-legacy-qualifiers/src/main/java/io/quarkus/it/hibernate/multitenancy/inventory/Plane.java
{ "start": 434, "end": 1565 }
class ____ { private Long id; private String name; public Plane() { } public Plane(Long id, String name) { this.id = id; this.name = name; } @Id @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "plane_iq_seq") public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public int hashCode() { return Objects.hash(id, name); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Plane other = (Plane) obj; return Objects.equals(this.name, other.name) && Objects.equals(this.id, other.id); } @Override public String toString() { return "Plane [id=" + id + ", name=" + name + "]"; } }
Plane
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/JUnit4ClassUsedInJUnit3Test.java
{ "start": 1263, "end": 1845 }
class ____ extends TestCase { public void testName1() { System.out.println("here"); } public void testName2() {} } """) .doTest(); } @Test public void negative_assume_in_junit4() { compilationHelper .addSourceLines( "Foo.java", """ import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import org.junit.Assume; import org.junit.Test; @RunWith(JUnit4.class) public
Foo
java
quarkusio__quarkus
extensions/liquibase/liquibase-mongodb/runtime/src/main/java/io/quarkus/liquibase/mongodb/runtime/LiquibaseMongodbBuildTimeClientConfig.java
{ "start": 259, "end": 527 }
interface ____ { /** * The change log file */ @WithDefault("db/changeLog.xml") String changeLog(); /** * The search path for DirectoryResourceAccessor */ Optional<List<String>> searchPath(); }
LiquibaseMongodbBuildTimeClientConfig
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/main/java/org/elasticsearch/xpack/monitoring/exporter/http/HttpResource.java
{ "start": 874, "end": 970 }
class ____ { /** * The current state of the {@link HttpResource}. */
HttpResource
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/CriteriaRestrictionTest.java
{ "start": 611, "end": 2408 }
class ____ { @JiraKey( "HHH-19572" ) @Test void test(EntityManagerFactoryScope scope) { scope.inTransaction( entityManager -> { Doc doc1 = new Doc(); doc1.title = "Hibernate ORM"; doc1.author = "Gavin King"; doc1.text = "Hibernate ORM is a Java Persistence API implementation"; entityManager.persist( doc1 ); Doc doc2 = new Doc(); doc2.title = "Hibernate ORM"; doc2.author = "Hibernate Team"; doc2.text = "Hibernate ORM is a Jakarta Persistence implementation"; entityManager.persist( doc2 ); } ); scope.inTransaction( entityManager -> { var builder = entityManager.getCriteriaBuilder(); var query = builder.createQuery( Doc.class ); var d = query.from( Doc.class ); // test with list query.where( List.of( builder.like( d.get( "title" ), "Hibernate%" ), builder.equal( d.get( "author" ), "Gavin King" ) ) ); var resultList = entityManager.createQuery( query ).getResultList(); assertEquals( 1, resultList.size() ); assertEquals( "Hibernate ORM is a Java Persistence API implementation", resultList.get( 0 ).text ); } ); scope.inTransaction( entityManager -> { var builder = entityManager.getCriteriaBuilder(); var query = builder.createQuery( Doc.class ); var d = query.from( Doc.class ); // test with varargs query.where( builder.like( d.get( "title" ), "Hibernate%" ), builder.equal( d.get( "author" ), "Hibernate Team" ) ); var resultList = entityManager.createQuery( query ).getResultList(); assertEquals( 1, resultList.size() ); assertEquals( "Hibernate ORM is a Jakarta Persistence implementation", resultList.get( 0 ).text ); } ); } @Entity static
CriteriaRestrictionTest
java
elastic__elasticsearch
x-pack/plugin/security/qa/security-basic/src/javaRestTest/java/org/elasticsearch/xpack/security/QueryRoleIT.java
{ "start": 2186, "end": 32240 }
class ____ extends SecurityInBasicRestTestCase { private static final String READ_SECURITY_USER_AUTH_HEADER = "Basic cmVhZF9zZWN1cml0eV91c2VyOnJlYWQtc2VjdXJpdHktcGFzc3dvcmQ="; @Before public void initialize() { new ReservedRolesStore(); } public void testSimpleQueryAllRoles() throws Exception { createRandomRole(); assertQuery("", 1 + ReservedRolesStore.names().size(), roles -> { // default size is 10 assertThat(roles, iterableWithSize(10)); }); assertQuery( Strings.format(""" {"query":{"match_all":{}},"from":%d}""", 1 + ReservedRolesStore.names().size()), 1 + ReservedRolesStore.names().size(), roles -> assertThat(roles, emptyIterable()) ); } public void testDisallowedFields() throws Exception { if (randomBoolean()) { createRandomRole(); } // query on some disallowed field { Request request = new Request(randomFrom("POST", "GET"), "/_security/_query/role"); request.setOptions(request.getOptions().toBuilder().addHeader(HttpHeaders.AUTHORIZATION, READ_SECURITY_USER_AUTH_HEADER)); request.setJsonEntity(""" {"query":{"prefix":{"password":"whatever"}}}"""); ResponseException e = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(400)); assertThat(e.getMessage(), containsString("Field [password] is not allowed for querying or aggregation")); } // query on the _id field { Request request = new Request(randomFrom("POST", "GET"), "/_security/_query/role"); request.setOptions(request.getOptions().toBuilder().addHeader(HttpHeaders.AUTHORIZATION, READ_SECURITY_USER_AUTH_HEADER)); request.setJsonEntity(""" {"query":{"term":{"_id":"role-test"}}}"""); ResponseException e = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(400)); assertThat(e.getMessage(), containsString("Field [_id] is not allowed for querying or aggregation")); } // sort on disallowed field { Request request = new Request(randomFrom("POST", "GET"), "/_security/_query/role"); request.setOptions(request.getOptions().toBuilder().addHeader(HttpHeaders.AUTHORIZATION, READ_SECURITY_USER_AUTH_HEADER)); request.setJsonEntity(""" {"query":{"bool":{"must_not":[{"wildcard":{"applications.application":"a*9"}}]}},"sort":["api_key_hash"]}"""); ResponseException e = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(400)); assertThat(e.getMessage(), containsString("Field [api_key_hash] is not allowed for querying or aggregation")); } } public void testDisallowedQueryType() throws Exception { if (randomBoolean()) { createRandomRole(); } // query using some disallowed query type { Request request = new Request(randomFrom("POST", "GET"), "/_security/_query/role"); request.setOptions(request.getOptions().toBuilder().addHeader(HttpHeaders.AUTHORIZATION, READ_SECURITY_USER_AUTH_HEADER)); request.setJsonEntity(""" {"query":{"match_phrase":{"description":{"query":"whatever"}}}}"""); ResponseException e = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(400)); assertThat(e.getMessage(), containsString("Query type [match_phrase] is not currently supported in this context")); } // query using some disallowed query type inside the (allowed) boolean query type { Request request = new Request(randomFrom("POST", "GET"), "/_security/_query/role"); request.setOptions(request.getOptions().toBuilder().addHeader(HttpHeaders.AUTHORIZATION, READ_SECURITY_USER_AUTH_HEADER)); request.setJsonEntity(""" {"query":{"bool":{"must_not":[{"more_like_this":{"fields":["description"],"like":"hollywood"}}]}}}"""); ResponseException e = expectThrows(ResponseException.class, () -> client().performRequest(request)); assertThat(e.getResponse().getStatusLine().getStatusCode(), equalTo(400)); assertThat(e.getMessage(), containsString("Query type [more_like_this] is not currently supported in this context")); } } public void testSimpleMetadataSearch() throws Exception { int nroles = randomIntBetween(1, 3); for (int i = 0; i < nroles; i++) { createRandomRole(); } RoleDescriptor matchesOnMetadataValue = createRole( "matchesOnMetadataValue", randomBoolean() ? null : randomAlphaOfLength(8), Map.of("matchSimpleKey", "matchSimpleValue"), randomApplicationPrivileges() ); RoleDescriptor matchesOnMetadataKey = createRole( "matchesOnMetadataKey", randomBoolean() ? null : randomAlphaOfLength(8), Map.of("matchSimpleKey", "other"), randomApplicationPrivileges() ); createRole( "other2", randomBoolean() ? null : randomAlphaOfLength(8), Map.of("other", "matchSimpleValue"), randomApplicationPrivileges() ); waitForMigrationCompletion(adminClient(), SecurityMigrations.ROLE_METADATA_FLATTENED_MIGRATION_VERSION); assertQuery(""" {"query":{"term":{"metadata.matchSimpleKey":"matchSimpleValue"}}}""", 1, roles -> { assertThat(roles, iterableWithSize(1)); assertRoleMap(roles.get(0), matchesOnMetadataValue); }); assertQuery(""" {"query":{"exists":{"field":"metadata.matchSimpleKey"}}}""", 2, roles -> { assertThat(roles, iterableWithSize(2)); roles.sort(Comparator.comparing(o -> ((String) o.get("name")))); assertRoleMap(roles.get(0), matchesOnMetadataKey); assertRoleMap(roles.get(1), matchesOnMetadataValue); }); } public void testSearchMultipleMetadataFields() throws Exception { createRole( "noMetadataRole", randomBoolean() ? null : randomAlphaOfLength(8), randomBoolean() ? null : Map.of(), randomApplicationPrivileges() ); RoleDescriptor role1 = createRole( "1" + randomAlphaOfLength(4), randomBoolean() ? null : randomAlphaOfLength(8), Map.of("simpleField1", "matchThis", "simpleField2", "butNotThis"), randomApplicationPrivileges() ); createRole( "2" + randomAlphaOfLength(4), randomBoolean() ? null : randomAlphaOfLength(8), Map.of("simpleField2", "butNotThis"), randomApplicationPrivileges() ); RoleDescriptor role3 = createRole( "3" + randomAlphaOfLength(4), randomBoolean() ? null : randomAlphaOfLength(8), Map.of("listField1", List.of("matchThis", "butNotThis"), "listField2", List.of("butNotThisToo")), randomApplicationPrivileges() ); createRole( "4" + randomAlphaOfLength(4), randomBoolean() ? null : randomAlphaOfLength(8), Map.of("listField2", List.of("butNotThisToo", "andAlsoNotThis")), randomApplicationPrivileges() ); RoleDescriptor role5 = createRole( "5" + randomAlphaOfLength(4), randomBoolean() ? null : randomAlphaOfLength(8), Map.of("listField1", List.of("maybeThis", List.of("matchThis")), "listField2", List.of("butNotThis")), randomApplicationPrivileges() ); RoleDescriptor role6 = createRole( "6" + randomAlphaOfLength(4), randomBoolean() ? null : randomAlphaOfLength(8), Map.of("mapField1", Map.of("innerField", "matchThis")), randomApplicationPrivileges() ); createRole( "7" + randomAlphaOfLength(4), randomBoolean() ? null : randomAlphaOfLength(8), Map.of("mapField1", Map.of("innerField", "butNotThis")), randomApplicationPrivileges() ); RoleDescriptor role8 = createRole( "8" + randomAlphaOfLength(4), randomBoolean() ? null : randomAlphaOfLength(8), Map.of("mapField1", Map.of("innerField", "butNotThis", "innerField2", Map.of("deeperInnerField", "matchThis"))), randomApplicationPrivileges() ); waitForMigrationCompletion(adminClient(), SecurityMigrations.ROLE_METADATA_FLATTENED_MIGRATION_VERSION); Consumer<List<Map<String, Object>>> matcher = roles -> { assertThat(roles, iterableWithSize(5)); roles.sort(Comparator.comparing(o -> ((String) o.get("name")))); assertRoleMap(roles.get(0), role1); assertRoleMap(roles.get(1), role3); assertRoleMap(roles.get(2), role5); assertRoleMap(roles.get(3), role6); assertRoleMap(roles.get(4), role8); }; assertQuery(""" {"query":{"prefix":{"metadata":"match"}}}""", 5, matcher); assertQuery(""" {"query":{"simple_query_string":{"fields":["meta*"],"query":"matchThis"}}}""", 5, matcher); } @SuppressWarnings("unchecked") public void testSimpleSort() throws IOException { // some other non-matching roles int nOtherRoles = randomIntBetween(1, 5); for (int i = 0; i < nOtherRoles; i++) { createRandomRole(); } // some matching roles (at least 2, for sorting) int nMatchingRoles = randomIntBetween(2, 5); for (int i = 0; i < nMatchingRoles; i++) { ApplicationResourcePrivileges[] applicationResourcePrivileges = randomArray( 1, 5, ApplicationResourcePrivileges[]::new, this::randomApplicationResourcePrivileges ); { int matchingApplicationIndex = randomIntBetween(0, applicationResourcePrivileges.length - 1); // make sure the "application" matches the filter query below ("a*9") applicationResourcePrivileges[matchingApplicationIndex] = RoleDescriptor.ApplicationResourcePrivileges.builder() .application("a" + randomAlphaOfLength(4) + "9") .resources(applicationResourcePrivileges[matchingApplicationIndex].getResources()) .privileges(applicationResourcePrivileges[matchingApplicationIndex].getPrivileges()) .build(); } { int matchingApplicationIndex = randomIntBetween(0, applicationResourcePrivileges.length - 1); int matchingResourcesIndex = randomIntBetween( 0, applicationResourcePrivileges[matchingApplicationIndex].getResources().length - 1 ); // make sure the "resources" matches the terms query below ("99") applicationResourcePrivileges[matchingApplicationIndex] = RoleDescriptor.ApplicationResourcePrivileges.builder() .application(applicationResourcePrivileges[matchingApplicationIndex].getApplication()) .resources(applicationResourcePrivileges[matchingApplicationIndex].getResources()[matchingResourcesIndex] = "99") .privileges(applicationResourcePrivileges[matchingApplicationIndex].getPrivileges()) .build(); } createRole( randomAlphaOfLength(4) + i, randomBoolean() ? null : randomAlphaOfLength(8), randomBoolean() ? null : randomMetadata(), applicationResourcePrivileges ); } assertQuery(""" {"query":{"bool":{"filter":[{"wildcard":{"applications.application":"a*9"}}]}},"sort":["name"]}""", nMatchingRoles, roles -> { assertThat(roles, iterableWithSize(nMatchingRoles)); // assert sorting on name for (int i = 0; i < nMatchingRoles; i++) { assertThat(roles.get(i).get("_sort"), instanceOf(List.class)); assertThat(((List<String>) roles.get(i).get("_sort")), iterableWithSize(1)); assertThat(((List<String>) roles.get(i).get("_sort")).get(0), equalTo(roles.get(i).get("name"))); } // assert the ascending sort order for (int i = 1; i < nMatchingRoles; i++) { int compareNames = roles.get(i - 1).get("name").toString().compareTo(roles.get(i).get("name").toString()); assertThat(compareNames < 0, is(true)); } }); assertQuery( """ {"query":{"bool":{"must":[{"terms":{"applications.resources":["99"]}}]}},"sort":["applications.privileges"]}""", nMatchingRoles, roles -> { assertThat(roles, iterableWithSize(nMatchingRoles)); // assert sorting on best "applications.privileges" for (int i = 0; i < nMatchingRoles; i++) { assertThat(roles.get(i).get("_sort"), instanceOf(List.class)); assertThat(((List<String>) roles.get(i).get("_sort")), iterableWithSize(1)); assertThat(((List<String>) roles.get(i).get("_sort")).get(0), equalTo(getPrivilegeNameUsedForSorting(roles.get(i)))); } // assert the ascending sort order for (int i = 1; i < nMatchingRoles; i++) { int comparePrivileges = getPrivilegeNameUsedForSorting(roles.get(i - 1)).compareTo( getPrivilegeNameUsedForSorting(roles.get(i)) ); assertThat(comparePrivileges < 0, is(true)); } } ); } @SuppressWarnings("unchecked") public void testSortWithPagination() throws IOException { int roleIdx = 0; // some non-matching roles int nOtherRoles = randomIntBetween(0, 5); for (int i = 0; i < nOtherRoles; i++) { createRole( Strings.format("role_%03d", roleIdx++), randomBoolean() ? null : randomDescription(), randomBoolean() ? null : randomMetadata(), randomApplicationPrivileges() ); } // first matching role RoleDescriptor firstMatchingRole = createRole( Strings.format("role_%03d", roleIdx++), "some ZZZZmatchZZZZ descr", randomBoolean() ? null : randomMetadata(), randomApplicationPrivileges() ); nOtherRoles = randomIntBetween(0, 5); for (int i = 0; i < nOtherRoles; i++) { createRole( Strings.format("role_%03d", roleIdx++), randomBoolean() ? null : randomDescription(), randomBoolean() ? null : randomMetadata(), randomApplicationPrivileges() ); } // second matching role RoleDescriptor secondMatchingRole = createRole( Strings.format("role_%03d", roleIdx++), "other ZZZZmatchZZZZ meh", randomBoolean() ? null : randomMetadata(), randomApplicationPrivileges() ); nOtherRoles = randomIntBetween(0, 5); for (int i = 0; i < nOtherRoles; i++) { createRole( Strings.format("role_%03d", roleIdx++), randomBoolean() ? null : randomDescription(), randomBoolean() ? null : randomMetadata(), randomApplicationPrivileges() ); } // third matching role RoleDescriptor thirdMatchingRole = createRole( Strings.format("role_%03d", roleIdx++), "me ZZZZmatchZZZZ go", randomBoolean() ? null : randomMetadata(), randomApplicationPrivileges() ); nOtherRoles = randomIntBetween(0, 5); for (int i = 0; i < nOtherRoles; i++) { createRole( Strings.format("role_%03d", roleIdx++), randomBoolean() ? null : randomDescription(), randomBoolean() ? null : randomMetadata(), randomApplicationPrivileges() ); } String queryTemplate = """ {"query":{"match":{"description":{"query":"ZZZZmatchZZZZ"}}}, "size":1, "sort":[{"name":{"order":"desc"}},{"applications.resources":{"order":"asc"}}] %s }"""; AtomicReference<String> searchAfter = new AtomicReference<>(""); Consumer<Map<String, Object>> searchAfterChain = roleMap -> { assertThat(roleMap.get("_sort"), instanceOf(List.class)); assertThat(((List<String>) roleMap.get("_sort")), iterableWithSize(2)); String firstSortValue = ((List<String>) roleMap.get("_sort")).get(0); assertThat(firstSortValue, equalTo(roleMap.get("name"))); String secondSortValue = ((List<String>) roleMap.get("_sort")).get(1); searchAfter.set( ",\"search_after\":[\"" + firstSortValue + "\"," + (secondSortValue != null ? ("\"" + secondSortValue + "\"") : "null") + "]" ); }; assertQuery(Strings.format(queryTemplate, searchAfter.get()), 3, roles -> { assertThat(roles, iterableWithSize(1)); assertRoleMap(roles.get(0), thirdMatchingRole); searchAfterChain.accept(roles.get(0)); }); assertQuery(Strings.format(queryTemplate, searchAfter.get()), 3, roles -> { assertThat(roles, iterableWithSize(1)); assertRoleMap(roles.get(0), secondMatchingRole); searchAfterChain.accept(roles.get(0)); }); assertQuery(Strings.format(queryTemplate, searchAfter.get()), 3, roles -> { assertThat(roles, iterableWithSize(1)); assertRoleMap(roles.get(0), firstMatchingRole); searchAfterChain.accept(roles.get(0)); }); // no more results assertQuery(Strings.format(queryTemplate, searchAfter.get()), 3, roles -> assertThat(roles, emptyIterable())); } @SuppressWarnings("unchecked") private String getPrivilegeNameUsedForSorting(Map<String, Object> roleMap) { String bestPrivilege = null; List<Map<String, Object>> applications = (List<Map<String, Object>>) roleMap.get("applications"); if (applications == null) { return bestPrivilege; } for (Map<String, Object> application : applications) { List<String> privileges = (List<String>) application.get("privileges"); if (privileges != null) { for (String privilege : privileges) { if (bestPrivilege == null) { bestPrivilege = privilege; } else if (privilege.compareTo(bestPrivilege) < 0) { bestPrivilege = privilege; } } } } return bestPrivilege; } private RoleDescriptor createRandomRole() throws IOException { return createRole( randomUUID(), randomBoolean() ? null : randomDescription(), randomBoolean() ? null : randomMetadata(), randomApplicationPrivileges() ); } private ApplicationResourcePrivileges[] randomApplicationPrivileges() { ApplicationResourcePrivileges[] applicationResourcePrivileges = randomArray( 0, 3, ApplicationResourcePrivileges[]::new, this::randomApplicationResourcePrivileges ); return applicationResourcePrivileges.length == 0 && randomBoolean() ? null : applicationResourcePrivileges; } @SuppressWarnings("unchecked") private RoleDescriptor createRole( String roleName, String description, Map<String, Object> metadata, ApplicationResourcePrivileges... applicationResourcePrivileges ) throws IOException { Request request = new Request("POST", "/_security/role/" + roleName); Map<String, Object> requestMap = new HashMap<>(); if (description != null) { requestMap.put(RoleDescriptor.Fields.DESCRIPTION.getPreferredName(), description); } if (metadata != null) { requestMap.put(RoleDescriptor.Fields.METADATA.getPreferredName(), metadata); } if (applicationResourcePrivileges != null) { requestMap.put(RoleDescriptor.Fields.APPLICATIONS.getPreferredName(), applicationResourcePrivileges); } BytesReference source = BytesReference.bytes(jsonBuilder().map(requestMap)); request.setJsonEntity(source.utf8ToString()); Response response = adminClient().performRequest(request); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertTrue((Boolean) ((Map<String, Object>) responseMap.get("role")).get("created")); return new RoleDescriptor( roleName, null, null, applicationResourcePrivileges, null, null, metadata, null, null, null, null, description ); } static void assertQuery(String body, int total, Consumer<List<Map<String, Object>>> roleVerifier) throws IOException { assertQuery(client(), body, total, roleVerifier); } private static Request queryRoleRequestWithAuth() { Request request = new Request(randomFrom("POST", "GET"), "/_security/_query/role"); request.setOptions(request.getOptions().toBuilder().addHeader(HttpHeaders.AUTHORIZATION, READ_SECURITY_USER_AUTH_HEADER)); return request; } public static void assertQuery(RestClient client, String body, int total, Consumer<List<Map<String, Object>>> roleVerifier) throws IOException { Request request = queryRoleRequestWithAuth(); request.setJsonEntity(body); Response response = client.performRequest(request); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertThat(responseMap.get("total"), is(total)); @SuppressWarnings("unchecked") List<Map<String, Object>> roles = new ArrayList<>((List<Map<String, Object>>) responseMap.get("roles")); assertThat(roles.size(), is(responseMap.get("count"))); roleVerifier.accept(roles); } @SuppressWarnings("unchecked") private void assertRoleMap(Map<String, Object> roleMap, RoleDescriptor roleDescriptor) { assertThat(roleMap.get("name"), equalTo(roleDescriptor.getName())); if (Strings.isNullOrEmpty(roleDescriptor.getDescription())) { assertThat(roleMap.get("description"), nullValue()); } else { assertThat(roleMap.get("description"), equalTo(roleDescriptor.getDescription())); } // "applications" is always present assertThat(roleMap.get("applications"), instanceOf(Iterable.class)); if (roleDescriptor.getApplicationPrivileges().length == 0) { assertThat((Iterable<ApplicationResourcePrivileges>) roleMap.get("applications"), emptyIterable()); } else { assertThat( (Iterable<Map<String, Object>>) roleMap.get("applications"), iterableWithSize(roleDescriptor.getApplicationPrivileges().length) ); Iterator<Map<String, Object>> responseIterator = ((Iterable<Map<String, Object>>) roleMap.get("applications")).iterator(); Iterator<ApplicationResourcePrivileges> descriptorIterator = Arrays.asList(roleDescriptor.getApplicationPrivileges()) .iterator(); while (responseIterator.hasNext()) { assertTrue(descriptorIterator.hasNext()); Map<String, Object> responsePrivilege = responseIterator.next(); ApplicationResourcePrivileges descriptorPrivilege = descriptorIterator.next(); assertThat(responsePrivilege.get("application"), equalTo(descriptorPrivilege.getApplication())); assertThat(responsePrivilege.get("privileges"), equalTo(Arrays.asList(descriptorPrivilege.getPrivileges()))); assertThat(responsePrivilege.get("resources"), equalTo(Arrays.asList(descriptorPrivilege.getResources()))); } assertFalse(descriptorIterator.hasNext()); } // in this test suite all roles are always enabled assertTrue(roleMap.containsKey("transient_metadata")); assertThat(roleMap.get("transient_metadata"), Matchers.instanceOf(Map.class)); assertThat(((Map<String, Object>) roleMap.get("transient_metadata")).get("enabled"), equalTo(true)); } private Map<String, Object> randomMetadata() { return randomMetadata(3); } private Map<String, Object> randomMetadata(int maxLevel) { int size = randomIntBetween(0, 5); Map<String, Object> metadata = new HashMap<>(size); for (int i = 0; i < size; i++) { switch (randomFrom(1, 2, 3, 4, 5)) { case 1: metadata.put(randomAlphaOfLength(4), randomAlphaOfLength(4)); break; case 2: metadata.put(randomAlphaOfLength(4), randomInt()); break; case 3: metadata.put(randomAlphaOfLength(4), randomList(0, 3, () -> randomAlphaOfLength(4))); break; case 4: metadata.put(randomAlphaOfLength(4), randomList(0, 3, () -> randomInt(4))); break; case 5: if (maxLevel > 0) { metadata.put(randomAlphaOfLength(4), randomMetadata(maxLevel - 1)); } break; } } return metadata; } private ApplicationResourcePrivileges randomApplicationResourcePrivileges() { String applicationName; if (randomBoolean()) { applicationName = "*"; } else { applicationName = randomAlphaOfLength(1).toLowerCase(Locale.ROOT) + randomAlphaOfLengthBetween(2, 10); } Supplier<String> privilegeNameSupplier = () -> randomAlphaOfLength(1).toLowerCase(Locale.ROOT) + randomAlphaOfLengthBetween(2, 8); int size = randomIntBetween(1, 5); List<String> resources = new ArrayList<>(size); for (int i = 0; i < size; i++) { if (randomBoolean()) { String suffix = randomBoolean() ? "*" : randomAlphaOfLengthBetween(4, 9); resources.add(randomAlphaOfLengthBetween(2, 5) + "/" + suffix); } else { resources.add(randomAlphaOfLength(1).toLowerCase(Locale.ROOT) + randomAlphaOfLengthBetween(2, 8)); } } return RoleDescriptor.ApplicationResourcePrivileges.builder() .application(applicationName) .resources(resources) .privileges(randomList(1, 3, privilegeNameSupplier)) .build(); } private String randomDescription() { StringBuilder randomDescriptionBuilder = new StringBuilder(); int nParts = randomIntBetween(1, 5); for (int i = 0; i < nParts; i++) { randomDescriptionBuilder.append(randomAlphaOfLengthBetween(1, 5)); } return randomDescriptionBuilder.toString(); } @SuppressWarnings("unchecked") public static void waitForMigrationCompletion(RestClient adminClient, Integer migrationVersion) throws Exception { final Request request = new Request("GET", "_cluster/state/metadata/" + INTERNAL_SECURITY_MAIN_INDEX_7); assertBusy(() -> { Response response = adminClient.performRequest(request); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); Map<String, Object> indicesMetadataMap = (Map<String, Object>) ((Map<String, Object>) responseMap.get("metadata")).get( "indices" ); assertTrue(indicesMetadataMap.containsKey(INTERNAL_SECURITY_MAIN_INDEX_7)); assertTrue( ((Map<String, Object>) indicesMetadataMap.get(INTERNAL_SECURITY_MAIN_INDEX_7)).containsKey(MIGRATION_VERSION_CUSTOM_KEY) ); if (migrationVersion != null) { assertTrue( ((Map<String, Object>) ((Map<String, Object>) indicesMetadataMap.get(INTERNAL_SECURITY_MAIN_INDEX_7)).get( MIGRATION_VERSION_CUSTOM_KEY )).containsKey(MIGRATION_VERSION_CUSTOM_DATA_KEY) ); Integer versionInteger = Integer.parseInt( (String) ((Map<String, Object>) ((Map<String, Object>) indicesMetadataMap.get(INTERNAL_SECURITY_MAIN_INDEX_7)).get( MIGRATION_VERSION_CUSTOM_KEY )).get(MIGRATION_VERSION_CUSTOM_DATA_KEY) ); assertThat(versionInteger, greaterThanOrEqualTo(migrationVersion)); } }); } }
QueryRoleIT
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringDynamicRouterTest.java
{ "start": 1038, "end": 1314 }
class ____ extends DynamicRouterTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/SpringDynamicRouterTest.xml"); } }
SpringDynamicRouterTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/parser/ClassConstructorTest1.java
{ "start": 176, "end": 481 }
class ____ extends TestCase { public void test_error() throws Exception { String modelJSON = "{\"age\":12, \"name\":\"nanqi\"}"; Model model = JSON.parseObject(modelJSON, Model.class); // Assert.notNull(model.getName()); //skip } public static
ClassConstructorTest1
java
micronaut-projects__micronaut-core
context/src/main/java/io/micronaut/scheduling/annotation/Async.java
{ "start": 1696, "end": 1942 }
interface ____ { /** * The name of the executor service to execute the task on. Defaults to {@link TaskExecutors#SCHEDULED} * * @return The name of the thread pool */ String value() default TaskExecutors.SCHEDULED; }
Async
java
elastic__elasticsearch
x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/integration/SecurityFeatureResetTests.java
{ "start": 1581, "end": 5678 }
class ____ extends SecurityIntegTestCase { private static final SecureString SUPER_USER_PASSWD = SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING; @Override protected boolean addMockHttpTransport() { return false; // enable http } @Before public void setupForTests() throws Exception { // adds a dummy user to the native realm to force .security index creation new TestSecurityClient(getRestClient(), SecuritySettingsSource.SECURITY_REQUEST_OPTIONS).putUser( new User("dummy_user", "missing_role"), SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING ); assertSecurityIndexActive(); } @Override protected String configUsers() { final String usersPasswHashed = new String(getFastStoredHashAlgoForTests().hash(SUPER_USER_PASSWD)); return super.configUsers() + "su:" + usersPasswHashed + "\n" + "manager:" + usersPasswHashed + "\n" + "usr:" + usersPasswHashed + "\n"; } @Override protected String configUsersRoles() { return super.configUsersRoles() + """ superuser:su role1:manager role2:usr"""; } @Override protected String configRoles() { return super.configRoles() + """ %s role1: cluster: [ manage ] indices: - names: '*' privileges: [ manage ] role2: cluster: [ monitor ] indices: - names: '*' privileges: [ read ] """; } public void testFeatureResetSuperuser() { assertResetSuccessful("su", SUPER_USER_PASSWD); } public void testFeatureResetManageRole() { assertResetSuccessful("manager", SUPER_USER_PASSWD); } public void testFeatureResetNoManageRole() { final ResetFeatureStateRequest req = new ResetFeatureStateRequest(TEST_REQUEST_TIMEOUT); client().filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue("usr", SUPER_USER_PASSWD))) .admin() .cluster() .execute(TransportResetFeatureStateAction.TYPE, req, new ActionListener<>() { @Override public void onResponse(ResetFeatureStateResponse response) { fail("Shouldn't reach here"); } @Override public void onFailure(Exception e) { assertThat( e.getMessage(), containsString( "action [cluster:admin/features/reset] is unauthorized for user [usr]" + " with effective roles [role2]" ) ); } }); // Manually delete the security index, reset shouldn't work deleteSecurityIndex(); } private void assertResetSuccessful(String user, SecureString password) { final ResetFeatureStateRequest req = new ResetFeatureStateRequest(TEST_REQUEST_TIMEOUT); client().filterWithHeader(Collections.singletonMap(BASIC_AUTH_HEADER, basicAuthHeaderValue(user, password))) .admin() .cluster() .execute(TransportResetFeatureStateAction.TYPE, req, new ActionListener<>() { @Override public void onResponse(ResetFeatureStateResponse response) { long failures = response.getFeatureStateResetStatuses() .stream() .filter(status -> status.getStatus() == ResetFeatureStateResponse.ResetFeatureStateStatus.Status.FAILURE) .count(); assertEquals(0, failures); } @Override public void onFailure(Exception e) { fail("Shouldn't reach here"); } }); } }
SecurityFeatureResetTests
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/rules/logical/ReplaceMinusWithAntiJoinRule.java
{ "start": 1714, "end": 3103 }
class ____ extends RelRule<ReplaceMinusWithAntiJoinRule.ReplaceMinusWithAntiJoinRuleConfig> { public static final ReplaceMinusWithAntiJoinRule INSTANCE = ReplaceMinusWithAntiJoinRule.ReplaceMinusWithAntiJoinRuleConfig.DEFAULT.toRule(); private ReplaceMinusWithAntiJoinRule(ReplaceMinusWithAntiJoinRuleConfig config) { super(config); } @Override public boolean matches(RelOptRuleCall call) { Minus minus = call.rel(0); return !minus.all && minus.getInputs().size() == 2; } @Override public void onMatch(RelOptRuleCall call) { Minus minus = call.rel(0); RelNode left = minus.getInput(0); RelNode right = minus.getInput(1); RelBuilder relBuilder = call.builder(); List<Integer> keys = Util.range(left.getRowType().getFieldCount()); List<RexNode> conditions = generateEqualsCondition(relBuilder, left, right, keys); relBuilder.push(left); relBuilder.push(right); relBuilder .join(JoinRelType.ANTI, conditions) .aggregate( relBuilder.groupKey(keys.stream().mapToInt(Integer::intValue).toArray())); RelNode rel = relBuilder.build(); call.transformTo(rel); } /** Rule configuration. */ @Value.Immutable(singleton = false) public
ReplaceMinusWithAntiJoinRule
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/net/impl/VertxConnection.java
{ "start": 16917, "end": 17074 }
interface ____ { boolean isWritable(); boolean write(MessageWrite msg); boolean tryDrain(); void close(); } private final
OutboundWriteQueue
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/spi/ReloadStrategy.java
{ "start": 1027, "end": 1558 }
interface ____ extends StaticService, CamelContextAware { /** * Trigger reload. * * @param source source that triggers the reloading. */ void onReload(Object source); /** * Number of reloads succeeded. */ int getReloadCounter(); /** * Number of reloads failed. */ int getFailedCounter(); /** * Reset the counters. */ void resetCounters(); /** * Gets the last error if reloading failed */ Exception getLastError(); }
ReloadStrategy
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/server/handler/FilteringWebHandlerTests.java
{ "start": 5834, "end": 6143 }
class ____ implements WebHandler { private volatile boolean invoked; public boolean invoked() { return this.invoked; } @Override public Mono<Void> handle(ServerWebExchange exchange) { logger.trace("StubHandler invoked."); this.invoked = true; return Mono.empty(); } } }
StubWebHandler
java
quarkusio__quarkus
extensions/mongodb-client/deployment/src/test/java/io/quarkus/mongodb/MongoTracingEnabled.java
{ "start": 526, "end": 1673 }
class ____ extends MongoTestBase { @Inject ReactiveMongoClient reactiveClient; @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addClasses(MongoTestBase.class, MockReactiveContextProvider.class, MockCommandListener.class)) .withConfigurationResource("application-tracing-mongoclient.properties"); @AfterEach void cleanup() { if (reactiveClient != null) { reactiveClient.close(); } } @Test void invokeReactiveContextProvider() { String dbNames = reactiveClient.listDatabaseNames().toUni().await().atMost(Duration.ofSeconds(30L)); assertThat(dbNames).as("expect db names available").isNotBlank(); await().atMost(Duration.ofSeconds(30L)).untilAsserted( () -> assertThat(MockReactiveContextProvider.EVENTS) .as("reactive context provider must be called") .isNotEmpty()); assertThat(MockCommandListener.EVENTS).isNotEmpty(); } }
MongoTracingEnabled
java
apache__camel
components/camel-grpc/src/test/java/org/apache/camel/component/grpc/GrpcProxyAsyncSyncTest.java
{ "start": 5395, "end": 6300 }
class ____ extends PingPongGrpc.PingPongImplBase { @Override public StreamObserver<PingRequest> pingAsyncSync(StreamObserver<PongResponse> responseObserver) { return new StreamObserver<PingRequest>() { @Override public void onNext(PingRequest pingRequest) { LOG.info(pingRequest.toString()); } @Override public void onError(Throwable throwable) { throw new RuntimeException(throwable); } @Override public void onCompleted() { PongResponse response01 = PongResponse.newBuilder().setPongName("rs").setPongId(1).build(); responseObserver.onNext(response01); responseObserver.onCompleted(); } }; } } }
PingPongImpl
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/client/XdsClient.java
{ "start": 9737, "end": 15581 }
class ____ { private final String failedVersion; private final long failedUpdateTimeNanos; private final String failedDetails; private UpdateFailureState( String failedVersion, long failedUpdateTimeNanos, String failedDetails) { this.failedVersion = checkNotNull(failedVersion, "failedVersion"); this.failedUpdateTimeNanos = failedUpdateTimeNanos; this.failedDetails = checkNotNull(failedDetails, "failedDetails"); } /** The rejected version string of the last failed update attempt. */ public String getFailedVersion() { return failedVersion; } /** Details about the last failed update attempt. */ public long getFailedUpdateTimeNanos() { return failedUpdateTimeNanos; } /** Timestamp of the last failed update attempt. */ public String getFailedDetails() { return failedDetails; } } } /** * Shutdown this {@link XdsClient} and release resources. */ public void shutdown() { throw new UnsupportedOperationException(); } /** * Returns {@code true} if {@link #shutdown()} has been called. */ public boolean isShutDown() { throw new UnsupportedOperationException(); } /** * Returns the config used to bootstrap this XdsClient {@link Bootstrapper.BootstrapInfo}. */ public Bootstrapper.BootstrapInfo getBootstrapInfo() { throw new UnsupportedOperationException(); } /** * Returns the implementation specific security configuration used in this XdsClient. */ public Object getSecurityConfig() { throw new UnsupportedOperationException(); } /** * Returns a {@link ListenableFuture} to the snapshot of the subscribed resources as * they are at the moment of the call. * * <p>The snapshot is a map from the "resource type" to * a map ("resource name": "resource metadata"). */ // Must be synchronized. public ListenableFuture<Map<XdsResourceType<?>, Map<String, ResourceMetadata>>> getSubscribedResourcesMetadataSnapshot() { throw new UnsupportedOperationException(); } /** * Registers a data watcher for the given Xds resource. */ public <T extends ResourceUpdate> void watchXdsResource(XdsResourceType<T> type, String resourceName, ResourceWatcher<T> watcher, Executor executor) { throw new UnsupportedOperationException(); } public <T extends ResourceUpdate> void watchXdsResource(XdsResourceType<T> type, String resourceName, ResourceWatcher<T> watcher) { watchXdsResource(type, resourceName, watcher, MoreExecutors.directExecutor()); } /** * Unregisters the given resource watcher. */ public <T extends ResourceUpdate> void cancelXdsResourceWatch(XdsResourceType<T> type, String resourceName, ResourceWatcher<T> watcher) { throw new UnsupportedOperationException(); } /** * Adds drop stats for the specified cluster with edsServiceName by using the returned object * to record dropped requests. Drop stats recorded with the returned object will be reported * to the load reporting server. The returned object is reference counted and the caller should * use {@link LoadStatsManager2.ClusterDropStats#release} to release its <i>hard</i> reference * when it is safe to stop reporting dropped RPCs for the specified cluster in the future. */ public LoadStatsManager2.ClusterDropStats addClusterDropStats( Bootstrapper.ServerInfo serverInfo, String clusterName, @Nullable String edsServiceName) { throw new UnsupportedOperationException(); } /** * Adds load stats for the specified locality (in the specified cluster with edsServiceName) by * using the returned object to record RPCs. Load stats recorded with the returned object will * be reported to the load reporting server. The returned object is reference counted and the * caller should use {@link LoadStatsManager2.ClusterLocalityStats#release} to release its * <i>hard</i> reference when it is safe to stop reporting RPC loads for the specified locality * in the future. */ public LoadStatsManager2.ClusterLocalityStats addClusterLocalityStats( Bootstrapper.ServerInfo serverInfo, String clusterName, @Nullable String edsServiceName, Locality locality) { return addClusterLocalityStats(serverInfo, clusterName, edsServiceName, locality, null); } /** * Adds load stats for the specified locality (in the specified cluster with edsServiceName) by * using the returned object to record RPCs. Load stats recorded with the returned object will * be reported to the load reporting server. The returned object is reference counted and the * caller should use {@link LoadStatsManager2.ClusterLocalityStats#release} to release its * <i>hard</i> reference when it is safe to stop reporting RPC loads for the specified locality * in the future. * * @param backendMetricPropagation Configuration for which backend metrics should be propagated * to LRS load reports. If null, all metrics will be propagated (legacy behavior). */ public LoadStatsManager2.ClusterLocalityStats addClusterLocalityStats( Bootstrapper.ServerInfo serverInfo, String clusterName, @Nullable String edsServiceName, Locality locality, @Nullable BackendMetricPropagation backendMetricPropagation) { throw new UnsupportedOperationException(); } /** * Returns a map of control plane server info objects to the LoadReportClients that are * responsible for sending load reports to the control plane servers. */ public Map<Bootstrapper.ServerInfo, LoadReportClient> getServerLrsClientMap() { throw new UnsupportedOperationException(); } /** Callback used to report a gauge metric value for server connections. */ public
UpdateFailureState
java
dropwizard__dropwizard
dropwizard-views-mustache/src/test/java/io/dropwizard/views/mustache/BadView.java
{ "start": 87, "end": 190 }
class ____ extends View { public BadView() { super("/woo-oo-ahh.txt.mustache"); } }
BadView
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/specialmappings/PointEntity.java
{ "start": 111, "end": 309 }
class ____ extends DataIdentity { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } }
PointEntity
java
google__gson
gson/src/test/java/com/google/gson/functional/MapTest.java
{ "start": 11674, "end": 13622 }
class ____<K, V> extends LinkedHashMap<K, V> { final int foo; MyParameterizedMap(int foo) { this.foo = foo; } } @Test public void testMapSubclassSerialization() { MyMap map = new MyMap(); map.put("a", "b"); String json = gson.toJson(map, MyMap.class); assertThat(json).contains("\"a\":\"b\""); } @Test public void testMapStandardSubclassDeserialization() { String json = "{a:'1',b:'2'}"; Type type = new TypeToken<LinkedHashMap<String, String>>() {}.getType(); LinkedHashMap<String, String> map = gson.fromJson(json, type); assertThat(map).containsEntry("a", "1"); assertThat(map).containsEntry("b", "2"); } @Test public void testMapSubclassDeserialization() { Gson gson = new GsonBuilder() .registerTypeAdapter(MyMap.class, (InstanceCreator<MyMap>) type -> new MyMap()) .create(); String json = "{\"a\":1,\"b\":2}"; MyMap map = gson.fromJson(json, MyMap.class); assertThat(map.get("a")).isEqualTo("1"); assertThat(map.get("b")).isEqualTo("2"); } @Test public void testCustomSerializerForSpecificMapType() { Type type = GsonTypes.newParameterizedTypeWithOwner(null, Map.class, String.class, Long.class); Gson gson = new GsonBuilder() .registerTypeAdapter( type, (JsonSerializer<Map<String, Long>>) (src, typeOfSrc, context) -> { JsonArray array = new JsonArray(); for (long value : src.values()) { array.add(new JsonPrimitive(value)); } return array; }) .create(); Map<String, Long> src = new LinkedHashMap<>(); src.put("one", 1L); src.put("two", 2L); src.put("three", 3L); assertThat(gson.toJson(src, type)).isEqualTo("[1,2,3]"); } private static
MyParameterizedMap
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableMapNotificationTest.java
{ "start": 1238, "end": 6693 }
class ____ extends RxJavaTest { @Test public void just() { TestSubscriber<Object> ts = new TestSubscriber<>(); Flowable.just(1) .flatMap( new Function<Integer, Flowable<Object>>() { @Override public Flowable<Object> apply(Integer item) { return Flowable.just((Object)(item + 1)); } }, new Function<Throwable, Flowable<Object>>() { @Override public Flowable<Object> apply(Throwable e) { return Flowable.error(e); } }, new Supplier<Flowable<Object>>() { @Override public Flowable<Object> get() { return Flowable.never(); } } ).subscribe(ts); ts.assertNoErrors(); ts.assertNotComplete(); ts.assertValue(2); } @Test public void backpressure() { TestSubscriber<Object> ts = TestSubscriber.create(0L); new FlowableMapNotification<>(Flowable.range(1, 3), new Function<Integer, Integer>() { @Override public Integer apply(Integer item) { return item + 1; } }, new Function<Throwable, Integer>() { @Override public Integer apply(Throwable e) { return 0; } }, new Supplier<Integer>() { @Override public Integer get() { return 5; } } ).subscribe(ts); ts.assertNoValues(); ts.assertNoErrors(); ts.assertNotComplete(); ts.request(3); ts.assertValues(2, 3, 4); ts.assertNoErrors(); ts.assertNotComplete(); ts.request(1); ts.assertValues(2, 3, 4, 5); ts.assertNoErrors(); ts.assertComplete(); } @Test public void noBackpressure() { TestSubscriber<Object> ts = TestSubscriber.create(0L); PublishProcessor<Integer> pp = PublishProcessor.create(); new FlowableMapNotification<>(pp, new Function<Integer, Integer>() { @Override public Integer apply(Integer item) { return item + 1; } }, new Function<Throwable, Integer>() { @Override public Integer apply(Throwable e) { return 0; } }, new Supplier<Integer>() { @Override public Integer get() { return 5; } } ).subscribe(ts); ts.assertNoValues(); ts.assertNoErrors(); ts.assertNotComplete(); pp.onNext(1); pp.onNext(2); pp.onNext(3); pp.onComplete(); ts.assertNoValues(); ts.assertNoErrors(); ts.assertNotComplete(); ts.request(1); ts.assertValue(0); ts.assertNoErrors(); ts.assertComplete(); } @Test public void dispose() { TestHelper.checkDisposed(new Flowable<Integer>() { @SuppressWarnings({ "rawtypes", "unchecked" }) @Override protected void subscribeActual(Subscriber<? super Integer> subscriber) { MapNotificationSubscriber mn = new MapNotificationSubscriber( subscriber, Functions.justFunction(Flowable.just(1)), Functions.justFunction(Flowable.just(2)), Functions.justSupplier(Flowable.just(3)) ); mn.onSubscribe(new BooleanSubscription()); } }); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Flowable<Object> f) throws Exception { return f.flatMap( Functions.justFunction(Flowable.just(1)), Functions.justFunction(Flowable.just(2)), Functions.justSupplier(Flowable.just(3)) ); } }); } @Test public void onErrorCrash() { TestSubscriberEx<Integer> ts = Flowable.<Integer>error(new TestException("Outer")) .flatMap(Functions.justFunction(Flowable.just(1)), new Function<Throwable, Publisher<Integer>>() { @Override public Publisher<Integer> apply(Throwable t) throws Exception { throw new TestException("Inner"); } }, Functions.justSupplier(Flowable.just(3))) .to(TestHelper.<Integer>testConsumer()) .assertFailure(CompositeException.class); TestHelper.assertError(ts, 0, TestException.class, "Outer"); TestHelper.assertError(ts, 1, TestException.class, "Inner"); } }
FlowableMapNotificationTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/bigdecimals/BigDecimals_assertIsNegative_Test.java
{ "start": 1278, "end": 2730 }
class ____ extends BigDecimalsBaseTest { @Test void should_succeed_since_actual_is_negative() { numbers.assertIsNegative(someInfo(), new BigDecimal("-1.0")); } @Test void should_succeed_since_actual_is_negative_according_to_custom_comparison_strategy() { numbersWithComparatorComparisonStrategy.assertIsNegative(someInfo(), new BigDecimal("-1.0")); } @Test void should_fail_since_actual_is_zero() { // WHEN var assertionError = expectAssertionError(() -> numbers.assertIsNegative(someInfo(), BigDecimal.ZERO)); // THEN then(assertionError).hasMessage(shouldBeLess(BigDecimal.ZERO, BigDecimal.ZERO).create()); } @Test void should_fail_since_actual_is_not_negative() { // WHEN var assertionError = expectAssertionError(() -> numbers.assertIsNegative(someInfo(), BigDecimal.ONE)); // THEN then(assertionError).hasMessage(shouldBeLess(BigDecimal.ONE, BigDecimal.ZERO).create()); } @Test void should_fail_since_actual_is_not_negative_according_to_custom_comparison_strategy() { // WHEN var error = expectAssertionError(() -> numbersWithAbsValueComparisonStrategy.assertIsNegative(someInfo(), new BigDecimal(-1))); // THEN then(error).hasMessage(shouldBeLess(new BigDecimal(-1), BigDecimal.ZERO, absValueComparisonStrategy).create()); } }
BigDecimals_assertIsNegative_Test
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/bean/override/BeanOverrideHandler.java
{ "start": 9303, "end": 9520 }
class ____. if (!localFieldsOnly && TestContextAnnotationUtils.searchEnclosingClass(clazz)) { findHandlers(clazz.getEnclosingClass(), testClass, handlers, localFieldsOnly, visitedTypes); } // 2) Search
hierarchy
java
apache__camel
test-infra/camel-test-infra-infinispan/src/test/java/org/apache/camel/test/infra/infinispan/services/InfinispanServiceFactory.java
{ "start": 3541, "end": 3647 }
class ____ extends InfinispanRemoteInfraService implements InfinispanService { } }
InfinispanRemoteService
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/PainlessScriptEngine.java
{ "start": 1714, "end": 5327 }
class ____ implements ScriptEngine { /** * Standard name of the Painless language. */ public static final String NAME = "painless"; /* * Setup the allowed permissions. */ static { final Permissions none = new Permissions(); none.setReadOnly(); } /** * Default compiler settings to be used. Note that {@link CompilerSettings} is mutable but this instance shouldn't be mutated outside * of {@link PainlessScriptEngine#PainlessScriptEngine(Settings, Map)}. */ private final CompilerSettings defaultCompilerSettings = new CompilerSettings(); private final Map<ScriptContext<?>, Compiler> contextsToCompilers; private final Map<ScriptContext<?>, PainlessLookup> contextsToLookups; /** * Constructor. * @param settings The settings to initialize the engine with. */ public PainlessScriptEngine(Settings settings, Map<ScriptContext<?>, List<Whitelist>> contexts) { defaultCompilerSettings.setRegexesEnabled(CompilerSettings.REGEX_ENABLED.get(settings)); defaultCompilerSettings.setRegexLimitFactor(CompilerSettings.REGEX_LIMIT_FACTOR.get(settings)); Map<ScriptContext<?>, Compiler> mutableContextsToCompilers = new HashMap<>(); Map<ScriptContext<?>, PainlessLookup> mutableContextsToLookups = new HashMap<>(); final Map<Object, Object> dedup = new HashMap<>(); final Map<PainlessMethod, PainlessMethod> filteredMethodCache = new HashMap<>(); for (Map.Entry<ScriptContext<?>, List<Whitelist>> entry : contexts.entrySet()) { ScriptContext<?> context = entry.getKey(); PainlessLookup lookup = PainlessLookupBuilder.buildFromWhitelists(entry.getValue(), dedup, filteredMethodCache); mutableContextsToCompilers.put( context, new Compiler(context.instanceClazz, context.factoryClazz, context.statefulFactoryClazz, lookup) ); mutableContextsToLookups.put(context, lookup); } this.contextsToCompilers = Collections.unmodifiableMap(mutableContextsToCompilers); this.contextsToLookups = Collections.unmodifiableMap(mutableContextsToLookups); } public Map<ScriptContext<?>, PainlessLookup> getContextsToLookups() { return contextsToLookups; } /** * Get the type name(s) for the language. * @return Always contains only the single name of the language. */ @Override public String getType() { return NAME; } @Override public <T> T compile(String scriptName, String scriptSource, ScriptContext<T> context, Map<String, String> params) { Compiler compiler = contextsToCompilers.get(context); // Check we ourselves are not being called by unprivileged code. SpecialPermission.check(); // Create our loader (which loads compiled code with no permissions). final Loader loader = compiler.createLoader(getClass().getClassLoader()); ScriptScope scriptScope = compile(contextsToCompilers.get(context), loader, scriptName, scriptSource, params); if (context.statefulFactoryClazz != null) { return generateFactory(loader, context, generateStatefulFactory(loader, context, scriptScope), scriptScope); } else { return generateFactory(loader, context, WriterConstants.CLASS_TYPE, scriptScope); } } @Override public Set<ScriptContext<?>> getSupportedContexts() { return contextsToCompilers.keySet(); } /** * Generates a stateful factory
PainlessScriptEngine
java
google__guice
core/test/com/google/inject/ImplicitBindingTest.java
{ "start": 1326, "end": 1373 }
class ____ { @Inject Bar bar; } static
Foo
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/task/TaskSchedulingAutoConfigurationTests.java
{ "start": 13563, "end": 13845 }
class ____ { @Bean ThreadPoolTaskSchedulerCustomizer testTaskSchedulerCustomizer() { return ((taskScheduler) -> taskScheduler.setThreadNamePrefix("customized-scheduler-")); } } @Configuration(proxyBeanMethods = false) static
ThreadPoolTaskSchedulerCustomizerConfiguration
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/security/AppPriorityACLsManager.java
{ "start": 1468, "end": 1534 }
class ____ store and check permission for Priority ACLs. */ public
to
java
spring-projects__spring-security
rsocket/src/main/java/org/springframework/security/rsocket/authorization/PayloadExchangeMatcherReactiveAuthorizationManager.java
{ "start": 3078, "end": 3663 }
class ____ { private final List<PayloadExchangeMatcherEntry<ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext>>> mappings = new ArrayList<>(); private Builder() { } public PayloadExchangeMatcherReactiveAuthorizationManager.Builder add( PayloadExchangeMatcherEntry<ReactiveAuthorizationManager<PayloadExchangeAuthorizationContext>> entry) { this.mappings.add(entry); return this; } public PayloadExchangeMatcherReactiveAuthorizationManager build() { return new PayloadExchangeMatcherReactiveAuthorizationManager(this.mappings); } } }
Builder
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocol/LayoutVersion.java
{ "start": 9562, "end": 13314 }
enum ____ and build a map of // LayoutVersion <-> Set of all supported features in that LayoutVersion SortedSet<LayoutFeature> existingFeatures = new TreeSet<LayoutFeature>( new LayoutFeatureComparator()); for (SortedSet<LayoutFeature> s : map.values()) { existingFeatures.addAll(s); } LayoutFeature prevF = existingFeatures.isEmpty() ? null : existingFeatures.first(); for (LayoutFeature f : features) { final FeatureInfo info = f.getInfo(); int minCompatLV = info.getMinimumCompatibleLayoutVersion(); if (prevF != null && minCompatLV > prevF.getInfo().getMinimumCompatibleLayoutVersion()) { throw new AssertionError(String.format( "Features must be listed in order of minimum compatible layout " + "version. Check features %s and %s.", prevF, f)); } prevF = f; SortedSet<LayoutFeature> ancestorSet = map.get(info.getAncestorLayoutVersion()); if (ancestorSet == null) { // Empty set ancestorSet = new TreeSet<LayoutFeature>(new LayoutFeatureComparator()); map.put(info.getAncestorLayoutVersion(), ancestorSet); } SortedSet<LayoutFeature> featureSet = new TreeSet<LayoutFeature>(ancestorSet); if (info.getSpecialFeatures() != null) { for (LayoutFeature specialFeature : info.getSpecialFeatures()) { featureSet.add(specialFeature); } } featureSet.add(f); map.put(info.getLayoutVersion(), featureSet); } } /** * Gets formatted string that describes {@link LayoutVersion} information. */ public String getString(Map<Integer, SortedSet<LayoutFeature>> map, LayoutFeature[] values) { final StringBuilder buf = new StringBuilder(); buf.append("Feature List:\n"); for (LayoutFeature f : values) { final FeatureInfo info = f.getInfo(); buf.append(f).append(" introduced in layout version ") .append(info.getLayoutVersion()).append(" (") .append(info.getDescription()).append(")\n"); } buf.append("\n\nLayoutVersion and supported features:\n"); for (LayoutFeature f : values) { final FeatureInfo info = f.getInfo(); buf.append(info.getLayoutVersion()).append(": ") .append(map.get(info.getLayoutVersion())).append("\n"); } return buf.toString(); } /** * Returns true if a given feature is supported in the given layout version * @param map layout feature map * @param f Feature * @param lv LayoutVersion * @return true if {@code f} is supported in layout version {@code lv} */ public static boolean supports(Map<Integer, SortedSet<LayoutFeature>> map, final LayoutFeature f, final int lv) { final SortedSet<LayoutFeature> set = map.get(lv); return set != null && set.contains(f); } /** * Get the current layout version */ public static int getCurrentLayoutVersion(LayoutFeature[] features) { return getLastNonReservedFeature(features).getInfo().getLayoutVersion(); } /** * Gets the minimum compatible layout version. * * @param features all features to check * @return minimum compatible layout version */ public static int getMinimumCompatibleLayoutVersion( LayoutFeature[] features) { return getLastNonReservedFeature(features).getInfo() .getMinimumCompatibleLayoutVersion(); } static LayoutFeature getLastNonReservedFeature(LayoutFeature[] features) { for (int i = features.length -1; i >= 0; i--) { final FeatureInfo info = features[i].getInfo(); if (!info.isReservedForOldRelease()) { return features[i]; } } throw new AssertionError("All layout versions are reserved."); } }
constants
java
apache__camel
components/camel-csv/src/test/java/org/apache/camel/dataformat/csv/CsvMarshalPipeDelimiterTest.java
{ "start": 1309, "end": 2872 }
class ____ extends CamelTestSupport { @EndpointInject("mock:result") private MockEndpoint result; @Test void testCsvMarshal() throws Exception { result.expectedMessageCount(1); template.sendBody("direct:start", createBody()); MockEndpoint.assertIsSatisfied(context); String body = result.getReceivedExchanges().get(0).getIn().getBody(String.class); String[] lines = body.split(LS); assertEquals(2, lines.length); assertEquals("123|Camel in Action|1", lines[0].trim()); assertEquals("124|ActiveMQ in Action|2", lines[1].trim()); } private List<Map<String, Object>> createBody() { List<Map<String, Object>> data = new ArrayList<>(); Map<String, Object> row1 = new LinkedHashMap<>(); row1.put("orderId", 123); row1.put("item", "Camel in Action"); row1.put("amount", 1); data.add(row1); Map<String, Object> row2 = new LinkedHashMap<>(); row2.put("orderId", 124); row2.put("item", "ActiveMQ in Action"); row2.put("amount", 2); data.add(row2); return data; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { CsvDataFormat csv = new CsvDataFormat().setDelimiter('|').setHeaderDisabled(true); from("direct:start").marshal(csv).convertBodyTo(String.class).to("mock:result"); } }; } }
CsvMarshalPipeDelimiterTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/resources/LengthParam.java
{ "start": 886, "end": 1605 }
class ____ extends LongParam { /** Parameter name. */ public static final String NAME = "length"; /** Default parameter value. */ public static final String DEFAULT = NULL; private static final Domain DOMAIN = new Domain(NAME); /** * Constructor. * @param value the parameter value. */ public LengthParam(final Long value) { super(DOMAIN, value, 0L, null); } /** * Constructor. * @param str a string representation of the parameter value. */ public LengthParam(final String str) { this(DOMAIN.parse(str)); } @Override public String getName() { return NAME; } public long getLength() { Long v = getValue(); return v == null ? -1 : v; } }
LengthParam
java
google__guava
guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
{ "start": 26304, "end": 26420 }
class ____ { void packagePrivateOneArg(String s) {} } private static
BaseClassThatFailsToThrowForPackagePrivate
java
quarkusio__quarkus
integration-tests/elytron-resteasy-reactive/src/main/java/io/quarkus/it/resteasy/reactive/elytron/AuthenticationFailedExceptionMapper.java
{ "start": 346, "end": 611 }
class ____ implements ExceptionMapper<AuthenticationFailedException> { @Override public Response toResponse(AuthenticationFailedException exception) { return Response.status(401).entity("customized").build(); } }
AuthenticationFailedExceptionMapper
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/AssertFalseTest.java
{ "start": 1989, "end": 2239 }
class ____ { public void assertFalse() { // BUG: Diagnostic contains: throw new AssertionError() assert false; } }\ """) .doTest(); } }
AssertFalsePositiveCases
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/nestedtargetproperties/ChartEntryToArtistUpdate.java
{ "start": 884, "end": 2012 }
class ____ { public static final ChartEntryToArtistUpdate MAPPER = Mappers.getMapper( ChartEntryToArtistUpdate.class ); @Mappings({ @Mapping(target = "type", ignore = true), @Mapping(target = "name", source = "chartName"), @Mapping(target = "song.title", source = "songTitle" ), @Mapping(target = "song.artist.name", source = "artistName" ), @Mapping(target = "song.artist.label.studio.name", source = "recordedAt"), @Mapping(target = "song.artist.label.studio.city", source = "city" ), @Mapping(target = "song.positions", source = "position" ) }) public abstract void map(ChartEntry chartEntry, @MappingTarget Chart chart ); protected List<Integer> mapPosition(Integer in) { if ( in != null ) { return Arrays.asList( in ); } else { return Collections.emptyList(); } } protected Integer mapPosition(List<Integer> in) { if ( in != null && !in.isEmpty() ) { return in.get( 0 ); } else { return null; } } }
ChartEntryToArtistUpdate
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/core/security/transport/netty4/SecurityNetty4Transport.java
{ "start": 17680, "end": 25334 }
class ____ the differences of client side TCP network settings between default and _remote_cluster transport profiles. // A field will be null if there is no difference between associated settings of the two profiles. It has a non-null value only // when the _remote_cluster profile has a different value from the default profile. record RemoteClusterClientBootstrapOptions( Boolean tcpNoDelay, Boolean tcpKeepAlive, Integer tcpKeepIdle, Integer tcpKeepInterval, Integer tcpKeepCount, ByteSizeValue tcpSendBufferSize, ByteSizeValue tcpReceiveBufferSize, Boolean tcpReuseAddress ) { boolean isEmpty() { return tcpNoDelay == null && tcpKeepAlive == null && tcpKeepIdle == null && tcpKeepInterval == null && tcpKeepCount == null && tcpSendBufferSize == null && tcpReceiveBufferSize == null && tcpReuseAddress == null; } void configure(Bootstrap bootstrap) { if (tcpNoDelay != null) { bootstrap.option(ChannelOption.TCP_NODELAY, tcpNoDelay); } if (tcpKeepAlive != null) { bootstrap.option(ChannelOption.SO_KEEPALIVE, tcpKeepAlive); if (tcpKeepAlive) { // Note that Netty logs a warning if it can't set the option if (tcpKeepIdle != null) { if (tcpKeepIdle >= 0) { bootstrap.option(OPTION_TCP_KEEP_IDLE, tcpKeepIdle); } else { bootstrap.option(OPTION_TCP_KEEP_IDLE, null); } } if (tcpKeepInterval != null) { if (tcpKeepInterval >= 0) { bootstrap.option(OPTION_TCP_KEEP_INTERVAL, tcpKeepInterval); } else { bootstrap.option(OPTION_TCP_KEEP_INTERVAL, null); } } if (tcpKeepCount != null) { if (tcpKeepCount >= 0) { bootstrap.option(OPTION_TCP_KEEP_COUNT, tcpKeepCount); } else { bootstrap.option(OPTION_TCP_KEEP_COUNT, null); } } } else { bootstrap.option(OPTION_TCP_KEEP_IDLE, null); bootstrap.option(OPTION_TCP_KEEP_INTERVAL, null); bootstrap.option(OPTION_TCP_KEEP_COUNT, null); } } if (tcpSendBufferSize != null) { if (tcpSendBufferSize.getBytes() > 0) { bootstrap.option(ChannelOption.SO_SNDBUF, Math.toIntExact(tcpSendBufferSize.getBytes())); } else { bootstrap.option(ChannelOption.SO_SNDBUF, null); } } if (tcpReceiveBufferSize != null) { if (tcpReceiveBufferSize.getBytes() > 0) { bootstrap.option(ChannelOption.SO_RCVBUF, Math.toIntExact(tcpReceiveBufferSize.getBytes())); } else { bootstrap.option(ChannelOption.SO_RCVBUF, null); } } if (tcpReuseAddress != null) { bootstrap.option(ChannelOption.SO_REUSEADDR, tcpReuseAddress); } } static RemoteClusterClientBootstrapOptions fromSettings(Settings settings) { Boolean tcpNoDelay = RemoteClusterPortSettings.TCP_NO_DELAY.get(settings); if (tcpNoDelay == TransportSettings.TCP_NO_DELAY.get(settings)) { tcpNoDelay = null; } // It is possible that both default and _remote_cluster enable keepAlive but have different // values for either keepIdle, keepInterval or keepCount. In this case, we need have a // non-null value for keepAlive even it is the same between default and _remote_cluster. Boolean tcpKeepAlive = RemoteClusterPortSettings.TCP_KEEP_ALIVE.get(settings); Integer tcpKeepIdle = RemoteClusterPortSettings.TCP_KEEP_IDLE.get(settings); Integer tcpKeepInterval = RemoteClusterPortSettings.TCP_KEEP_INTERVAL.get(settings); Integer tcpKeepCount = RemoteClusterPortSettings.TCP_KEEP_COUNT.get(settings); final Boolean defaultTcpKeepAlive = TransportSettings.TCP_KEEP_ALIVE.get(settings); if (tcpKeepAlive) { if (defaultTcpKeepAlive) { // Both profiles have keepAlive enabled, we need to check whether any keepIdle, keepInterval, keepCount is different if (tcpKeepIdle.equals(TransportSettings.TCP_KEEP_IDLE.get(settings))) { tcpKeepIdle = null; } if (tcpKeepInterval.equals(TransportSettings.TCP_KEEP_INTERVAL.get(settings))) { tcpKeepInterval = null; } if (tcpKeepCount.equals(TransportSettings.TCP_KEEP_COUNT.get(settings))) { tcpKeepCount = null; } if (tcpKeepIdle == null && tcpKeepInterval == null && tcpKeepCount == null) { // If keepIdle, keepInterval, keepCount are all identical, keepAlive can be null as well. // That is no need to update anything keepXxx related tcpKeepAlive = null; } } } else { if (false == defaultTcpKeepAlive) { tcpKeepAlive = null; } // _remote_cluster has keepAlive disabled, all other keepXxx has no reason to exist tcpKeepIdle = null; tcpKeepInterval = null; tcpKeepCount = null; } assert (tcpKeepAlive == null && tcpKeepIdle == null && tcpKeepInterval == null && tcpKeepCount == null) || (tcpKeepAlive == false && tcpKeepIdle == null && tcpKeepInterval == null && tcpKeepCount == null) || (tcpKeepAlive && (tcpKeepIdle != null || tcpKeepInterval != null || tcpKeepCount != null)) : "keepAlive == true must be accompanied with either keepIdle, keepInterval or keepCount change"; ByteSizeValue tcpSendBufferSize = RemoteClusterPortSettings.TCP_SEND_BUFFER_SIZE.get(settings); if (tcpSendBufferSize.equals(TransportSettings.TCP_SEND_BUFFER_SIZE.get(settings))) { tcpSendBufferSize = null; } ByteSizeValue tcpReceiveBufferSize = RemoteClusterPortSettings.TCP_RECEIVE_BUFFER_SIZE.get(settings); if (tcpReceiveBufferSize.equals(TransportSettings.TCP_RECEIVE_BUFFER_SIZE.get(settings))) { tcpReceiveBufferSize = null; } Boolean tcpReuseAddress = RemoteClusterPortSettings.TCP_REUSE_ADDRESS.get(settings); if (tcpReuseAddress == TransportSettings.TCP_REUSE_ADDRESS.get(settings)) { tcpReuseAddress = null; } return new RemoteClusterClientBootstrapOptions( tcpNoDelay, tcpKeepAlive, tcpKeepIdle, tcpKeepInterval, tcpKeepCount, tcpSendBufferSize, tcpReceiveBufferSize, tcpReuseAddress ); } } }
captures
java
google__guava
android/guava-tests/benchmark/com/google/common/base/ToStringHelperBenchmark.java
{ "start": 1071, "end": 4461 }
enum ____ { SMALL { @Override void addEntries(MoreObjects.ToStringHelper helper) { helper .add(SHORT_NAME, 10) .addValue(10L) .add(SHORT_NAME, 3.14f) .addValue(3.14d) .add(LONG_NAME, false) .add(LONG_NAME, LONG_NAME); } }, CONDITIONAL { @Override void addEntries(MoreObjects.ToStringHelper helper) { helper .add(SHORT_NAME, "x") .add(LONG_NAME, "y") .add(SHORT_NAME, null) .add(LONG_NAME, null) .addValue("z") .addValue("") .addValue(null) .add(SHORT_NAME, Arrays.asList("A")) .add(LONG_NAME, Arrays.asList("B")) .add(SHORT_NAME, Arrays.asList()) .add(LONG_NAME, Arrays.asList()) .addValue(Arrays.asList("C")) .addValue(Arrays.asList()) .add(SHORT_NAME, Collections.singletonMap("k1", "v1")) .add(LONG_NAME, Collections.singletonMap("k2", "v2")) .addValue(Collections.singletonMap("k3", "v3")) .addValue(Collections.emptyMap()) .addValue(null) .add(SHORT_NAME, Optional.of("1")) .add(LONG_NAME, Optional.of("1")) .add(SHORT_NAME, Optional.absent()) .add(LONG_NAME, Optional.absent()) .add(SHORT_NAME, Optional.of("2")) .add(SHORT_NAME, Optional.absent()) .addValue(null) .add(SHORT_NAME, new int[] {1}) .add(LONG_NAME, new int[] {2}) .addValue(new int[] {3}) .addValue(new int[] {}) .addValue(null); } }, UNCONDITIONAL { @Override void addEntries(MoreObjects.ToStringHelper helper) { helper .add(SHORT_NAME, false) .add(LONG_NAME, false) .addValue(true) .add(SHORT_NAME, (byte) 1) .add(LONG_NAME, (byte) 2) .addValue((byte) 3) .add(SHORT_NAME, 'A') .add(LONG_NAME, 'B') .addValue('C') .add(SHORT_NAME, (short) 4) .add(LONG_NAME, (short) 5) .addValue((short) 6) .add(SHORT_NAME, 7) .add(LONG_NAME, 8) .addValue(9) .add(SHORT_NAME, 10L) .add(LONG_NAME, 11L) .addValue(12L) .add(SHORT_NAME, 13.0f) .add(LONG_NAME, 14.0f) .addValue(15.0f); } }; void addEntries(MoreObjects.ToStringHelper helper) {} } @Param Dataset dataset; private static final String SHORT_NAME = "userId"; private static final String LONG_NAME = "fluxCapacitorFailureRate95Percentile"; private MoreObjects.ToStringHelper newHelper() { MoreObjects.ToStringHelper helper = MoreObjects.toStringHelper("klass"); if (omitNulls) { helper = helper.omitNullValues(); } return helper; } @Benchmark int toString(int reps) { int dummy = 0; for (int i = 0; i < reps; i++) { MoreObjects.ToStringHelper helper = newHelper(); for (int j = 0; j < dataSize; ++j) { dataset.addEntries(helper); } dummy ^= helper.toString().hashCode(); } return dummy; } // When omitEmptyValues() is released, remove this method and add a new @Param "omitEmptyValues". }
Dataset
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/collections/ordering/Contact.java
{ "start": 394, "end": 1106 }
class ____ { @Basic @Column(name = "last_name") private String lastName; @Basic @Column(name = "first_name") private String firstName; @Enumerated(EnumType.STRING) private TypesOfThings stuff; public Contact(String lastName, String firstName) { this.lastName = lastName; this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public TypesOfThings getStuff() { return stuff; } public void setStuff(TypesOfThings stuff) { this.stuff = stuff; } }
Contact
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/event/service/spi/EventActionWithParameter.java
{ "start": 210, "end": 324 }
interface ____<T, U, X> { void applyEventToListener(T eventListener, U action, X param); }
EventActionWithParameter
java
netty__netty
common/src/main/java/io/netty/util/Version.java
{ "start": 1981, "end": 7120 }
class ____}. * * @return A {@link Map} whose keys are Maven artifact IDs and whose values are {@link Version}s */ public static Map<String, Version> identify() { return identify(null); } /** * Retrieves the version information of Netty artifacts using the specified {@link ClassLoader}. * * @return A {@link Map} whose keys are Maven artifact IDs and whose values are {@link Version}s */ public static Map<String, Version> identify(ClassLoader classLoader) { if (classLoader == null) { classLoader = PlatformDependent.getContextClassLoader(); } // Collect all properties. Properties props = new Properties(); try { Enumeration<URL> resources = classLoader.getResources("META-INF/io.netty.versions.properties"); while (resources.hasMoreElements()) { URL url = resources.nextElement(); InputStream in = url.openStream(); try { props.load(in); } finally { try { in.close(); } catch (Exception ignore) { // Ignore. } } } } catch (Exception ignore) { // Not critical. Just ignore. } // Collect all artifactIds. Set<String> artifactIds = new HashSet<String>(); for (Object o: props.keySet()) { String k = (String) o; int dotIndex = k.indexOf('.'); if (dotIndex <= 0) { continue; } String artifactId = k.substring(0, dotIndex); // Skip the entries without required information. if (!props.containsKey(artifactId + PROP_VERSION) || !props.containsKey(artifactId + PROP_BUILD_DATE) || !props.containsKey(artifactId + PROP_COMMIT_DATE) || !props.containsKey(artifactId + PROP_SHORT_COMMIT_HASH) || !props.containsKey(artifactId + PROP_LONG_COMMIT_HASH) || !props.containsKey(artifactId + PROP_REPO_STATUS)) { continue; } artifactIds.add(artifactId); } Map<String, Version> versions = new TreeMap<String, Version>(); for (String artifactId: artifactIds) { versions.put( artifactId, new Version( artifactId, props.getProperty(artifactId + PROP_VERSION), parseIso8601(props.getProperty(artifactId + PROP_BUILD_DATE)), parseIso8601(props.getProperty(artifactId + PROP_COMMIT_DATE)), props.getProperty(artifactId + PROP_SHORT_COMMIT_HASH), props.getProperty(artifactId + PROP_LONG_COMMIT_HASH), props.getProperty(artifactId + PROP_REPO_STATUS))); } return versions; } private static long parseIso8601(String value) { try { return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z").parse(value).getTime(); } catch (ParseException ignored) { return 0; } } /** * Prints the version information to {@link System#err}. */ public static void main(String[] args) { for (Version v: identify().values()) { System.err.println(v); } } private final String artifactId; private final String artifactVersion; private final long buildTimeMillis; private final long commitTimeMillis; private final String shortCommitHash; private final String longCommitHash; private final String repositoryStatus; private Version( String artifactId, String artifactVersion, long buildTimeMillis, long commitTimeMillis, String shortCommitHash, String longCommitHash, String repositoryStatus) { this.artifactId = artifactId; this.artifactVersion = artifactVersion; this.buildTimeMillis = buildTimeMillis; this.commitTimeMillis = commitTimeMillis; this.shortCommitHash = shortCommitHash; this.longCommitHash = longCommitHash; this.repositoryStatus = repositoryStatus; } public String artifactId() { return artifactId; } public String artifactVersion() { return artifactVersion; } public long buildTimeMillis() { return buildTimeMillis; } public long commitTimeMillis() { return commitTimeMillis; } public String shortCommitHash() { return shortCommitHash; } public String longCommitHash() { return longCommitHash; } public String repositoryStatus() { return repositoryStatus; } @Override public String toString() { return artifactId + '-' + artifactVersion + '.' + shortCommitHash + ("clean".equals(repositoryStatus)? "" : " (repository: " + repositoryStatus + ')'); } }
loader
java
google__error-prone
check_api/src/main/java/com/google/errorprone/util/ASTHelpers.java
{ "start": 77462, "end": 79087 }
enum ____ // it is gets referenced by the stream, so the code won't work if compiled with a JDK that has // the change and executed with one that doesn't, or vice versa. Erasure means that the call to // Flags.asFlagSet doesn't itself cause problems because EnumSet<Flags.Flag> gets erased to just // EnumSet in the bytecode. return ((EnumSet<?>) Flags.asFlagSet(flags)) .stream().map(Object::toString).collect(toImmutableSet()); } // Removed in JDK 21 by JDK-8026369 public static final long POTENTIALLY_AMBIGUOUS = 1L << 48; /** Returns true if the given source code contains comments. */ public static boolean stringContainsComments(CharSequence source, Context context) { JavaTokenizer tokenizer = new JavaTokenizer(ScannerFactory.instance(context), CharBuffer.wrap(source)) {}; for (Token token = tokenizer.readToken(); token.kind != TokenKind.EOF; token = tokenizer.readToken()) { if (token.comments != null && !token.comments.isEmpty()) { return true; } } return false; } /** * Returns the mapping between type variables and their instantiations in the given type. For * example, the instantiation of {@code Map<K, V>} as {@code Map<String, Integer>} would be * represented as a {@code TypeSubstitution} from {@code [K, V]} to {@code [String, Integer]}. */ public static ImmutableListMultimap<Symbol.TypeVariableSymbol, Type> getTypeSubstitution( Type type, Symbol sym) { ImmutableListMultimap.Builder<Symbol.TypeVariableSymbol, Type> result = ImmutableListMultimap.builder();
type
java
elastic__elasticsearch
x-pack/plugin/enrich/src/main/java/org/elasticsearch/xpack/enrich/EnrichPolicyLocks.java
{ "start": 762, "end": 1026 }
class ____ for capturing the current execution * state of any policy executions in flight. This execution state can be captured and then later be used to verify that no policy * executions have started in the time between the first state capturing. */ public
allows
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/common/extension/AdaptiveClassCodeGenerator.java
{ "start": 13810, "end": 15198 }
class ____ as the key if (value.length == 0) { String splitName = StringUtils.camelToSplitName(type.getSimpleName(), "."); value = new String[] {splitName}; } return value; } /** * get parameter with type <code>URL</code> from method parameter: * <p> * test if parameter has method which returns type <code>URL</code> * <p> * if not found, throws IllegalStateException */ private String generateUrlAssignmentIndirectly(Method method) { Class<?>[] pts = method.getParameterTypes(); Map<String, Integer> getterReturnUrl = new HashMap<>(); // find URL getter method for (int i = 0; i < pts.length; ++i) { for (Method m : pts[i].getMethods()) { String name = m.getName(); if ((name.startsWith("get") || name.length() > 3) && Modifier.isPublic(m.getModifiers()) && !Modifier.isStatic(m.getModifiers()) && m.getParameterTypes().length == 0 && m.getReturnType() == URL.class) { getterReturnUrl.put(name, i); } } } if (getterReturnUrl.size() <= 0) { // getter method not found, throw throw new IllegalStateException("Failed to create adaptive
name
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azure/ITestPageBlobInputStream.java
{ "start": 1779, "end": 16476 }
class ____ extends AbstractWasbTestBase { private static final Logger LOG = LoggerFactory.getLogger( ITestPageBlobInputStream.class); private static final int KILOBYTE = 1024; private static final int MEGABYTE = KILOBYTE * KILOBYTE; private static final int TEST_FILE_SIZE = 6 * MEGABYTE; private static final Path TEST_FILE_PATH = new Path( "TestPageBlobInputStream.txt"); private long testFileLength; private FileStatus testFileStatus; private Path hugefile; @BeforeEach @Override public void setUp() throws Exception { super.setUp(); createTestAccount(); hugefile = fs.makeQualified(TEST_FILE_PATH); try { testFileStatus = fs.getFileStatus(TEST_FILE_PATH); testFileLength = testFileStatus.getLen(); } catch (FileNotFoundException e) { // file doesn't exist testFileLength = 0; } } @Override protected AzureBlobStorageTestAccount createTestAccount() throws Exception { Configuration conf = new Configuration(); // Configure the page blob directories key so every file created is a page blob. conf.set(AzureNativeFileSystemStore.KEY_PAGE_BLOB_DIRECTORIES, "/"); return AzureBlobStorageTestAccount.create( "testpageblobinputstream", EnumSet.of(AzureBlobStorageTestAccount.CreateOptions.CreateContainer), conf, true); } /** * Create a test file by repeating the characters in the alphabet. * @throws IOException */ private void createTestFileAndSetLength() throws IOException { // To reduce test run time, the test file can be reused. if (fs.exists(TEST_FILE_PATH)) { testFileStatus = fs.getFileStatus(TEST_FILE_PATH); testFileLength = testFileStatus.getLen(); LOG.info("Reusing test file: {}", testFileStatus); return; } byte[] buffer = new byte[256]; for (int i = 0; i < buffer.length; i++) { buffer[i] = (byte) i; } LOG.info("Creating test file {} of size: {}", TEST_FILE_PATH, TEST_FILE_SIZE); try(FSDataOutputStream outputStream = fs.create(TEST_FILE_PATH)) { int bytesWritten = 0; while (bytesWritten < TEST_FILE_SIZE) { outputStream.write(buffer); bytesWritten += buffer.length; } LOG.info("Closing stream {}", outputStream); outputStream.close(); } testFileLength = fs.getFileStatus(TEST_FILE_PATH).getLen(); } void assumeHugeFileExists() throws IOException { ContractTestUtils.assertPathExists(fs, "huge file not created", hugefile); FileStatus status = fs.getFileStatus(hugefile); ContractTestUtils.assertIsFile(hugefile, status); assertTrue(status.getLen() > 0, "File " + hugefile + " is empty"); } @Test public void test_0100_CreateHugeFile() throws IOException { createTestFileAndSetLength(); } @Test public void test_0200_BasicReadTest() throws Exception { assumeHugeFileExists(); try ( FSDataInputStream inputStream = fs.open(TEST_FILE_PATH); ) { byte[] buffer = new byte[3 * MEGABYTE]; // v1 forward seek and read a kilobyte into first kilobyte of buffer long position = 5 * MEGABYTE; inputStream.seek(position); int numBytesRead = inputStream.read(buffer, 0, KILOBYTE); assertEquals(KILOBYTE, numBytesRead); byte[] expected = new byte[3 * MEGABYTE]; for (int i = 0; i < KILOBYTE; i++) { expected[i] = (byte) ((i + position) % 256); } assertArrayEquals(expected, buffer); int len = MEGABYTE; int offset = buffer.length - len; // v1 reverse seek and read a megabyte into last megabyte of buffer position = 3 * MEGABYTE; inputStream.seek(position); numBytesRead = inputStream.read(buffer, offset, len); assertEquals(len, numBytesRead); for (int i = offset; i < offset + len; i++) { expected[i] = (byte) ((i + position) % 256); } assertArrayEquals(expected, buffer); } } @Test public void test_0201_RandomReadTest() throws Exception { assumeHugeFileExists(); try ( FSDataInputStream inputStream = fs.open(TEST_FILE_PATH); ) { final int bufferSize = 4 * KILOBYTE; byte[] buffer = new byte[bufferSize]; long position = 0; verifyConsistentReads(inputStream, buffer, position); inputStream.seek(0); verifyConsistentReads(inputStream, buffer, position); int seekPosition = 2 * KILOBYTE; inputStream.seek(seekPosition); position = seekPosition; verifyConsistentReads(inputStream, buffer, position); inputStream.seek(0); position = 0; verifyConsistentReads(inputStream, buffer, position); seekPosition = 5 * KILOBYTE; inputStream.seek(seekPosition); position = seekPosition; verifyConsistentReads(inputStream, buffer, position); seekPosition = 10 * KILOBYTE; inputStream.seek(seekPosition); position = seekPosition; verifyConsistentReads(inputStream, buffer, position); seekPosition = 4100 * KILOBYTE; inputStream.seek(seekPosition); position = seekPosition; verifyConsistentReads(inputStream, buffer, position); for (int i = 4 * 1024 * 1023; i < 5000; i++) { seekPosition = i; inputStream.seek(seekPosition); position = seekPosition; verifyConsistentReads(inputStream, buffer, position); } inputStream.seek(0); position = 0; buffer = new byte[1]; for (int i = 0; i < 5000; i++) { assertEquals(1, inputStream.skip(1)); position++; verifyConsistentReads(inputStream, buffer, position); position++; } } } private void verifyConsistentReads(FSDataInputStream inputStream, byte[] buffer, long position) throws IOException { int size = buffer.length; final int numBytesRead = inputStream.read(buffer, 0, size); assertEquals(size, numBytesRead, "Bytes read from stream"); byte[] expected = new byte[size]; for (int i = 0; i < expected.length; i++) { expected[i] = (byte) ((position + i) % 256); } assertArrayEquals(expected, buffer, "Mismatch"); } /** * Validates the implementation of InputStream.markSupported. * @throws IOException */ @Test public void test_0301_MarkSupported() throws IOException { assumeHugeFileExists(); try (FSDataInputStream inputStream = fs.open(TEST_FILE_PATH)) { assertTrue(inputStream.markSupported(), "mark is not supported"); } } /** * Validates the implementation of InputStream.mark and reset * for version 1 of the block blob input stream. * @throws Exception */ @Test public void test_0303_MarkAndResetV1() throws Exception { assumeHugeFileExists(); try (FSDataInputStream inputStream = fs.open(TEST_FILE_PATH)) { inputStream.mark(KILOBYTE - 1); byte[] buffer = new byte[KILOBYTE]; int bytesRead = inputStream.read(buffer); assertEquals(buffer.length, bytesRead); inputStream.reset(); assertEquals(0, inputStream.getPos(), "rest -> pos 0"); inputStream.mark(8 * KILOBYTE - 1); buffer = new byte[8 * KILOBYTE]; bytesRead = inputStream.read(buffer); assertEquals(buffer.length, bytesRead); intercept(IOException.class, "Resetting to invalid mark", new Callable<FSDataInputStream>() { @Override public FSDataInputStream call() throws Exception { inputStream.reset(); return inputStream; } } ); } } /** * Validates the implementation of Seekable.seekToNewSource, which should * return false for version 1 of the block blob input stream. * @throws IOException */ @Test public void test_0305_SeekToNewSourceV1() throws IOException { assumeHugeFileExists(); try (FSDataInputStream inputStream = fs.open(TEST_FILE_PATH)) { assertFalse(inputStream.seekToNewSource(0)); } } /** * Validates the implementation of InputStream.skip and ensures there is no * network I/O for version 1 of the block blob input stream. * @throws Exception */ @Test public void test_0307_SkipBounds() throws Exception { assumeHugeFileExists(); try (FSDataInputStream inputStream = fs.open(TEST_FILE_PATH)) { long skipped = inputStream.skip(-1); assertEquals(0, skipped); skipped = inputStream.skip(0); assertEquals(0, skipped); assertTrue(testFileLength > 0); skipped = inputStream.skip(testFileLength); assertEquals(testFileLength, skipped); intercept(EOFException.class, new Callable<Long>() { @Override public Long call() throws Exception { return inputStream.skip(1); } } ); } } /** * Validates the implementation of Seekable.seek and ensures there is no * network I/O for forward seek. * @throws Exception */ @Test public void test_0309_SeekBounds() throws Exception { assumeHugeFileExists(); try ( FSDataInputStream inputStream = fs.open(TEST_FILE_PATH); ) { inputStream.seek(0); assertEquals(0, inputStream.getPos()); intercept(EOFException.class, FSExceptionMessages.NEGATIVE_SEEK, new Callable<FSDataInputStream>() { @Override public FSDataInputStream call() throws Exception { inputStream.seek(-1); return inputStream; } } ); assertTrue(testFileLength > 0, "Test file length only " + testFileLength); inputStream.seek(testFileLength); assertEquals(testFileLength, inputStream.getPos()); intercept(EOFException.class, FSExceptionMessages.CANNOT_SEEK_PAST_EOF, new Callable<FSDataInputStream>() { @Override public FSDataInputStream call() throws Exception { inputStream.seek(testFileLength + 1); return inputStream; } } ); } } /** * Validates the implementation of Seekable.seek, Seekable.getPos, * and InputStream.available. * @throws Exception */ @Test public void test_0311_SeekAndAvailableAndPosition() throws Exception { assumeHugeFileExists(); try (FSDataInputStream inputStream = fs.open(TEST_FILE_PATH)) { byte[] expected1 = {0, 1, 2}; byte[] expected2 = {3, 4, 5}; byte[] expected3 = {1, 2, 3}; byte[] expected4 = {6, 7, 8}; byte[] buffer = new byte[3]; int bytesRead = inputStream.read(buffer); assertEquals(buffer.length, bytesRead); assertArrayEquals(expected1, buffer); assertEquals(buffer.length, inputStream.getPos()); assertEquals(testFileLength - inputStream.getPos(), inputStream.available()); bytesRead = inputStream.read(buffer); assertEquals(buffer.length, bytesRead); assertArrayEquals(expected2, buffer); assertEquals(2 * buffer.length, inputStream.getPos()); assertEquals(testFileLength - inputStream.getPos(), inputStream.available()); // reverse seek int seekPos = 0; inputStream.seek(seekPos); bytesRead = inputStream.read(buffer); assertEquals(buffer.length, bytesRead); assertArrayEquals(expected1, buffer); assertEquals(buffer.length + seekPos, inputStream.getPos()); assertEquals(testFileLength - inputStream.getPos(), inputStream.available()); // reverse seek seekPos = 1; inputStream.seek(seekPos); bytesRead = inputStream.read(buffer); assertEquals(buffer.length, bytesRead); assertArrayEquals(expected3, buffer); assertEquals(buffer.length + seekPos, inputStream.getPos()); assertEquals(testFileLength - inputStream.getPos(), inputStream.available()); // forward seek seekPos = 6; inputStream.seek(seekPos); bytesRead = inputStream.read(buffer); assertEquals(buffer.length, bytesRead); assertArrayEquals(expected4, buffer); assertEquals(buffer.length + seekPos, inputStream.getPos()); assertEquals(testFileLength - inputStream.getPos(), inputStream.available()); } } /** * Validates the implementation of InputStream.skip, Seekable.getPos, * and InputStream.available. * @throws IOException */ @Test public void test_0313_SkipAndAvailableAndPosition() throws IOException { assumeHugeFileExists(); try ( FSDataInputStream inputStream = fs.open(TEST_FILE_PATH); ) { byte[] expected1 = {0, 1, 2}; byte[] expected2 = {3, 4, 5}; byte[] expected3 = {1, 2, 3}; byte[] expected4 = {6, 7, 8}; assertEquals(testFileLength, inputStream.available()); assertEquals(0, inputStream.getPos()); int n = 3; long skipped = inputStream.skip(n); assertEquals(skipped, inputStream.getPos()); assertEquals(testFileLength - inputStream.getPos(), inputStream.available()); assertEquals(skipped, n); byte[] buffer = new byte[3]; int bytesRead = inputStream.read(buffer); assertEquals(buffer.length, bytesRead); assertArrayEquals(expected2, buffer); assertEquals(buffer.length + skipped, inputStream.getPos()); assertEquals(testFileLength - inputStream.getPos(), inputStream.available()); // does skip still work after seek? int seekPos = 1; inputStream.seek(seekPos); bytesRead = inputStream.read(buffer); assertEquals(buffer.length, bytesRead); assertArrayEquals(expected3, buffer); assertEquals(buffer.length + seekPos, inputStream.getPos()); assertEquals(testFileLength - inputStream.getPos(), inputStream.available()); long currentPosition = inputStream.getPos(); n = 2; skipped = inputStream.skip(n); assertEquals(currentPosition + skipped, inputStream.getPos()); assertEquals(testFileLength - inputStream.getPos(), inputStream.available()); assertEquals(skipped, n); bytesRead = inputStream.read(buffer); assertEquals(buffer.length, bytesRead); assertArrayEquals(expected4, buffer); assertEquals(buffer.length + skipped + currentPosition, inputStream.getPos()); assertEquals(testFileLength - inputStream.getPos(), inputStream.available()); } } @Test public void test_999_DeleteHugeFiles() throws IOException { fs.delete(TEST_FILE_PATH, false); } }
ITestPageBlobInputStream
java
apache__maven
compat/maven-repository-metadata/src/main/java/org/apache/maven/artifact/repository/metadata/io/xpp3/MetadataXpp3Reader.java
{ "start": 5385, "end": 5816 }
interface ____ { /** * Interpolate the value read from the xpp3 document * * @param source The source value * @param fieldName A description of the field being interpolated. The implementation may use this to * log stuff. * @return The interpolated value. */ String transform(String source, String fieldName); } }
ContentTransformer
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/coordination/MasterHistoryService.java
{ "start": 1628, "end": 10425 }
class ____ { private final TransportService transportService; private final MasterHistory localMasterHistory; private final LongSupplier currentTimeMillisSupplier; private final TimeValue acceptableRemoteHistoryAge; /* * This is a view of the master history one a remote node, or the exception that fetching it resulted in. This is populated * asynchronously. It is non-private for testing. Note that this field is not nulled out after its time to live expires. That check * is only done in getRemoteMasterHistory(). All non-testing access to this field needs to go through getRemoteMasterHistory(). */ volatile RemoteHistoryOrException remoteHistoryOrException = new RemoteHistoryOrException(null, null, Long.MIN_VALUE); private static final Logger logger = LogManager.getLogger(MasterHistoryService.class); private static final TimeValue DEFAULT_REMOTE_HISTORY_TIME_TO_LIVE = new TimeValue(5, TimeUnit.MINUTES); /** * This is the amount of time that can pass after a RemoteHistoryOrException is returned from the remote master until it is * considered stale and not usable. */ public static final Setting<TimeValue> REMOTE_HISTORY_TIME_TO_LIVE_SETTING = Setting.positiveTimeSetting( "master_history.remote_history_time_to_live", DEFAULT_REMOTE_HISTORY_TIME_TO_LIVE, Setting.Property.NodeScope ); public MasterHistoryService(TransportService transportService, ThreadPool threadPool, ClusterService clusterService) { this.transportService = transportService; this.localMasterHistory = new MasterHistory(threadPool, clusterService); this.currentTimeMillisSupplier = threadPool.relativeTimeInMillisSupplier(); this.acceptableRemoteHistoryAge = REMOTE_HISTORY_TIME_TO_LIVE_SETTING.get(clusterService.getSettings()); } /** * This returns the MasterHistory as seen from this node. The returned MasterHistory will be automatically updated whenever the * ClusterState on this node is updated with new information about the master. * @return The MasterHistory from this node's point of view. This MasterHistory object will be updated whenever the ClusterState changes */ public MasterHistory getLocalMasterHistory() { return localMasterHistory; } /** * This method returns a static view of the MasterHistory on a remote node. This MasterHistory is static in that it will not be * updated even if the ClusterState is updated on this node or the remote node. The history is retrieved asynchronously, and only if * refreshRemoteMasterHistory has been called for this node. If anything has gone wrong fetching it, the exception returned by the * remote machine will be thrown here. If the remote history has not been fetched or if something went wrong and there was no exception, * the returned value will be null. If the remote history is old enough to be considered stale (that is, older than * MAX_USABLE_REMOTE_HISTORY_AGE_SETTING), then the returned value will be null. * @return The MasterHistory from a remote node's point of view. This MasterHistory object will not be updated with future changes * @throws Exception the exception (if any) returned by the remote machine when fetching the history */ @Nullable public List<DiscoveryNode> getRemoteMasterHistory() throws Exception { // Grabbing a reference to the object in case it is replaced in another thread during this method: RemoteHistoryOrException remoteHistoryOrExceptionCopy = remoteHistoryOrException; /* * If the remote history we have is too old, we just return null with the assumption that it is stale and the new one has not * come in yet. */ long acceptableRemoteHistoryTime = currentTimeMillisSupplier.getAsLong() - acceptableRemoteHistoryAge.getMillis(); if (remoteHistoryOrExceptionCopy.creationTimeMillis < acceptableRemoteHistoryTime) { return null; } if (remoteHistoryOrExceptionCopy.exception != null) { throw remoteHistoryOrExceptionCopy.exception; } return remoteHistoryOrExceptionCopy.remoteHistory; } /** * This method attempts to fetch the master history from the requested node. If we are able to successfully fetch it, it will be * available in a later call to getRemoteMasterHistory. The client is not notified if or when the remote history is successfully * retrieved. This method only fetches the remote master history once, and it is never updated unless this method is called again. If * two calls are made to this method, the response of one will overwrite the response of the other (with no guarantee of the ordering * of responses). * This is a remote call, so clients should avoid calling it any more often than necessary. * @param node The node whose view of the master history we want to fetch */ public void refreshRemoteMasterHistory(DiscoveryNode node) { Version minSupportedVersion = Version.V_8_4_0; if (node.getVersion().before(minSupportedVersion)) { // This was introduced in 8.3.0 (and the action name changed in 8.4.0) logger.trace( "Cannot get master history for {} because it is at version {} and {} is required", node, node.getVersion(), minSupportedVersion ); return; } long startTime = System.nanoTime(); transportService.connectToNode( // Note: This connection must be explicitly closed below node, new ActionListener<>() { @Override public void onResponse(Releasable releasable) { logger.trace("Connected to {}, making master history request", node); // If we don't get a response in 10 seconds that is a failure worth capturing on its own: final TimeValue remoteMasterHistoryTimeout = TimeValue.timeValueSeconds(10); transportService.sendRequest( node, MasterHistoryAction.NAME, new MasterHistoryAction.Request(), TransportRequestOptions.timeout(remoteMasterHistoryTimeout), new ActionListenerResponseHandler<>(ActionListener.runBefore(new ActionListener<>() { @Override public void onResponse(MasterHistoryAction.Response response) { long endTime = System.nanoTime(); logger.trace("Received history from {} in {}", node, TimeValue.timeValueNanos(endTime - startTime)); remoteHistoryOrException = new RemoteHistoryOrException( response.getMasterHistory(), currentTimeMillisSupplier.getAsLong() ); } @Override public void onFailure(Exception e) { logger.warn("Exception in master history request to master node", e); remoteHistoryOrException = new RemoteHistoryOrException(e, currentTimeMillisSupplier.getAsLong()); } }, () -> Releasables.close(releasable)), MasterHistoryAction.Response::new, TransportResponseHandler.TRANSPORT_WORKER ) ); } @Override public void onFailure(Exception e) { logger.warn("Exception connecting to master node", e); remoteHistoryOrException = new RemoteHistoryOrException(e, currentTimeMillisSupplier.getAsLong()); } } ); } // non-private for testing record RemoteHistoryOrException(List<DiscoveryNode> remoteHistory, Exception exception, long creationTimeMillis) { public RemoteHistoryOrException { if (remoteHistory != null && exception != null) { throw new IllegalArgumentException("Remote history and exception cannot both be non-null"); } } RemoteHistoryOrException(List<DiscoveryNode> remoteHistory, long creationTimeMillis) { this(remoteHistory, null, creationTimeMillis); } RemoteHistoryOrException(Exception exception, long creationTimeMillis) { this(null, exception, creationTimeMillis); } } }
MasterHistoryService
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-hs/src/main/java/org/apache/hadoop/mapreduce/v2/hs/webapp/HsWebServices.java
{ "start": 4219, "end": 21942 }
class ____ extends WebServices { private static final Logger LOG = LoggerFactory.getLogger(HsWebServices.class); private final HistoryContext ctx; private WebApp webapp; private LogServlet logServlet; private boolean mrAclsEnabled; @Context private HttpServletResponse response; @Context private UriInfo uriInfo; @Inject public HsWebServices( final @Named("ctx") HistoryContext ctx, final @Named("conf") Configuration conf, final @Named("hsWebApp") WebApp webapp, final @Named("appClient") @Nullable ApplicationClientProtocol appBaseProto) { super(appBaseProto); this.ctx = ctx; this.webapp = webapp; this.logServlet = new LogServlet(conf, this); this.mrAclsEnabled = conf.getBoolean(MRConfig.MR_ACLS_ENABLED, false); } private boolean hasAccess(Job job, HttpServletRequest request) { String remoteUser = request.getRemoteUser(); if (remoteUser != null) { return job.checkAccess(UserGroupInformation.createRemoteUser(remoteUser), JobACL.VIEW_JOB); } return true; } private void checkAccess(Job job, HttpServletRequest request) { if (!hasAccess(job, request)) { throw new WebApplicationException(Status.UNAUTHORIZED); } } private void checkAccess(String containerIdStr, HttpServletRequest hsr) { // Apply MR ACLs only if the container belongs to a MapReduce job. // For non-MapReduce jobs, no corresponding Job will be found, // so ACLs are not enforced. if (mrAclsEnabled && isMRJobContainer(containerIdStr)) { Job job = AMWebServices.getJobFromContainerIdString(containerIdStr, ctx); checkAccess(job, hsr); } } private boolean isMRJobContainer(String containerIdStr) { try { AMWebServices.getJobFromContainerIdString(containerIdStr, ctx); return true; } catch (NotFoundException e) { LOG.trace("Container {} does not belong to a MapReduce job", containerIdStr); return false; } } private void init() { //clear content type response.setContentType(null); } @VisibleForTesting void setResponse(HttpServletResponse response) { this.response = response; } @GET @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public HistoryInfo get() { return getHistoryInfo(); } @GET @Path("/info") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public HistoryInfo getHistoryInfo() { init(); return new HistoryInfo(); } @GET @Path("/mapreduce/jobs") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public JobsInfo getJobs(@QueryParam("user") String userQuery, @QueryParam("limit") String count, @QueryParam("state") String stateQuery, @QueryParam("queue") String queueQuery, @QueryParam("startedTimeBegin") String startedBegin, @QueryParam("startedTimeEnd") String startedEnd, @QueryParam("finishedTimeBegin") String finishBegin, @QueryParam("finishedTimeEnd") String finishEnd) { Long countParam = null; init(); if (count != null && !count.isEmpty()) { try { countParam = Long.parseLong(count); } catch (NumberFormatException e) { throw new BadRequestException(e.getMessage()); } if (countParam <= 0) { throw new BadRequestException("limit value must be greater then 0"); } } Long sBegin = null; if (startedBegin != null && !startedBegin.isEmpty()) { try { sBegin = Long.parseLong(startedBegin); } catch (NumberFormatException e) { throw new BadRequestException("Invalid number format: " + e.getMessage()); } if (sBegin < 0) { throw new BadRequestException("startedTimeBegin must be greater than 0"); } } Long sEnd = null; if (startedEnd != null && !startedEnd.isEmpty()) { try { sEnd = Long.parseLong(startedEnd); } catch (NumberFormatException e) { throw new BadRequestException("Invalid number format: " + e.getMessage()); } if (sEnd < 0) { throw new BadRequestException("startedTimeEnd must be greater than 0"); } } if (sBegin != null && sEnd != null && sBegin > sEnd) { throw new BadRequestException( "startedTimeEnd must be greater than startTimeBegin"); } Long fBegin = null; if (finishBegin != null && !finishBegin.isEmpty()) { try { fBegin = Long.parseLong(finishBegin); } catch (NumberFormatException e) { throw new BadRequestException("Invalid number format: " + e.getMessage()); } if (fBegin < 0) { throw new BadRequestException("finishedTimeBegin must be greater than 0"); } } Long fEnd = null; if (finishEnd != null && !finishEnd.isEmpty()) { try { fEnd = Long.parseLong(finishEnd); } catch (NumberFormatException e) { throw new BadRequestException("Invalid number format: " + e.getMessage()); } if (fEnd < 0) { throw new BadRequestException("finishedTimeEnd must be greater than 0"); } } if (fBegin != null && fEnd != null && fBegin > fEnd) { throw new BadRequestException( "finishedTimeEnd must be greater than finishedTimeBegin"); } JobState jobState = null; if (stateQuery != null) { jobState = JobState.valueOf(stateQuery); } return ctx.getPartialJobs(0l, countParam, userQuery, queueQuery, sBegin, sEnd, fBegin, fEnd, jobState); } @GET @Path("/mapreduce/jobs/{jobid}") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public JobInfo getJob(@Context HttpServletRequest hsr, @PathParam("jobid") String jid) { init(); Job job = AMWebServices.getJobFromJobIdString(jid, ctx); checkAccess(job, hsr); return new JobInfo(job); } @GET @Path("/mapreduce/jobs/{jobid}/jobattempts") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public AMAttemptsInfo getJobAttempts(@PathParam("jobid") String jid) { init(); Job job = AMWebServices.getJobFromJobIdString(jid, ctx); AMAttemptsInfo amAttempts = new AMAttemptsInfo(); for (AMInfo amInfo : job.getAMInfos()) { AMAttemptInfo attempt = new AMAttemptInfo(amInfo, MRApps.toString(job .getID()), job.getUserName(), uriInfo.getBaseUri().toString(), webapp.name()); amAttempts.add(attempt); } return amAttempts; } @GET @Path("/mapreduce/jobs/{jobid}/counters") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public JobCounterInfo getJobCounters(@Context HttpServletRequest hsr, @PathParam("jobid") String jid) { init(); Job job = AMWebServices.getJobFromJobIdString(jid, ctx); checkAccess(job, hsr); return new JobCounterInfo(this.ctx, job); } @GET @Path("/mapreduce/jobs/{jobid}/conf") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public ConfInfo getJobConf(@Context HttpServletRequest hsr, @PathParam("jobid") String jid) { init(); Job job = AMWebServices.getJobFromJobIdString(jid, ctx); checkAccess(job, hsr); ConfInfo info; try { info = new ConfInfo(job); } catch (IOException e) { throw new NotFoundException("unable to load configuration for job: " + jid); } return info; } @GET @Path("/mapreduce/jobs/{jobid}/tasks") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public TasksInfo getJobTasks(@Context HttpServletRequest hsr, @PathParam("jobid") String jid, @QueryParam("type") String type) { init(); Job job = AMWebServices.getJobFromJobIdString(jid, ctx); checkAccess(job, hsr); TasksInfo allTasks = new TasksInfo(); for (Task task : job.getTasks().values()) { TaskType ttype = null; if (type != null && !type.isEmpty()) { try { ttype = MRApps.taskType(type); } catch (YarnRuntimeException e) { throw new BadRequestException("tasktype must be either m or r"); } } if (ttype != null && task.getType() != ttype) { continue; } allTasks.add(new TaskInfo(task)); } return allTasks; } @GET @Path("/mapreduce/jobs/{jobid}/tasks/{taskid}") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public TaskInfo getJobTask(@Context HttpServletRequest hsr, @PathParam("jobid") String jid, @PathParam("taskid") String tid) { init(); Job job = AMWebServices.getJobFromJobIdString(jid, ctx); checkAccess(job, hsr); Task task = AMWebServices.getTaskFromTaskIdString(tid, job); return new TaskInfo(task); } @GET @Path("/mapreduce/jobs/{jobid}/tasks/{taskid}/counters") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public JobTaskCounterInfo getSingleTaskCounters( @Context HttpServletRequest hsr, @PathParam("jobid") String jid, @PathParam("taskid") String tid) { init(); Job job = AMWebServices.getJobFromJobIdString(jid, ctx); checkAccess(job, hsr); TaskId taskID = MRApps.toTaskID(tid); if (taskID == null) { throw new NotFoundException("taskid " + tid + " not found or invalid"); } Task task = job.getTask(taskID); if (task == null) { throw new NotFoundException("task not found with id " + tid); } return new JobTaskCounterInfo(task); } @GET @Path("/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public TaskAttemptsInfo getJobTaskAttempts(@Context HttpServletRequest hsr, @PathParam("jobid") String jid, @PathParam("taskid") String tid) { init(); TaskAttemptsInfo attempts = new TaskAttemptsInfo(); Job job = AMWebServices.getJobFromJobIdString(jid, ctx); checkAccess(job, hsr); Task task = AMWebServices.getTaskFromTaskIdString(tid, job); for (TaskAttempt ta : task.getAttempts().values()) { if (ta != null) { if (task.getType() == TaskType.REDUCE) { attempts.add(new ReduceTaskAttemptInfo(ta)); } else { attempts.add(new MapTaskAttemptInfo(ta, false)); } } } return attempts; } @GET @Path("/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public TaskAttemptInfo getJobTaskAttemptId(@Context HttpServletRequest hsr, @PathParam("jobid") String jid, @PathParam("taskid") String tid, @PathParam("attemptid") String attId) { init(); Job job = AMWebServices.getJobFromJobIdString(jid, ctx); checkAccess(job, hsr); Task task = AMWebServices.getTaskFromTaskIdString(tid, job); TaskAttempt ta = AMWebServices.getTaskAttemptFromTaskAttemptString(attId, task); if (task.getType() == TaskType.REDUCE) { return new ReduceTaskAttemptInfo(ta); } else { return new MapTaskAttemptInfo(ta, false); } } @GET @Path("/mapreduce/jobs/{jobid}/tasks/{taskid}/attempts/{attemptid}/counters") @Produces({ MediaType.APPLICATION_JSON + "; " + JettyUtils.UTF_8, MediaType.APPLICATION_XML + "; " + JettyUtils.UTF_8 }) public JobTaskAttemptCounterInfo getJobTaskAttemptIdCounters( @Context HttpServletRequest hsr, @PathParam("jobid") String jid, @PathParam("taskid") String tid, @PathParam("attemptid") String attId) { init(); Job job = AMWebServices.getJobFromJobIdString(jid, ctx); checkAccess(job, hsr); Task task = AMWebServices.getTaskFromTaskIdString(tid, job); TaskAttempt ta = AMWebServices.getTaskAttemptFromTaskAttemptString(attId, task); return new JobTaskAttemptCounterInfo(ta); } /** * Returns the user qualified path name of the remote log directory for * each pre-configured log aggregation file controller. * * @param req HttpServletRequest * @return Path names grouped by file controller name */ @GET @Path("/remote-log-dir") @Produces({ MediaType.APPLICATION_JSON + ";" + JettyUtils.UTF_8, MediaType.APPLICATION_XML + ";" + JettyUtils.UTF_8 }) public Response getRemoteLogDirPath(@Context HttpServletRequest req, @QueryParam(YarnWebServiceParams.REMOTE_USER) String user, @QueryParam(YarnWebServiceParams.APP_ID) String appIdStr) throws IOException { init(); return logServlet.getRemoteLogDirPath(user, appIdStr); } @GET @Path("/extended-log-query") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @InterfaceAudience.Public @InterfaceStability.Unstable public Response getAggregatedLogsMeta(@Context HttpServletRequest hsr, @QueryParam(YarnWebServiceParams.CONTAINER_LOG_FILE_NAME) String fileName, @QueryParam(YarnWebServiceParams.FILESIZE) Set<String> fileSize, @QueryParam(YarnWebServiceParams.MODIFICATION_TIME) Set<String> modificationTime, @QueryParam(YarnWebServiceParams.APP_ID) String appIdStr, @QueryParam(YarnWebServiceParams.CONTAINER_ID) String containerIdStr, @QueryParam(YarnWebServiceParams.NM_ID) String nmId) throws IOException { init(); ExtendedLogMetaRequest.ExtendedLogMetaRequestBuilder logsRequest = new ExtendedLogMetaRequest.ExtendedLogMetaRequestBuilder(); logsRequest.setAppId(appIdStr); logsRequest.setFileName(fileName); logsRequest.setContainerId(containerIdStr); logsRequest.setFileSize(fileSize); logsRequest.setModificationTime(modificationTime); logsRequest.setNodeId(nmId); return logServlet.getContainerLogsInfo(hsr, logsRequest); } @GET @Path("/aggregatedlogs") @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML }) @InterfaceAudience.Public @InterfaceStability.Unstable public Response getAggregatedLogsMeta(@Context HttpServletRequest hsr, @QueryParam(YarnWebServiceParams.APP_ID) String appIdStr, @QueryParam(YarnWebServiceParams.APPATTEMPT_ID) String appAttemptIdStr, @QueryParam(YarnWebServiceParams.CONTAINER_ID) String containerIdStr, @QueryParam(YarnWebServiceParams.NM_ID) String nmId, @QueryParam(YarnWebServiceParams.REDIRECTED_FROM_NODE) @DefaultValue("false") boolean redirectedFromNode, @QueryParam(YarnWebServiceParams.MANUAL_REDIRECTION) @DefaultValue("false") boolean manualRedirection) { init(); return logServlet.getLogsInfo(hsr, appIdStr, appAttemptIdStr, containerIdStr, nmId, redirectedFromNode, manualRedirection); } @GET @Path("/containers/{containerid}/logs") @Produces({ MediaType.APPLICATION_JSON + ";" + JettyUtils.UTF_8, MediaType.APPLICATION_XML + ";" + JettyUtils.UTF_8}) @InterfaceAudience.Public @InterfaceStability.Unstable public Response getContainerLogs(@Context HttpServletRequest hsr, @PathParam(YarnWebServiceParams.CONTAINER_ID) String containerIdStr, @QueryParam(YarnWebServiceParams.NM_ID) String nmId, @QueryParam(YarnWebServiceParams.REDIRECTED_FROM_NODE) @DefaultValue("false") boolean redirectedFromNode, @QueryParam(YarnWebServiceParams.MANUAL_REDIRECTION) @DefaultValue("false") boolean manualRedirection) { init(); checkAccess(containerIdStr, hsr); WrappedLogMetaRequest.Builder logMetaRequestBuilder = LogServlet.createRequestFromContainerId(containerIdStr); return logServlet.getContainerLogsInfo(hsr, logMetaRequestBuilder, nmId, redirectedFromNode, null, manualRedirection); } @GET @Path("/containerlogs/{containerid}/{filename}") @Produces({ MediaType.TEXT_PLAIN + "; " + JettyUtils.UTF_8 }) @InterfaceAudience.Public @InterfaceStability.Unstable public Response getContainerLogFile(@Context HttpServletRequest req, @PathParam(YarnWebServiceParams.CONTAINER_ID) String containerIdStr, @PathParam(YarnWebServiceParams.CONTAINER_LOG_FILE_NAME) String filename, @QueryParam(YarnWebServiceParams.RESPONSE_CONTENT_FORMAT) String format, @QueryParam(YarnWebServiceParams.RESPONSE_CONTENT_SIZE) String size, @QueryParam(YarnWebServiceParams.NM_ID) String nmId, @QueryParam(YarnWebServiceParams.REDIRECTED_FROM_NODE) @DefaultValue("false") boolean redirectedFromNode, @QueryParam(YarnWebServiceParams.MANUAL_REDIRECTION) @DefaultValue("false") boolean manualRedirection) { init(); checkAccess(containerIdStr, req); return logServlet.getLogFile(req, containerIdStr, filename, format, size, nmId, redirectedFromNode, null, manualRedirection); } @VisibleForTesting LogServlet getLogServlet() { return this.logServlet; } @VisibleForTesting public void setLogServlet(LogServlet logServlet) { this.logServlet = logServlet; } @VisibleForTesting public void setHttpServletResponse(HttpServletResponse resp) { this.response = resp; } }
HsWebServices
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/parser/SqlBaseListener.java
{ "start": 244, "end": 46683 }
interface ____ extends ParseTreeListener { /** * Enter a parse tree produced by {@link SqlBaseParser#singleStatement}. * @param ctx the parse tree */ void enterSingleStatement(SqlBaseParser.SingleStatementContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#singleStatement}. * @param ctx the parse tree */ void exitSingleStatement(SqlBaseParser.SingleStatementContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#singleExpression}. * @param ctx the parse tree */ void enterSingleExpression(SqlBaseParser.SingleExpressionContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#singleExpression}. * @param ctx the parse tree */ void exitSingleExpression(SqlBaseParser.SingleExpressionContext ctx); /** * Enter a parse tree produced by the {@code statementDefault} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterStatementDefault(SqlBaseParser.StatementDefaultContext ctx); /** * Exit a parse tree produced by the {@code statementDefault} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitStatementDefault(SqlBaseParser.StatementDefaultContext ctx); /** * Enter a parse tree produced by the {@code explain} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterExplain(SqlBaseParser.ExplainContext ctx); /** * Exit a parse tree produced by the {@code explain} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitExplain(SqlBaseParser.ExplainContext ctx); /** * Enter a parse tree produced by the {@code debug} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterDebug(SqlBaseParser.DebugContext ctx); /** * Exit a parse tree produced by the {@code debug} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitDebug(SqlBaseParser.DebugContext ctx); /** * Enter a parse tree produced by the {@code showTables} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterShowTables(SqlBaseParser.ShowTablesContext ctx); /** * Exit a parse tree produced by the {@code showTables} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitShowTables(SqlBaseParser.ShowTablesContext ctx); /** * Enter a parse tree produced by the {@code showColumns} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterShowColumns(SqlBaseParser.ShowColumnsContext ctx); /** * Exit a parse tree produced by the {@code showColumns} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitShowColumns(SqlBaseParser.ShowColumnsContext ctx); /** * Enter a parse tree produced by the {@code showFunctions} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterShowFunctions(SqlBaseParser.ShowFunctionsContext ctx); /** * Exit a parse tree produced by the {@code showFunctions} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitShowFunctions(SqlBaseParser.ShowFunctionsContext ctx); /** * Enter a parse tree produced by the {@code showSchemas} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterShowSchemas(SqlBaseParser.ShowSchemasContext ctx); /** * Exit a parse tree produced by the {@code showSchemas} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitShowSchemas(SqlBaseParser.ShowSchemasContext ctx); /** * Enter a parse tree produced by the {@code showCatalogs} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterShowCatalogs(SqlBaseParser.ShowCatalogsContext ctx); /** * Exit a parse tree produced by the {@code showCatalogs} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitShowCatalogs(SqlBaseParser.ShowCatalogsContext ctx); /** * Enter a parse tree produced by the {@code sysTables} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterSysTables(SqlBaseParser.SysTablesContext ctx); /** * Exit a parse tree produced by the {@code sysTables} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitSysTables(SqlBaseParser.SysTablesContext ctx); /** * Enter a parse tree produced by the {@code sysColumns} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterSysColumns(SqlBaseParser.SysColumnsContext ctx); /** * Exit a parse tree produced by the {@code sysColumns} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitSysColumns(SqlBaseParser.SysColumnsContext ctx); /** * Enter a parse tree produced by the {@code sysTypes} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void enterSysTypes(SqlBaseParser.SysTypesContext ctx); /** * Exit a parse tree produced by the {@code sysTypes} * labeled alternative in {@link SqlBaseParser#statement}. * @param ctx the parse tree */ void exitSysTypes(SqlBaseParser.SysTypesContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#query}. * @param ctx the parse tree */ void enterQuery(SqlBaseParser.QueryContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#query}. * @param ctx the parse tree */ void exitQuery(SqlBaseParser.QueryContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#queryNoWith}. * @param ctx the parse tree */ void enterQueryNoWith(SqlBaseParser.QueryNoWithContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#queryNoWith}. * @param ctx the parse tree */ void exitQueryNoWith(SqlBaseParser.QueryNoWithContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#limitClause}. * @param ctx the parse tree */ void enterLimitClause(SqlBaseParser.LimitClauseContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#limitClause}. * @param ctx the parse tree */ void exitLimitClause(SqlBaseParser.LimitClauseContext ctx); /** * Enter a parse tree produced by the {@code queryPrimaryDefault} * labeled alternative in {@link SqlBaseParser#queryTerm}. * @param ctx the parse tree */ void enterQueryPrimaryDefault(SqlBaseParser.QueryPrimaryDefaultContext ctx); /** * Exit a parse tree produced by the {@code queryPrimaryDefault} * labeled alternative in {@link SqlBaseParser#queryTerm}. * @param ctx the parse tree */ void exitQueryPrimaryDefault(SqlBaseParser.QueryPrimaryDefaultContext ctx); /** * Enter a parse tree produced by the {@code subquery} * labeled alternative in {@link SqlBaseParser#queryTerm}. * @param ctx the parse tree */ void enterSubquery(SqlBaseParser.SubqueryContext ctx); /** * Exit a parse tree produced by the {@code subquery} * labeled alternative in {@link SqlBaseParser#queryTerm}. * @param ctx the parse tree */ void exitSubquery(SqlBaseParser.SubqueryContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#orderBy}. * @param ctx the parse tree */ void enterOrderBy(SqlBaseParser.OrderByContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#orderBy}. * @param ctx the parse tree */ void exitOrderBy(SqlBaseParser.OrderByContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#querySpecification}. * @param ctx the parse tree */ void enterQuerySpecification(SqlBaseParser.QuerySpecificationContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#querySpecification}. * @param ctx the parse tree */ void exitQuerySpecification(SqlBaseParser.QuerySpecificationContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#fromClause}. * @param ctx the parse tree */ void enterFromClause(SqlBaseParser.FromClauseContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#fromClause}. * @param ctx the parse tree */ void exitFromClause(SqlBaseParser.FromClauseContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#groupBy}. * @param ctx the parse tree */ void enterGroupBy(SqlBaseParser.GroupByContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#groupBy}. * @param ctx the parse tree */ void exitGroupBy(SqlBaseParser.GroupByContext ctx); /** * Enter a parse tree produced by the {@code singleGroupingSet} * labeled alternative in {@link SqlBaseParser#groupingElement}. * @param ctx the parse tree */ void enterSingleGroupingSet(SqlBaseParser.SingleGroupingSetContext ctx); /** * Exit a parse tree produced by the {@code singleGroupingSet} * labeled alternative in {@link SqlBaseParser#groupingElement}. * @param ctx the parse tree */ void exitSingleGroupingSet(SqlBaseParser.SingleGroupingSetContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#groupingExpressions}. * @param ctx the parse tree */ void enterGroupingExpressions(SqlBaseParser.GroupingExpressionsContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#groupingExpressions}. * @param ctx the parse tree */ void exitGroupingExpressions(SqlBaseParser.GroupingExpressionsContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#namedQuery}. * @param ctx the parse tree */ void enterNamedQuery(SqlBaseParser.NamedQueryContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#namedQuery}. * @param ctx the parse tree */ void exitNamedQuery(SqlBaseParser.NamedQueryContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#topClause}. * @param ctx the parse tree */ void enterTopClause(SqlBaseParser.TopClauseContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#topClause}. * @param ctx the parse tree */ void exitTopClause(SqlBaseParser.TopClauseContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#setQuantifier}. * @param ctx the parse tree */ void enterSetQuantifier(SqlBaseParser.SetQuantifierContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#setQuantifier}. * @param ctx the parse tree */ void exitSetQuantifier(SqlBaseParser.SetQuantifierContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#selectItems}. * @param ctx the parse tree */ void enterSelectItems(SqlBaseParser.SelectItemsContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#selectItems}. * @param ctx the parse tree */ void exitSelectItems(SqlBaseParser.SelectItemsContext ctx); /** * Enter a parse tree produced by the {@code selectExpression} * labeled alternative in {@link SqlBaseParser#selectItem}. * @param ctx the parse tree */ void enterSelectExpression(SqlBaseParser.SelectExpressionContext ctx); /** * Exit a parse tree produced by the {@code selectExpression} * labeled alternative in {@link SqlBaseParser#selectItem}. * @param ctx the parse tree */ void exitSelectExpression(SqlBaseParser.SelectExpressionContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#relation}. * @param ctx the parse tree */ void enterRelation(SqlBaseParser.RelationContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#relation}. * @param ctx the parse tree */ void exitRelation(SqlBaseParser.RelationContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#joinRelation}. * @param ctx the parse tree */ void enterJoinRelation(SqlBaseParser.JoinRelationContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#joinRelation}. * @param ctx the parse tree */ void exitJoinRelation(SqlBaseParser.JoinRelationContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#joinType}. * @param ctx the parse tree */ void enterJoinType(SqlBaseParser.JoinTypeContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#joinType}. * @param ctx the parse tree */ void exitJoinType(SqlBaseParser.JoinTypeContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#joinCriteria}. * @param ctx the parse tree */ void enterJoinCriteria(SqlBaseParser.JoinCriteriaContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#joinCriteria}. * @param ctx the parse tree */ void exitJoinCriteria(SqlBaseParser.JoinCriteriaContext ctx); /** * Enter a parse tree produced by the {@code tableName} * labeled alternative in {@link SqlBaseParser#relationPrimary}. * @param ctx the parse tree */ void enterTableName(SqlBaseParser.TableNameContext ctx); /** * Exit a parse tree produced by the {@code tableName} * labeled alternative in {@link SqlBaseParser#relationPrimary}. * @param ctx the parse tree */ void exitTableName(SqlBaseParser.TableNameContext ctx); /** * Enter a parse tree produced by the {@code aliasedQuery} * labeled alternative in {@link SqlBaseParser#relationPrimary}. * @param ctx the parse tree */ void enterAliasedQuery(SqlBaseParser.AliasedQueryContext ctx); /** * Exit a parse tree produced by the {@code aliasedQuery} * labeled alternative in {@link SqlBaseParser#relationPrimary}. * @param ctx the parse tree */ void exitAliasedQuery(SqlBaseParser.AliasedQueryContext ctx); /** * Enter a parse tree produced by the {@code aliasedRelation} * labeled alternative in {@link SqlBaseParser#relationPrimary}. * @param ctx the parse tree */ void enterAliasedRelation(SqlBaseParser.AliasedRelationContext ctx); /** * Exit a parse tree produced by the {@code aliasedRelation} * labeled alternative in {@link SqlBaseParser#relationPrimary}. * @param ctx the parse tree */ void exitAliasedRelation(SqlBaseParser.AliasedRelationContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#pivotClause}. * @param ctx the parse tree */ void enterPivotClause(SqlBaseParser.PivotClauseContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#pivotClause}. * @param ctx the parse tree */ void exitPivotClause(SqlBaseParser.PivotClauseContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#pivotArgs}. * @param ctx the parse tree */ void enterPivotArgs(SqlBaseParser.PivotArgsContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#pivotArgs}. * @param ctx the parse tree */ void exitPivotArgs(SqlBaseParser.PivotArgsContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#namedValueExpression}. * @param ctx the parse tree */ void enterNamedValueExpression(SqlBaseParser.NamedValueExpressionContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#namedValueExpression}. * @param ctx the parse tree */ void exitNamedValueExpression(SqlBaseParser.NamedValueExpressionContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#expression}. * @param ctx the parse tree */ void enterExpression(SqlBaseParser.ExpressionContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#expression}. * @param ctx the parse tree */ void exitExpression(SqlBaseParser.ExpressionContext ctx); /** * Enter a parse tree produced by the {@code logicalNot} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterLogicalNot(SqlBaseParser.LogicalNotContext ctx); /** * Exit a parse tree produced by the {@code logicalNot} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitLogicalNot(SqlBaseParser.LogicalNotContext ctx); /** * Enter a parse tree produced by the {@code stringQuery} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterStringQuery(SqlBaseParser.StringQueryContext ctx); /** * Exit a parse tree produced by the {@code stringQuery} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitStringQuery(SqlBaseParser.StringQueryContext ctx); /** * Enter a parse tree produced by the {@code booleanDefault} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterBooleanDefault(SqlBaseParser.BooleanDefaultContext ctx); /** * Exit a parse tree produced by the {@code booleanDefault} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitBooleanDefault(SqlBaseParser.BooleanDefaultContext ctx); /** * Enter a parse tree produced by the {@code exists} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterExists(SqlBaseParser.ExistsContext ctx); /** * Exit a parse tree produced by the {@code exists} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitExists(SqlBaseParser.ExistsContext ctx); /** * Enter a parse tree produced by the {@code multiMatchQuery} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterMultiMatchQuery(SqlBaseParser.MultiMatchQueryContext ctx); /** * Exit a parse tree produced by the {@code multiMatchQuery} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitMultiMatchQuery(SqlBaseParser.MultiMatchQueryContext ctx); /** * Enter a parse tree produced by the {@code matchQuery} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterMatchQuery(SqlBaseParser.MatchQueryContext ctx); /** * Exit a parse tree produced by the {@code matchQuery} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitMatchQuery(SqlBaseParser.MatchQueryContext ctx); /** * Enter a parse tree produced by the {@code logicalBinary} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void enterLogicalBinary(SqlBaseParser.LogicalBinaryContext ctx); /** * Exit a parse tree produced by the {@code logicalBinary} * labeled alternative in {@link SqlBaseParser#booleanExpression}. * @param ctx the parse tree */ void exitLogicalBinary(SqlBaseParser.LogicalBinaryContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#matchQueryOptions}. * @param ctx the parse tree */ void enterMatchQueryOptions(SqlBaseParser.MatchQueryOptionsContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#matchQueryOptions}. * @param ctx the parse tree */ void exitMatchQueryOptions(SqlBaseParser.MatchQueryOptionsContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#predicated}. * @param ctx the parse tree */ void enterPredicated(SqlBaseParser.PredicatedContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#predicated}. * @param ctx the parse tree */ void exitPredicated(SqlBaseParser.PredicatedContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#predicate}. * @param ctx the parse tree */ void enterPredicate(SqlBaseParser.PredicateContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#predicate}. * @param ctx the parse tree */ void exitPredicate(SqlBaseParser.PredicateContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#likePattern}. * @param ctx the parse tree */ void enterLikePattern(SqlBaseParser.LikePatternContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#likePattern}. * @param ctx the parse tree */ void exitLikePattern(SqlBaseParser.LikePatternContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#pattern}. * @param ctx the parse tree */ void enterPattern(SqlBaseParser.PatternContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#pattern}. * @param ctx the parse tree */ void exitPattern(SqlBaseParser.PatternContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#patternEscape}. * @param ctx the parse tree */ void enterPatternEscape(SqlBaseParser.PatternEscapeContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#patternEscape}. * @param ctx the parse tree */ void exitPatternEscape(SqlBaseParser.PatternEscapeContext ctx); /** * Enter a parse tree produced by the {@code valueExpressionDefault} * labeled alternative in {@link SqlBaseParser#valueExpression}. * @param ctx the parse tree */ void enterValueExpressionDefault(SqlBaseParser.ValueExpressionDefaultContext ctx); /** * Exit a parse tree produced by the {@code valueExpressionDefault} * labeled alternative in {@link SqlBaseParser#valueExpression}. * @param ctx the parse tree */ void exitValueExpressionDefault(SqlBaseParser.ValueExpressionDefaultContext ctx); /** * Enter a parse tree produced by the {@code comparison} * labeled alternative in {@link SqlBaseParser#valueExpression}. * @param ctx the parse tree */ void enterComparison(SqlBaseParser.ComparisonContext ctx); /** * Exit a parse tree produced by the {@code comparison} * labeled alternative in {@link SqlBaseParser#valueExpression}. * @param ctx the parse tree */ void exitComparison(SqlBaseParser.ComparisonContext ctx); /** * Enter a parse tree produced by the {@code arithmeticBinary} * labeled alternative in {@link SqlBaseParser#valueExpression}. * @param ctx the parse tree */ void enterArithmeticBinary(SqlBaseParser.ArithmeticBinaryContext ctx); /** * Exit a parse tree produced by the {@code arithmeticBinary} * labeled alternative in {@link SqlBaseParser#valueExpression}. * @param ctx the parse tree */ void exitArithmeticBinary(SqlBaseParser.ArithmeticBinaryContext ctx); /** * Enter a parse tree produced by the {@code arithmeticUnary} * labeled alternative in {@link SqlBaseParser#valueExpression}. * @param ctx the parse tree */ void enterArithmeticUnary(SqlBaseParser.ArithmeticUnaryContext ctx); /** * Exit a parse tree produced by the {@code arithmeticUnary} * labeled alternative in {@link SqlBaseParser#valueExpression}. * @param ctx the parse tree */ void exitArithmeticUnary(SqlBaseParser.ArithmeticUnaryContext ctx); /** * Enter a parse tree produced by the {@code dereference} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterDereference(SqlBaseParser.DereferenceContext ctx); /** * Exit a parse tree produced by the {@code dereference} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitDereference(SqlBaseParser.DereferenceContext ctx); /** * Enter a parse tree produced by the {@code cast} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterCast(SqlBaseParser.CastContext ctx); /** * Exit a parse tree produced by the {@code cast} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitCast(SqlBaseParser.CastContext ctx); /** * Enter a parse tree produced by the {@code constantDefault} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterConstantDefault(SqlBaseParser.ConstantDefaultContext ctx); /** * Exit a parse tree produced by the {@code constantDefault} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitConstantDefault(SqlBaseParser.ConstantDefaultContext ctx); /** * Enter a parse tree produced by the {@code extract} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterExtract(SqlBaseParser.ExtractContext ctx); /** * Exit a parse tree produced by the {@code extract} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitExtract(SqlBaseParser.ExtractContext ctx); /** * Enter a parse tree produced by the {@code parenthesizedExpression} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterParenthesizedExpression(SqlBaseParser.ParenthesizedExpressionContext ctx); /** * Exit a parse tree produced by the {@code parenthesizedExpression} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitParenthesizedExpression(SqlBaseParser.ParenthesizedExpressionContext ctx); /** * Enter a parse tree produced by the {@code star} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterStar(SqlBaseParser.StarContext ctx); /** * Exit a parse tree produced by the {@code star} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitStar(SqlBaseParser.StarContext ctx); /** * Enter a parse tree produced by the {@code castOperatorExpression} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterCastOperatorExpression(SqlBaseParser.CastOperatorExpressionContext ctx); /** * Exit a parse tree produced by the {@code castOperatorExpression} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitCastOperatorExpression(SqlBaseParser.CastOperatorExpressionContext ctx); /** * Enter a parse tree produced by the {@code function} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterFunction(SqlBaseParser.FunctionContext ctx); /** * Exit a parse tree produced by the {@code function} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitFunction(SqlBaseParser.FunctionContext ctx); /** * Enter a parse tree produced by the {@code currentDateTimeFunction} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterCurrentDateTimeFunction(SqlBaseParser.CurrentDateTimeFunctionContext ctx); /** * Exit a parse tree produced by the {@code currentDateTimeFunction} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitCurrentDateTimeFunction(SqlBaseParser.CurrentDateTimeFunctionContext ctx); /** * Enter a parse tree produced by the {@code subqueryExpression} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterSubqueryExpression(SqlBaseParser.SubqueryExpressionContext ctx); /** * Exit a parse tree produced by the {@code subqueryExpression} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitSubqueryExpression(SqlBaseParser.SubqueryExpressionContext ctx); /** * Enter a parse tree produced by the {@code case} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void enterCase(SqlBaseParser.CaseContext ctx); /** * Exit a parse tree produced by the {@code case} * labeled alternative in {@link SqlBaseParser#primaryExpression}. * @param ctx the parse tree */ void exitCase(SqlBaseParser.CaseContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#builtinDateTimeFunction}. * @param ctx the parse tree */ void enterBuiltinDateTimeFunction(SqlBaseParser.BuiltinDateTimeFunctionContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#builtinDateTimeFunction}. * @param ctx the parse tree */ void exitBuiltinDateTimeFunction(SqlBaseParser.BuiltinDateTimeFunctionContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#castExpression}. * @param ctx the parse tree */ void enterCastExpression(SqlBaseParser.CastExpressionContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#castExpression}. * @param ctx the parse tree */ void exitCastExpression(SqlBaseParser.CastExpressionContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#castTemplate}. * @param ctx the parse tree */ void enterCastTemplate(SqlBaseParser.CastTemplateContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#castTemplate}. * @param ctx the parse tree */ void exitCastTemplate(SqlBaseParser.CastTemplateContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#convertTemplate}. * @param ctx the parse tree */ void enterConvertTemplate(SqlBaseParser.ConvertTemplateContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#convertTemplate}. * @param ctx the parse tree */ void exitConvertTemplate(SqlBaseParser.ConvertTemplateContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#extractExpression}. * @param ctx the parse tree */ void enterExtractExpression(SqlBaseParser.ExtractExpressionContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#extractExpression}. * @param ctx the parse tree */ void exitExtractExpression(SqlBaseParser.ExtractExpressionContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#extractTemplate}. * @param ctx the parse tree */ void enterExtractTemplate(SqlBaseParser.ExtractTemplateContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#extractTemplate}. * @param ctx the parse tree */ void exitExtractTemplate(SqlBaseParser.ExtractTemplateContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#functionExpression}. * @param ctx the parse tree */ void enterFunctionExpression(SqlBaseParser.FunctionExpressionContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#functionExpression}. * @param ctx the parse tree */ void exitFunctionExpression(SqlBaseParser.FunctionExpressionContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#functionTemplate}. * @param ctx the parse tree */ void enterFunctionTemplate(SqlBaseParser.FunctionTemplateContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#functionTemplate}. * @param ctx the parse tree */ void exitFunctionTemplate(SqlBaseParser.FunctionTemplateContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#functionName}. * @param ctx the parse tree */ void enterFunctionName(SqlBaseParser.FunctionNameContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#functionName}. * @param ctx the parse tree */ void exitFunctionName(SqlBaseParser.FunctionNameContext ctx); /** * Enter a parse tree produced by the {@code nullLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void enterNullLiteral(SqlBaseParser.NullLiteralContext ctx); /** * Exit a parse tree produced by the {@code nullLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void exitNullLiteral(SqlBaseParser.NullLiteralContext ctx); /** * Enter a parse tree produced by the {@code intervalLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void enterIntervalLiteral(SqlBaseParser.IntervalLiteralContext ctx); /** * Exit a parse tree produced by the {@code intervalLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void exitIntervalLiteral(SqlBaseParser.IntervalLiteralContext ctx); /** * Enter a parse tree produced by the {@code numericLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void enterNumericLiteral(SqlBaseParser.NumericLiteralContext ctx); /** * Exit a parse tree produced by the {@code numericLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void exitNumericLiteral(SqlBaseParser.NumericLiteralContext ctx); /** * Enter a parse tree produced by the {@code booleanLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void enterBooleanLiteral(SqlBaseParser.BooleanLiteralContext ctx); /** * Exit a parse tree produced by the {@code booleanLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void exitBooleanLiteral(SqlBaseParser.BooleanLiteralContext ctx); /** * Enter a parse tree produced by the {@code stringLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void enterStringLiteral(SqlBaseParser.StringLiteralContext ctx); /** * Exit a parse tree produced by the {@code stringLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void exitStringLiteral(SqlBaseParser.StringLiteralContext ctx); /** * Enter a parse tree produced by the {@code paramLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void enterParamLiteral(SqlBaseParser.ParamLiteralContext ctx); /** * Exit a parse tree produced by the {@code paramLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void exitParamLiteral(SqlBaseParser.ParamLiteralContext ctx); /** * Enter a parse tree produced by the {@code dateEscapedLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void enterDateEscapedLiteral(SqlBaseParser.DateEscapedLiteralContext ctx); /** * Exit a parse tree produced by the {@code dateEscapedLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void exitDateEscapedLiteral(SqlBaseParser.DateEscapedLiteralContext ctx); /** * Enter a parse tree produced by the {@code timeEscapedLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void enterTimeEscapedLiteral(SqlBaseParser.TimeEscapedLiteralContext ctx); /** * Exit a parse tree produced by the {@code timeEscapedLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void exitTimeEscapedLiteral(SqlBaseParser.TimeEscapedLiteralContext ctx); /** * Enter a parse tree produced by the {@code timestampEscapedLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void enterTimestampEscapedLiteral(SqlBaseParser.TimestampEscapedLiteralContext ctx); /** * Exit a parse tree produced by the {@code timestampEscapedLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void exitTimestampEscapedLiteral(SqlBaseParser.TimestampEscapedLiteralContext ctx); /** * Enter a parse tree produced by the {@code guidEscapedLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void enterGuidEscapedLiteral(SqlBaseParser.GuidEscapedLiteralContext ctx); /** * Exit a parse tree produced by the {@code guidEscapedLiteral} * labeled alternative in {@link SqlBaseParser#constant}. * @param ctx the parse tree */ void exitGuidEscapedLiteral(SqlBaseParser.GuidEscapedLiteralContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#comparisonOperator}. * @param ctx the parse tree */ void enterComparisonOperator(SqlBaseParser.ComparisonOperatorContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#comparisonOperator}. * @param ctx the parse tree */ void exitComparisonOperator(SqlBaseParser.ComparisonOperatorContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#booleanValue}. * @param ctx the parse tree */ void enterBooleanValue(SqlBaseParser.BooleanValueContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#booleanValue}. * @param ctx the parse tree */ void exitBooleanValue(SqlBaseParser.BooleanValueContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#interval}. * @param ctx the parse tree */ void enterInterval(SqlBaseParser.IntervalContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#interval}. * @param ctx the parse tree */ void exitInterval(SqlBaseParser.IntervalContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#intervalField}. * @param ctx the parse tree */ void enterIntervalField(SqlBaseParser.IntervalFieldContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#intervalField}. * @param ctx the parse tree */ void exitIntervalField(SqlBaseParser.IntervalFieldContext ctx); /** * Enter a parse tree produced by the {@code primitiveDataType} * labeled alternative in {@link SqlBaseParser#dataType}. * @param ctx the parse tree */ void enterPrimitiveDataType(SqlBaseParser.PrimitiveDataTypeContext ctx); /** * Exit a parse tree produced by the {@code primitiveDataType} * labeled alternative in {@link SqlBaseParser#dataType}. * @param ctx the parse tree */ void exitPrimitiveDataType(SqlBaseParser.PrimitiveDataTypeContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#qualifiedName}. * @param ctx the parse tree */ void enterQualifiedName(SqlBaseParser.QualifiedNameContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#qualifiedName}. * @param ctx the parse tree */ void exitQualifiedName(SqlBaseParser.QualifiedNameContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#identifier}. * @param ctx the parse tree */ void enterIdentifier(SqlBaseParser.IdentifierContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#identifier}. * @param ctx the parse tree */ void exitIdentifier(SqlBaseParser.IdentifierContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#tableIdentifier}. * @param ctx the parse tree */ void enterTableIdentifier(SqlBaseParser.TableIdentifierContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#tableIdentifier}. * @param ctx the parse tree */ void exitTableIdentifier(SqlBaseParser.TableIdentifierContext ctx); /** * Enter a parse tree produced by the {@code quotedIdentifier} * labeled alternative in {@link SqlBaseParser#quoteIdentifier}. * @param ctx the parse tree */ void enterQuotedIdentifier(SqlBaseParser.QuotedIdentifierContext ctx); /** * Exit a parse tree produced by the {@code quotedIdentifier} * labeled alternative in {@link SqlBaseParser#quoteIdentifier}. * @param ctx the parse tree */ void exitQuotedIdentifier(SqlBaseParser.QuotedIdentifierContext ctx); /** * Enter a parse tree produced by the {@code backQuotedIdentifier} * labeled alternative in {@link SqlBaseParser#quoteIdentifier}. * @param ctx the parse tree */ void enterBackQuotedIdentifier(SqlBaseParser.BackQuotedIdentifierContext ctx); /** * Exit a parse tree produced by the {@code backQuotedIdentifier} * labeled alternative in {@link SqlBaseParser#quoteIdentifier}. * @param ctx the parse tree */ void exitBackQuotedIdentifier(SqlBaseParser.BackQuotedIdentifierContext ctx); /** * Enter a parse tree produced by the {@code unquotedIdentifier} * labeled alternative in {@link SqlBaseParser#unquoteIdentifier}. * @param ctx the parse tree */ void enterUnquotedIdentifier(SqlBaseParser.UnquotedIdentifierContext ctx); /** * Exit a parse tree produced by the {@code unquotedIdentifier} * labeled alternative in {@link SqlBaseParser#unquoteIdentifier}. * @param ctx the parse tree */ void exitUnquotedIdentifier(SqlBaseParser.UnquotedIdentifierContext ctx); /** * Enter a parse tree produced by the {@code digitIdentifier} * labeled alternative in {@link SqlBaseParser#unquoteIdentifier}. * @param ctx the parse tree */ void enterDigitIdentifier(SqlBaseParser.DigitIdentifierContext ctx); /** * Exit a parse tree produced by the {@code digitIdentifier} * labeled alternative in {@link SqlBaseParser#unquoteIdentifier}. * @param ctx the parse tree */ void exitDigitIdentifier(SqlBaseParser.DigitIdentifierContext ctx); /** * Enter a parse tree produced by the {@code decimalLiteral} * labeled alternative in {@link SqlBaseParser#number}. * @param ctx the parse tree */ void enterDecimalLiteral(SqlBaseParser.DecimalLiteralContext ctx); /** * Exit a parse tree produced by the {@code decimalLiteral} * labeled alternative in {@link SqlBaseParser#number}. * @param ctx the parse tree */ void exitDecimalLiteral(SqlBaseParser.DecimalLiteralContext ctx); /** * Enter a parse tree produced by the {@code integerLiteral} * labeled alternative in {@link SqlBaseParser#number}. * @param ctx the parse tree */ void enterIntegerLiteral(SqlBaseParser.IntegerLiteralContext ctx); /** * Exit a parse tree produced by the {@code integerLiteral} * labeled alternative in {@link SqlBaseParser#number}. * @param ctx the parse tree */ void exitIntegerLiteral(SqlBaseParser.IntegerLiteralContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#string}. * @param ctx the parse tree */ void enterString(SqlBaseParser.StringContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#string}. * @param ctx the parse tree */ void exitString(SqlBaseParser.StringContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#whenClause}. * @param ctx the parse tree */ void enterWhenClause(SqlBaseParser.WhenClauseContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#whenClause}. * @param ctx the parse tree */ void exitWhenClause(SqlBaseParser.WhenClauseContext ctx); /** * Enter a parse tree produced by {@link SqlBaseParser#nonReserved}. * @param ctx the parse tree */ void enterNonReserved(SqlBaseParser.NonReservedContext ctx); /** * Exit a parse tree produced by {@link SqlBaseParser#nonReserved}. * @param ctx the parse tree */ void exitNonReserved(SqlBaseParser.NonReservedContext ctx); }
SqlBaseListener
java
apache__dubbo
dubbo-rpc/dubbo-rpc-triple/src/main/java/org/apache/dubbo/rpc/protocol/tri/TripleCustomerProtocolWrapper.java
{ "start": 2648, "end": 6546 }
class ____ { private String serializeType; private byte[] data; private String type; public String getSerializeType() { return serializeType; } public byte[] getData() { return data; } public String getType() { return type; } public static TripleResponseWrapper parseFrom(byte[] data) { TripleResponseWrapper tripleResponseWrapper = new TripleResponseWrapper(); ByteBuffer byteBuffer = ByteBuffer.wrap(data); while (byteBuffer.position() < byteBuffer.limit()) { int tag = readRawVarint32(byteBuffer); int fieldNum = extractFieldNumFromTag(tag); int wireType = extractWireTypeFromTag(tag); if (wireType != 2) { throw new RuntimeException( String.format("unexpected wireType, expect %d realType %d", 2, wireType)); } if (fieldNum == 1) { int serializeTypeLength = readRawVarint32(byteBuffer); byte[] serializeTypeBytes = new byte[serializeTypeLength]; byteBuffer.get(serializeTypeBytes, 0, serializeTypeLength); tripleResponseWrapper.serializeType = new String(serializeTypeBytes); } else if (fieldNum == 2) { int dataLength = readRawVarint32(byteBuffer); byte[] dataBytes = new byte[dataLength]; byteBuffer.get(dataBytes, 0, dataLength); tripleResponseWrapper.data = dataBytes; } else if (fieldNum == 3) { int typeLength = readRawVarint32(byteBuffer); byte[] typeBytes = new byte[typeLength]; byteBuffer.get(typeBytes, 0, typeLength); tripleResponseWrapper.type = new String(typeBytes); } else { throw new RuntimeException("fieldNum should in (1,2,3)"); } } return tripleResponseWrapper; } public byte[] toByteArray() { int totalSize = 0; int serializeTypeTag = makeTag(1, 2); byte[] serializeTypeTagBytes = varIntEncode(serializeTypeTag); byte[] serializeTypeBytes = serializeType.getBytes(StandardCharsets.UTF_8); byte[] serializeTypeLengthVarIntEncodeBytes = varIntEncode(serializeTypeBytes.length); totalSize += serializeTypeTagBytes.length + serializeTypeLengthVarIntEncodeBytes.length + serializeTypeBytes.length; int dataTag = makeTag(2, 2); if (data != null) { totalSize += varIntComputeLength(dataTag) + varIntComputeLength(data.length) + data.length; } int typeTag = makeTag(3, 2); byte[] typeTagBytes = varIntEncode(typeTag); byte[] typeBytes = type.getBytes(StandardCharsets.UTF_8); byte[] typeLengthVarIntEncodeBytes = varIntEncode(typeBytes.length); totalSize += typeTagBytes.length + typeLengthVarIntEncodeBytes.length + typeBytes.length; ByteBuffer byteBuffer = ByteBuffer.allocate(totalSize); byteBuffer .put(serializeTypeTagBytes) .put(serializeTypeLengthVarIntEncodeBytes) .put(serializeTypeBytes); if (data != null) { byteBuffer .put(varIntEncode(dataTag)) .put(varIntEncode(data.length)) .put(data); } byteBuffer.put(typeTagBytes).put(typeLengthVarIntEncodeBytes).put(typeBytes); return byteBuffer.array(); } public static final
TripleResponseWrapper
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/pool/TestIdle3.java
{ "start": 954, "end": 4314 }
class ____ extends TestCase { protected void setUp() throws Exception { DruidDataSourceStatManager.clear(); } protected void tearDown() throws Exception { assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size()); } public void test_idle2() throws Exception { MockDriver driver = new MockDriver(); DruidDataSource dataSource = new DruidDataSource(); dataSource.setUrl("jdbc:mock:xxx"); dataSource.setDriver(driver); dataSource.setInitialSize(1); dataSource.setMaxActive(14); dataSource.setMaxIdle(14); dataSource.setMinIdle(1); dataSource.setMinEvictableIdleTimeMillis(30 * 100); // 300 / 10 dataSource.setTimeBetweenEvictionRunsMillis(18 * 100); // 180 / 10 dataSource.setTestWhileIdle(true); dataSource.setTestOnBorrow(false); dataSource.setValidationQuery("SELECT 1"); dataSource.setFilters("stat"); ManagementFactory.getPlatformMBeanServer().registerMBean(dataSource, new ObjectName( "com.alibaba:type=DataSource,name=mysql")); ManagementFactory.getPlatformMBeanServer().registerMBean(dataSource, new ObjectName( "com.alibaba:type=DataSource,name=oracle")); // 第一次创建连接 { assertEquals(0, dataSource.getCreateCount()); assertEquals(0, dataSource.getActiveCount()); Connection conn = dataSource.getConnection(); assertEquals(dataSource.getInitialSize(), dataSource.getCreateCount()); assertEquals(dataSource.getInitialSize(), driver.getConnections().size()); assertEquals(1, dataSource.getActiveCount()); conn.close(); assertEquals(0, dataSource.getDestroyCount()); assertEquals(1, driver.getConnections().size()); assertEquals(1, dataSource.getCreateCount()); assertEquals(0, dataSource.getActiveCount()); } { // 并发创建14个 int count = 14; Connection[] connections = new Connection[count]; for (int i = 0; i < count; ++i) { connections[i] = dataSource.getConnection(); assertEquals(i + 1, dataSource.getActiveCount()); } assertEquals(dataSource.getMaxActive(), dataSource.getCreateCount()); assertEquals(count, driver.getConnections().size()); // 全部关闭 for (int i = 0; i < count; ++i) { connections[i].close(); assertEquals(count - i - 1, dataSource.getActiveCount()); } assertEquals(dataSource.getMaxActive(), dataSource.getCreateCount()); assertEquals(0, dataSource.getActiveCount()); assertEquals(14, driver.getConnections().size()); } // 连续打开关闭单个连接 for (int i = 0; i < 1000; ++i) { assertEquals(0, dataSource.getActiveCount()); Connection conn = dataSource.getConnection(); assertEquals(1, dataSource.getActiveCount()); Thread.sleep(10); conn.close(); } assertEquals(true, dataSource.getPoolingCount() == 2 || dataSource.getPoolingCount() == 1); dataSource.close(); } }
TestIdle3
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/convert/ConvertingAbstractSerializer795Test.java
{ "start": 395, "end": 466 }
class ____ { public static abstract
ConvertingAbstractSerializer795Test
java
apache__camel
components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FromFtpPreMoveFilePrefixIT.java
{ "start": 1245, "end": 3086 }
class ____ extends FtpServerTestSupport { protected String getFtpUrl() { return "ftp://admin@localhost:{{ftp.server.port}}/movefile?password=admin&binary=false&delay=5000" + "&preMove=done/${file:name}"; } @Override public void doPostSetup() throws Exception { prepareFtpServer(); } @Test public void testPollFileAndShouldBeMoved() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.expectedBodiesReceived("Hello World this file will be moved"); mock.assertIsSatisfied(); // assert the file is moved File file = service.ftpFile("movefile/done/hello.txt").toFile(); assertTrue(file.exists(), "The file should have been moved"); } private void prepareFtpServer() throws Exception { // prepares the FTP Server by creating a file on the server that we want // to unit // test that we can pool and store as a local file Endpoint endpoint = context.getEndpoint(getFtpUrl()); Exchange exchange = endpoint.createExchange(); exchange.getIn().setBody("Hello World this file will be moved"); exchange.getIn().setHeader(Exchange.FILE_NAME, "hello.txt"); Producer producer = endpoint.createProducer(); producer.start(); producer.process(exchange); producer.stop(); // assert file is created File file = service.ftpFile("movefile/hello.txt").toFile(); assertTrue(file.exists(), "The file should exists"); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from(getFtpUrl()).to("mock:result"); } }; } }
FromFtpPreMoveFilePrefixIT
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/EnumNamingStrategies.java
{ "start": 240, "end": 322 }
class ____ implementations of the {@link EnumNamingStrategy} interface. */ public
for
java
apache__logging-log4j2
log4j-api/src/main/java/org/apache/logging/log4j/CloseableThreadContext.java
{ "start": 1430, "end": 4232 }
class ____ { private CloseableThreadContext() {} /** * Pushes new diagnostic context information on to the Thread Context Stack. The information will be popped off when * the instance is closed. * * @param message The new diagnostic context information. * @return a new instance that will back out the changes when closed. */ public static CloseableThreadContext.Instance push(final String message) { return new CloseableThreadContext.Instance().push(message); } /** * Pushes new diagnostic context information on to the Thread Context Stack. The information will be popped off when * the instance is closed. * * @param message The new diagnostic context information. * @param args Parameters for the message. * @return a new instance that will back out the changes when closed. */ public static CloseableThreadContext.Instance push(final String message, final Object... args) { return new CloseableThreadContext.Instance().push(message, args); } /** * Populates the Thread Context Map with the supplied key/value pair. Any existing key in the * {@link ThreadContext} will be replaced with the supplied value, and restored back to their original value when * the instance is closed. * * @param key The key to be added * @param value The value to be added * @return a new instance that will back out the changes when closed. */ public static CloseableThreadContext.Instance put(final String key, final String value) { return new CloseableThreadContext.Instance().put(key, value); } /** * Populates the Thread Context Stack with the supplied stack. The information will be popped off when * the instance is closed. * * @param messages The list of messages to be added * @return a new instance that will back out the changes when closed. * @since 2.8 */ public static CloseableThreadContext.Instance pushAll(final List<String> messages) { return new CloseableThreadContext.Instance().pushAll(messages); } /** * Populates the Thread Context Map with the supplied key/value pairs. Any existing keys in the * {@link ThreadContext} will be replaced with the supplied values, and restored back to their original value when * the instance is closed. * * @param values The map of key/value pairs to be added * @return a new instance that will back out the changes when closed. * @since 2.8 */ public static CloseableThreadContext.Instance putAll(final Map<String, String> values) { return new CloseableThreadContext.Instance().putAll(values); } /** * @since 2.6 */ public static
CloseableThreadContext
java
spring-projects__spring-security
crypto/src/main/java/org/springframework/security/crypto/password/PasswordEncoder.java
{ "start": 901, "end": 2595 }
interface ____ { /** * Encode the raw password. Generally, a good encoding algorithm uses an adaptive one * way function. * @param rawPassword a password that has not been encoded. The value can be null in * the event that the user has no password; in which case the result must be null. * @return A non-null encoded password, unless the rawPassword was null in which case * the result must be null. */ @Nullable String encode(@Nullable CharSequence rawPassword); /** * Verify the encoded password obtained from storage matches the submitted raw * password after it too is encoded. Returns true if the passwords match, false if * they do not. The stored password itself is never decoded. Never true if either * rawPassword or encodedPassword is null or an empty String. * @param rawPassword the raw password to encode and match. * @param encodedPassword the encoded password from storage to compare with. * @return true if the raw password, after encoding, matches the encoded password from * storage. */ boolean matches(@Nullable CharSequence rawPassword, @Nullable String encodedPassword); /** * Returns true if the encoded password should be encoded again for better security, * else false. The default implementation always returns false. * @param encodedPassword the encoded password to check. Possibly null if the user did * not have a password. * @return true if the encoded password should be encoded again for better security, * else false. If encodedPassword is null (the user didn't have a password), then * always false. */ default boolean upgradeEncoding(@Nullable String encodedPassword) { return false; } }
PasswordEncoder
java
apache__kafka
streams/src/test/java/org/apache/kafka/streams/state/StateSerdesTest.java
{ "start": 1392, "end": 6234 }
class ____ { @Test public void shouldThrowIfTopicNameIsNullForBuiltinTypes() { assertThrows(NullPointerException.class, () -> StateSerdes.withBuiltinTypes(null, byte[].class, byte[].class)); } @Test public void shouldThrowIfKeyClassIsNullForBuiltinTypes() { assertThrows(NullPointerException.class, () -> StateSerdes.withBuiltinTypes("anyName", null, byte[].class)); } @Test public void shouldThrowIfValueClassIsNullForBuiltinTypes() { assertThrows(NullPointerException.class, () -> StateSerdes.withBuiltinTypes("anyName", byte[].class, null)); } @Test public void shouldReturnSerdesForBuiltInKeyAndValueTypesForBuiltinTypes() { final Class[] supportedBuildInTypes = new Class[] { String.class, Short.class, Integer.class, Long.class, Float.class, Double.class, byte[].class, ByteBuffer.class, Bytes.class }; for (final Class keyClass : supportedBuildInTypes) { for (final Class valueClass : supportedBuildInTypes) { assertNotNull(StateSerdes.withBuiltinTypes("anyName", keyClass, valueClass)); } } } @Test public void shouldThrowForUnknownKeyTypeForBuiltinTypes() { assertThrows(IllegalArgumentException.class, () -> StateSerdes.withBuiltinTypes("anyName", Class.class, byte[].class)); } @Test public void shouldThrowForUnknownValueTypeForBuiltinTypes() { assertThrows(IllegalArgumentException.class, () -> StateSerdes.withBuiltinTypes("anyName", byte[].class, Class.class)); } @Test public void shouldThrowIfTopicNameIsNull() { assertThrows(NullPointerException.class, () -> new StateSerdes<>(null, Serdes.ByteArray(), Serdes.ByteArray())); } @Test public void shouldThrowIfKeyClassIsNull() { assertThrows(NullPointerException.class, () -> new StateSerdes<>("anyName", null, Serdes.ByteArray())); } @Test public void shouldThrowIfValueClassIsNull() { assertThrows(NullPointerException.class, () -> new StateSerdes<>("anyName", Serdes.ByteArray(), null)); } @Test public void shouldThrowIfIncompatibleSerdeForValue() throws ClassNotFoundException { final Class myClass = Class.forName("java.lang.String"); final StateSerdes<Object, Object> stateSerdes = new StateSerdes<Object, Object>("anyName", Serdes.serdeFrom(myClass), Serdes.serdeFrom(myClass)); final Integer myInt = 123; final Exception e = assertThrows(StreamsException.class, () -> stateSerdes.rawValue(myInt)); assertThat( e.getMessage(), equalTo( "A serializer (org.apache.kafka.common.serialization.StringSerializer) " + "is not compatible to the actual value type (value type: java.lang.Integer). " + "Change the default Serdes in StreamConfig or provide correct Serdes via method parameters.")); } @Test public void shouldSkipValueAndTimestampeInformationForErrorOnTimestampAndValueSerialization() throws ClassNotFoundException { final Class myClass = Class.forName("java.lang.String"); final StateSerdes<Object, Object> stateSerdes = new StateSerdes<Object, Object>("anyName", Serdes.serdeFrom(myClass), new ValueAndTimestampSerde(Serdes.serdeFrom(myClass))); final Integer myInt = 123; final Exception e = assertThrows(StreamsException.class, () -> stateSerdes.rawValue(ValueAndTimestamp.make(myInt, 0L))); assertThat( e.getMessage(), equalTo( "A serializer (org.apache.kafka.common.serialization.StringSerializer) " + "is not compatible to the actual value type (value type: java.lang.Integer). " + "Change the default Serdes in StreamConfig or provide correct Serdes via method parameters.")); } @Test public void shouldThrowIfIncompatibleSerdeForKey() throws ClassNotFoundException { final Class myClass = Class.forName("java.lang.String"); final StateSerdes<Object, Object> stateSerdes = new StateSerdes<Object, Object>("anyName", Serdes.serdeFrom(myClass), Serdes.serdeFrom(myClass)); final Integer myInt = 123; final Exception e = assertThrows(StreamsException.class, () -> stateSerdes.rawKey(myInt)); assertThat( e.getMessage(), equalTo( "A serializer (org.apache.kafka.common.serialization.StringSerializer) " + "is not compatible to the actual key type (key type: java.lang.Integer). " + "Change the default Serdes in StreamConfig or provide correct Serdes via method parameters.")); } }
StateSerdesTest
java
elastic__elasticsearch
plugins/repository-hdfs/src/test/java/org/elasticsearch/repositories/hdfs/HdfsTests.java
{ "start": 1716, "end": 12944 }
class ____ extends ESSingleNodeTestCase { @Override protected Collection<Class<? extends Plugin>> getPlugins() { return pluginList(HdfsPlugin.class); } public void testSimpleWorkflow() { Client client = client(); assertAcked( client.admin() .cluster() .preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "test-repo") .setType("hdfs") .setSettings( Settings.builder() .put("uri", "hdfs:///") .put("conf.fs.AbstractFileSystem.hdfs.impl", TestingFs.class.getName()) .put("path", "foo") .put("chunk_size", randomIntBetween(100, 1000) + "k") .put("compress", randomBoolean()) ) ); createIndex("test-idx-1"); createIndex("test-idx-2"); createIndex("test-idx-3"); ensureGreen(); logger.info("--> indexing some data"); for (int i = 0; i < 100; i++) { prepareIndex("test-idx-1").setId(Integer.toString(i)).setSource("foo", "bar" + i).get(); prepareIndex("test-idx-2").setId(Integer.toString(i)).setSource("foo", "bar" + i).get(); prepareIndex("test-idx-3").setId(Integer.toString(i)).setSource("foo", "bar" + i).get(); } client().admin().indices().prepareRefresh().get(); assertThat(count(client, "test-idx-1"), equalTo(100L)); assertThat(count(client, "test-idx-2"), equalTo(100L)); assertThat(count(client, "test-idx-3"), equalTo(100L)); logger.info("--> snapshot"); CreateSnapshotResponse createSnapshotResponse = client.admin() .cluster() .prepareCreateSnapshot(TEST_REQUEST_TIMEOUT, "test-repo", "test-snap") .setWaitForCompletion(true) .setIndices("test-idx-*", "-test-idx-3") .get(); assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0)); assertThat( createSnapshotResponse.getSnapshotInfo().successfulShards(), equalTo(createSnapshotResponse.getSnapshotInfo().totalShards()) ); assertThat( client.admin() .cluster() .prepareGetSnapshots(TEST_REQUEST_TIMEOUT, "test-repo") .setSnapshots("test-snap") .get() .getSnapshots() .get(0) .state(), equalTo(SnapshotState.SUCCESS) ); logger.info("--> delete some data"); for (int i = 0; i < 50; i++) { client.prepareDelete("test-idx-1", Integer.toString(i)).get(); } for (int i = 50; i < 100; i++) { client.prepareDelete("test-idx-2", Integer.toString(i)).get(); } for (int i = 0; i < 100; i += 2) { client.prepareDelete("test-idx-3", Integer.toString(i)).get(); } client().admin().indices().prepareRefresh().get(); assertThat(count(client, "test-idx-1"), equalTo(50L)); assertThat(count(client, "test-idx-2"), equalTo(50L)); assertThat(count(client, "test-idx-3"), equalTo(50L)); logger.info("--> close indices"); client.admin().indices().prepareClose("test-idx-1", "test-idx-2").get(); logger.info("--> restore all indices from the snapshot"); RestoreSnapshotResponse restoreSnapshotResponse = client.admin() .cluster() .prepareRestoreSnapshot(TEST_REQUEST_TIMEOUT, "test-repo", "test-snap") .setWaitForCompletion(true) .get(); assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); ensureGreen(); assertThat(count(client, "test-idx-1"), equalTo(100L)); assertThat(count(client, "test-idx-2"), equalTo(100L)); assertThat(count(client, "test-idx-3"), equalTo(50L)); // Test restore after index deletion logger.info("--> delete indices"); client().admin().indices().prepareDelete("test-idx-1", "test-idx-2").get(); logger.info("--> restore one index after deletion"); restoreSnapshotResponse = client.admin() .cluster() .prepareRestoreSnapshot(TEST_REQUEST_TIMEOUT, "test-repo", "test-snap") .setWaitForCompletion(true) .setIndices("test-idx-*", "-test-idx-2") .get(); assertThat(restoreSnapshotResponse.getRestoreInfo().totalShards(), greaterThan(0)); ensureGreen(); assertThat(count(client, "test-idx-1"), equalTo(100L)); ClusterState clusterState = client.admin().cluster().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); assertThat(clusterState.getMetadata().getProject().hasIndex("test-idx-1"), equalTo(true)); assertThat(clusterState.getMetadata().getProject().hasIndex("test-idx-2"), equalTo(false)); final BlobStoreRepository repo = (BlobStoreRepository) getInstanceFromNode(RepositoriesService.class).repository("test-repo"); BlobStoreTestUtil.assertConsistency(repo); } public void testMissingUri() { try { clusterAdmin().preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "test-repo") .setType("hdfs") .setSettings(Settings.EMPTY) .get(); fail(); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof IllegalArgumentException); assertTrue(e.getCause().getMessage().contains("No 'uri' defined for hdfs")); } } public void testEmptyUri() { try { clusterAdmin().preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "test-repo") .setType("hdfs") .setSettings(Settings.builder().put("uri", "/path").build()) .get(); fail(); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof IllegalArgumentException); assertTrue(e.getCause().getMessage(), e.getCause().getMessage().contains("Invalid scheme [null] specified in uri [/path]")); } } public void testNonHdfsUri() { try { clusterAdmin().preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "test-repo") .setType("hdfs") .setSettings(Settings.builder().put("uri", "file:///").build()) .get(); fail(); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof IllegalArgumentException); assertTrue(e.getCause().getMessage().contains("Invalid scheme [file] specified in uri [file:///]")); } } public void testPathSpecifiedInHdfs() { try { clusterAdmin().preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "test-repo") .setType("hdfs") .setSettings(Settings.builder().put("uri", "hdfs:///some/path").build()) .get(); fail(); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof IllegalArgumentException); assertTrue(e.getCause().getMessage().contains("Use 'path' option to specify a path [/some/path]")); } } public void testMissingPath() { try { clusterAdmin().preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "test-repo") .setType("hdfs") .setSettings(Settings.builder().put("uri", "hdfs:///").build()) .get(); fail(); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof IllegalArgumentException); assertTrue(e.getCause().getMessage().contains("No 'path' defined for hdfs")); } } public void testReplicationFactorBelowOne() { try { client().admin() .cluster() .preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "test-repo") .setType("hdfs") .setSettings(Settings.builder().put("uri", "hdfs:///").put("replication_factor", "0").put("path", "foo").build()) .get(); fail(); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof RepositoryException); assertTrue(e.getCause().getMessage().contains("Value of replication_factor [0] must be >= 1")); } } public void testReplicationFactorOverMaxShort() { try { client().admin() .cluster() .preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "test-repo") .setType("hdfs") .setSettings(Settings.builder().put("uri", "hdfs:///").put("replication_factor", "32768").put("path", "foo").build()) .get(); fail(); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof RepositoryException); assertTrue(e.getCause().getMessage().contains("Value of replication_factor [32768] must be <= 32767")); } } public void testReplicationFactorBelowReplicationMin() { try { client().admin() .cluster() .preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "test-repo") .setType("hdfs") .setSettings( Settings.builder() .put("uri", "hdfs:///") .put("replication_factor", "4") .put("path", "foo") .put("conf.dfs.replication.min", "5") .build() ) .get(); fail(); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof RepositoryException); assertTrue(e.getCause().getMessage().contains("Value of replication_factor [4] must be >= dfs.replication.min [5]")); } } public void testReplicationFactorOverReplicationMax() { try { client().admin() .cluster() .preparePutRepository(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "test-repo") .setType("hdfs") .setSettings( Settings.builder() .put("uri", "hdfs:///") .put("replication_factor", "600") .put("path", "foo") .put("conf.dfs.replication.max", "512") .build() ) .get(); fail(); } catch (RepositoryException e) { assertTrue(e.getCause() instanceof RepositoryException); assertTrue(e.getCause().getMessage().contains("Value of replication_factor [600] must be <= dfs.replication.max [512]")); } } private long count(Client client, String index) { return SearchResponseUtils.getTotalHitsValue(client.prepareSearch(index).setSize(0)); } }
HdfsTests
java
spring-projects__spring-boot
module/spring-boot-tomcat/src/main/java/org/springframework/boot/tomcat/TomcatEmbeddedContext.java
{ "start": 5163, "end": 5488 }
interface ____ { /** * {@link DeferredStartupExceptions} that does nothing. */ DeferredStartupExceptions NONE = () -> { }; /** * Rethrow deferred startup exceptions if there are any. * @throws Exception the deferred startup exception */ void rethrow() throws Exception; } }
DeferredStartupExceptions
java
apache__dubbo
dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/mock/MockTransporter.java
{ "start": 1151, "end": 1593 }
class ____ implements Transporter { private RemotingServer server = Mockito.mock(RemotingServer.class); private Client client = Mockito.mock(Client.class); @Override public RemotingServer bind(URL url, ChannelHandler handler) throws RemotingException { return server; } @Override public Client connect(URL url, ChannelHandler handler) throws RemotingException { return client; } }
MockTransporter
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/stream/Streams.java
{ "start": 2927, "end": 4290 }
class ____<E> implements Collector<E, List<E>, E[]> { private static final Set<Characteristics> characteristics = Collections.emptySet(); private final Class<E> elementType; /** * Constructs a new instance for the given element type. * * @param elementType The element type. */ public ArrayCollector(final Class<E> elementType) { this.elementType = Objects.requireNonNull(elementType, "elementType"); } @Override public BiConsumer<List<E>, E> accumulator() { return List::add; } @Override public Set<Characteristics> characteristics() { return characteristics; } @Override public BinaryOperator<List<E>> combiner() { return (left, right) -> { left.addAll(right); return left; }; } @Override public Function<List<E>, E[]> finisher() { return list -> list.toArray(ArrayUtils.newInstance(elementType, list.size())); } @Override public Supplier<List<E>> supplier() { return ArrayList::new; } } /** * Helps implement {@link Streams#of(Enumeration)}. * * @param <T> The element type. */ private static final
ArrayCollector
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableOnErrorNext.java
{ "start": 1655, "end": 3598 }
class ____<T> implements Observer<T> { final Observer<? super T> downstream; final Function<? super Throwable, ? extends ObservableSource<? extends T>> nextSupplier; final SequentialDisposable arbiter; boolean once; boolean done; OnErrorNextObserver(Observer<? super T> actual, Function<? super Throwable, ? extends ObservableSource<? extends T>> nextSupplier) { this.downstream = actual; this.nextSupplier = nextSupplier; this.arbiter = new SequentialDisposable(); } @Override public void onSubscribe(Disposable d) { arbiter.replace(d); } @Override public void onNext(T t) { if (done) { return; } downstream.onNext(t); } @Override public void onError(Throwable t) { if (once) { if (done) { RxJavaPlugins.onError(t); return; } downstream.onError(t); return; } once = true; ObservableSource<? extends T> p; try { p = nextSupplier.apply(t); } catch (Throwable e) { Exceptions.throwIfFatal(e); downstream.onError(new CompositeException(t, e)); return; } if (p == null) { NullPointerException npe = new NullPointerException("Observable is null"); npe.initCause(t); downstream.onError(npe); return; } p.subscribe(this); } @Override public void onComplete() { if (done) { return; } done = true; once = true; downstream.onComplete(); } } }
OnErrorNextObserver
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest15.java
{ "start": 837, "end": 1807 }
class ____ extends TestCase { public void test_true() throws Exception { assertTrue(WallUtils.isValidateMySql(// "SELECT m.*, m.icon AS micon, md.uid as md.uid, md.lastmsg,md.postnum," + "md.rvrc,md.money,md.credit,md.currency,md.lastvisit,md.thisvisit," + "md.onlinetime,md.lastpost,md.todaypost, md.monthpost,md.onlineip," + "md.uploadtime,md.uploadnum,md.starttime,md.pwdctime,md.monoltime," + "md.digests,md.f_num,md.creditpop, md.jobnum,md.lastgrab,md.follows,md.fans," + "md.newfans,md.newreferto,md.newcomment,md.postcheck,md.punch, mi.customdata " + "FROM pw_members m " + " LEFT JOIN pw_memberdata md ON m.uid=md.uid " + " LEFT JOIN pw_memberinfo mi ON mi.uid=m.uid " + "WHERE m.uid IN (?)")); } }
MySqlWallTest15
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/create/OracleCreateProcedureTest5.java
{ "start": 976, "end": 3041 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = "CREATE OR REPLACE PROCEDURE proc_helloworld\n" + "IS\n" + "BEGIN\n" + " DBMS_OUTPUT.put_line ('Hello World!');\n" + "END;"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); print(statementList); System.out.println("statementList===" + statementList); assertEquals(1, statementList.size()); SQLStatement stmt = (SQLStatement) statementList.get(0); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); stmt.accept(visitor); assertEquals("CREATE OR REPLACE PROCEDURE proc_helloworld\n" + "IS\n" + "BEGIN\n" + "\tDBMS_OUTPUT.put_line('Hello World!');\n" + "END;", stmt.toString()); assertEquals("CREATE OR REPLACE PROCEDURE proc_helloworld\n" + "IS\n" + "BEGIN\n" + "\tDBMS_OUTPUT.put_line('Hello World!');\n" + "END;", SQLUtils.toPGString(stmt)); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(0, visitor.getTables().size()); // assertTrue(visitor.getTables().containsKey(new TableStat.Name("fact_brand_provider"))); assertEquals(0, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertEquals(0, visitor.getRelationships().size()); // assertTrue(visitor.containsColumn("fact_brand_provider", "gyscode")); // assertTrue(visitor.containsColumn("fact_brand_provider", "gysname")); } }
OracleCreateProcedureTest5
java
quarkusio__quarkus
extensions/websockets-next/runtime/src/main/java/io/quarkus/websockets/next/runtime/HttpUpgradeSecurityInterceptor.java
{ "start": 241, "end": 1263 }
class ____ implements HttpUpgradeCheck { public static final int BEAN_PRIORITY = SecurityHttpUpgradeCheck.BEAN_PRIORITY + 10; private final Map<String, Consumer<RoutingContext>> endpointIdToInterceptor; HttpUpgradeSecurityInterceptor(Map<String, Consumer<RoutingContext>> endpointIdToInterceptor) { this.endpointIdToInterceptor = Map.copyOf(endpointIdToInterceptor); } @Override public Uni<CheckResult> perform(HttpUpgradeContext context) { if (context instanceof HttpUpgradeContextImpl impl) { endpointIdToInterceptor.get(context.endpointId()).accept(impl.routingContext()); return CheckResult.permitUpgrade(); } else { // this shouldn't happen and if anyone tries to change the 'impl', tests will fail return CheckResult.rejectUpgrade(500); } } @Override public boolean appliesTo(String endpointId) { return endpointIdToInterceptor.containsKey(endpointId); } }
HttpUpgradeSecurityInterceptor
java
square__retrofit
samples/src/main/java/com/example/retrofit/ErrorHandlingAdapter.java
{ "start": 2173, "end": 2889 }
class ____ extends CallAdapter.Factory { @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != MyCall.class) { return null; } if (!(returnType instanceof ParameterizedType)) { throw new IllegalStateException( "MyCall must have generic type (e.g., MyCall<ResponseBody>)"); } Type responseType = getParameterUpperBound(0, (ParameterizedType) returnType); Executor callbackExecutor = retrofit.callbackExecutor(); return new ErrorHandlingCallAdapter<>(responseType, callbackExecutor); } private static final
ErrorHandlingCallAdapterFactory
java
apache__avro
lang/java/perf/src/main/java/org/apache/avro/perf/test/basic/DoubleTest.java
{ "start": 2801, "end": 3573 }
class ____ extends BasicState { private byte[] testData; private Decoder decoder; public TestStateDecode() { super(); } /** * Generate test data. * * @throws IOException Could not setup test data */ @Setup(Level.Trial) public void doSetupTrial() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Encoder encoder = super.newEncoder(true, baos); for (int i = 0; i < getBatchSize(); i++) { encoder.writeDouble(super.getRandom().nextDouble()); } this.testData = baos.toByteArray(); } @Setup(Level.Invocation) public void doSetupInvocation() throws Exception { this.decoder = super.newDecoder(this.testData); } } }
TestStateDecode
java
junit-team__junit5
junit-jupiter-params/src/main/java/org/junit/jupiter/params/provider/EnumSource.java
{ "start": 4085, "end": 4317 }
enum ____ selection mode. * * <p>The mode only applies to the {@link #names} attribute and does not change * the behavior of {@link #from} and {@link #to}, which always define a range * based on the natural order of the
constant
java
alibaba__nacos
maintainer-client/src/main/java/com/alibaba/nacos/maintainer/client/utils/ParamUtil.java
{ "start": 6182, "end": 6544 }
class ____ remove subType JacksonUtils.registerSubtype(NoneSelector.class, SelectorType.none.name()); JacksonUtils.registerSubtype(NoneSelector.class, "NoneSelector"); JacksonUtils.registerSubtype(ExpressionSelector.class, SelectorType.label.name()); JacksonUtils.registerSubtype(ExpressionSelector.class, "LabelSelector"); } }
or
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/beanvalidation/CustomNullAndNotBlank.java
{ "start": 1024, "end": 1244 }
interface ____ { String message() default "{org.hibernate.validator.constraints.CustomNullAndNotBlank.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
CustomNullAndNotBlank
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4872ReactorResolutionAttachedWithExclusionsTest.java
{ "start": 1183, "end": 2347 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Test that resolution of (attached) artifacts from the reactor doesn't cause exclusions to be lost. * * @throws Exception in case of failure */ @Test public void testit() throws Exception { File testDir = extractResources("/mng-4872"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("consumer/target"); verifier.deleteArtifacts("org.apache.maven.its.mng4872"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); List<String> artifacts = verifier.loadLines("consumer/target/artifacts.txt"); assertTrue(artifacts.contains("org.apache.maven.its.mng4872:producer:jar:0.1"), artifacts.toString()); assertTrue(artifacts.contains("org.apache.maven.its.mng4872:producer:jar:shaded:0.1"), artifacts.toString()); assertFalse(artifacts.contains("org.apache.maven.its.mng4872:excluded:jar:0.1"), artifacts.toString()); } }
MavenITmng4872ReactorResolutionAttachedWithExclusionsTest
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/scripting/bsh/BshScriptFactory.java
{ "start": 2249, "end": 7126 }
class ____ return an actual instance of the scripted object. * @param scriptSourceLocator a locator that points to the source of the script. * Interpreted by the post-processor that actually creates the script. */ public BshScriptFactory(String scriptSourceLocator) { Assert.hasText(scriptSourceLocator, "'scriptSourceLocator' must not be empty"); this.scriptSourceLocator = scriptSourceLocator; this.scriptInterfaces = null; } /** * Create a new BshScriptFactory for the given script source. * <p>The script may either be a simple script that needs a corresponding proxy * generated (implementing the specified interfaces), or declare a full class * or return an actual instance of the scripted object (in which case the * specified interfaces, if any, need to be implemented by that class/instance). * @param scriptSourceLocator a locator that points to the source of the script. * Interpreted by the post-processor that actually creates the script. * @param scriptInterfaces the Java interfaces that the scripted object * is supposed to implement (may be {@code null}) */ public BshScriptFactory(String scriptSourceLocator, Class<?> @Nullable ... scriptInterfaces) { Assert.hasText(scriptSourceLocator, "'scriptSourceLocator' must not be empty"); this.scriptSourceLocator = scriptSourceLocator; this.scriptInterfaces = scriptInterfaces; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } @Override public String getScriptSourceLocator() { return this.scriptSourceLocator; } @Override public Class<?> @Nullable [] getScriptInterfaces() { return this.scriptInterfaces; } /** * BeanShell scripts do require a config interface. */ @Override public boolean requiresConfigInterface() { return true; } /** * Load and parse the BeanShell script via {@link BshScriptUtils}. * @see BshScriptUtils#createBshObject(String, Class[], ClassLoader) */ @Override public @Nullable Object getScriptedObject(ScriptSource scriptSource, Class<?> @Nullable ... actualInterfaces) throws IOException, ScriptCompilationException { Class<?> clazz; try { synchronized (this.scriptClassMonitor) { boolean requiresScriptEvaluation = (this.wasModifiedForTypeCheck && this.scriptClass == null); this.wasModifiedForTypeCheck = false; if (scriptSource.isModified() || requiresScriptEvaluation) { // New script content: Let's check whether it evaluates to a Class. Object result = BshScriptUtils.evaluateBshScript( scriptSource.getScriptAsString(), actualInterfaces, this.beanClassLoader); if (result instanceof Class<?> type) { // A Class: We'll cache the Class here and create an instance // outside the synchronized block. this.scriptClass = type; } else { // Not a Class: OK, we'll simply create BeanShell objects // through evaluating the script for every call later on. // For this first-time check, let's simply return the // already evaluated object. return result; } } clazz = this.scriptClass; } } catch (EvalError ex) { this.scriptClass = null; throw new ScriptCompilationException(scriptSource, ex); } if (clazz != null) { // A Class: We need to create an instance for every call. try { return ReflectionUtils.accessibleConstructor(clazz).newInstance(); } catch (Throwable ex) { throw new ScriptCompilationException( scriptSource, "Could not instantiate script class: " + clazz.getName(), ex); } } else { // Not a Class: We need to evaluate the script for every call. try { return BshScriptUtils.createBshObject( scriptSource.getScriptAsString(), actualInterfaces, this.beanClassLoader); } catch (EvalError ex) { throw new ScriptCompilationException(scriptSource, ex); } } } @Override public @Nullable Class<?> getScriptedObjectType(ScriptSource scriptSource) throws IOException, ScriptCompilationException { synchronized (this.scriptClassMonitor) { try { if (scriptSource.isModified()) { // New script content: Let's check whether it evaluates to a Class. this.wasModifiedForTypeCheck = true; this.scriptClass = BshScriptUtils.determineBshObjectType( scriptSource.getScriptAsString(), this.beanClassLoader); } return this.scriptClass; } catch (EvalError ex) { this.scriptClass = null; throw new ScriptCompilationException(scriptSource, ex); } } } @Override public boolean requiresScriptedObjectRefresh(ScriptSource scriptSource) { synchronized (this.scriptClassMonitor) { return (scriptSource.isModified() || this.wasModifiedForTypeCheck); } } @Override public String toString() { return "BshScriptFactory: script source locator [" + this.scriptSourceLocator + "]"; } }
or
java
google__guava
guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
{ "start": 24836, "end": 25175 }
class ____ extends PassObject { @Override public void twoNullableArgs(@Nullable String s, @Nullable Integer i) { i.intValue(); // ok to throw NPE? } } public void testPassTwoNullableArgsSecondThrowsNpe() { shouldPass(new PassTwoNullableArgsSecondThrowsNpe()); } private static
PassTwoNullableArgsSecondThrowsNpe
java
quarkusio__quarkus
integration-tests/jpa/src/main/java/io/quarkus/it/jpa/util/BeanInstantiator.java
{ "start": 92, "end": 1055 }
enum ____ { HIBERNATE, ARC; public static BeanInstantiator fromCaller() { return Arrays.stream(Thread.currentThread().getStackTrace()) .map(e -> { var className = e.getClassName(); if (className.startsWith("io.quarkus.it.")) { // Class from this integration test: ignore. return null; } if (className.startsWith("io.quarkus.")) { return ARC; } if (className.startsWith("org.hibernate.")) { return HIBERNATE; } else { return null; } }) .filter(Objects::nonNull) .findFirst() .orElseThrow(() -> new IllegalStateException("Could not determine bean instantiator")); } }
BeanInstantiator
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/conversion/currency/CurrencyConversionTest.java
{ "start": 666, "end": 2083 }
class ____ { @ProcessorTest public void shouldApplyCurrencyConversions() { final CurrencySource source = new CurrencySource(); source.setCurrencyA( Currency.getInstance( "USD" ) ); Set<Currency> currencies = new HashSet<>(); currencies.add( Currency.getInstance( "EUR" ) ); currencies.add( Currency.getInstance( "CHF" ) ); source.setUniqueCurrencies( currencies ); CurrencyTarget target = CurrencyMapper.INSTANCE.currencySourceToCurrencyTarget( source ); assertThat( target ).isNotNull(); assertThat( target.getCurrencyA() ).isEqualTo( "USD" ); assertThat( target.getUniqueCurrencies() ) .isNotEmpty() .containsExactlyInAnyOrder( "EUR", "CHF" ); } @ProcessorTest public void shouldApplyReverseConversions() { final CurrencyTarget target = new CurrencyTarget(); target.setCurrencyA( "USD" ); target.setUniqueCurrencies( Collections.asSet( "JPY" ) ); CurrencySource source = CurrencyMapper.INSTANCE.currencyTargetToCurrencySource( target ); assertThat( source ).isNotNull(); assertThat( source.getCurrencyA().getCurrencyCode() ).isEqualTo( Currency.getInstance( "USD" ) .getCurrencyCode() ); assertThat( source.getUniqueCurrencies() ).containsExactlyInAnyOrder( Currency.getInstance( "JPY" ) ); } }
CurrencyConversionTest
java
spring-projects__spring-framework
spring-jms/src/test/java/org/springframework/jms/config/JmsNamespaceHandlerTests.java
{ "start": 19428, "end": 19867 }
class ____ extends EmptyReaderEventListener { protected final Set<ComponentDefinition> registeredComponents; public StoringReaderEventListener(Set<ComponentDefinition> registeredComponents) { this.registeredComponents = registeredComponents; } @Override public void componentRegistered(ComponentDefinition componentDefinition) { this.registeredComponents.add(componentDefinition); } } static
StoringReaderEventListener
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/producer/internals/TransactionManager.java
{ "start": 78901, "end": 82272 }
class ____ extends TxnRequestHandler { private final FindCoordinatorRequest.Builder builder; private FindCoordinatorHandler(FindCoordinatorRequest.Builder builder) { super("FindCoordinator"); this.builder = builder; } @Override FindCoordinatorRequest.Builder requestBuilder() { return builder; } @Override Priority priority() { return Priority.FIND_COORDINATOR; } @Override FindCoordinatorRequest.CoordinatorType coordinatorType() { return null; } @Override String coordinatorKey() { return null; } @Override public void handleResponse(AbstractResponse response) { CoordinatorType coordinatorType = CoordinatorType.forId(builder.data().keyType()); List<Coordinator> coordinators = ((FindCoordinatorResponse) response).coordinators(); if (coordinators.size() != 1) { log.error("Group coordinator lookup failed: Invalid response containing more than a single coordinator"); fatalError(new IllegalStateException("Group coordinator lookup failed: Invalid response containing more than a single coordinator")); } Coordinator coordinatorData = coordinators.get(0); // For older versions without batching, obtain key from request data since it is not included in response String key = coordinatorData.key() == null ? builder.data().key() : coordinatorData.key(); Errors error = Errors.forCode(coordinatorData.errorCode()); if (error == Errors.NONE) { Node node = new Node(coordinatorData.nodeId(), coordinatorData.host(), coordinatorData.port()); switch (coordinatorType) { case GROUP: consumerGroupCoordinator = node; break; case TRANSACTION: transactionCoordinator = node; break; default: log.error("Group coordinator lookup failed: Unexpected coordinator type in response"); fatalError(new IllegalStateException("Group coordinator lookup failed: Unexpected coordinator type in response")); } result.done(); log.info("Discovered {} coordinator {}", coordinatorType.toString().toLowerCase(Locale.ROOT), node); } else if (error.exception() instanceof RetriableException) { reenqueue(); } else if (error == Errors.TRANSACTIONAL_ID_AUTHORIZATION_FAILED) { fatalError(error.exception()); } else if (error == Errors.GROUP_AUTHORIZATION_FAILED) { abortableError(GroupAuthorizationException.forGroupId(key)); } else if (error == Errors.TRANSACTION_ABORTABLE) { abortableError(error.exception()); } else { fatalError(new KafkaException(String.format("Could not find a coordinator with type %s with key %s due to " + "unexpected error: %s", coordinatorType, key, coordinatorData.errorMessage()))); } } } private
FindCoordinatorHandler
java
apache__spark
launcher/src/main/java/org/apache/spark/launcher/AbstractLauncher.java
{ "start": 991, "end": 1066 }
class ____ launcher implementations. * * @since 2.3.0 */ public abstract
for
java
elastic__elasticsearch
test/framework/src/main/java/org/elasticsearch/test/LambdaMatchers.java
{ "start": 869, "end": 2769 }
class ____<T, U> extends TypeSafeMatcher<T> { private final String transformDescription; private final Matcher<U> matcher; private final Function<T, U> transform; private TransformMatcher(String transformDescription, Matcher<U> matcher, Function<T, U> transform) { this.transformDescription = transformDescription; this.matcher = matcher; this.transform = transform; } @Override protected boolean matchesSafely(T item) { U u; try { u = transform.apply(item); } catch (ClassCastException e) { throw new AssertionError(e); } return matcher.matches(u); } @Override protected void describeMismatchSafely(T item, Description description) { U u; try { u = transform.apply(item); } catch (ClassCastException e) { description.appendValue(item).appendText(" is not of the correct type (").appendText(e.getMessage()).appendText(")"); return; } description.appendText(transformDescription).appendText(" "); matcher.describeMismatch(u, description); } @Override public void describeTo(Description description) { description.appendText(transformDescription).appendText(" matches ").appendDescriptionOf(matcher); } } public static <T, U> Matcher<T> transformedMatch(Function<T, U> function, Matcher<U> matcher) { return new TransformMatcher<>("transformed value", matcher, function); } public static <T, U> Matcher<T> transformedMatch(String description, Function<T, U> function, Matcher<U> matcher) { return new TransformMatcher<>(description, matcher, function); } private static
TransformMatcher
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/EventbridgeEndpointBuilderFactory.java
{ "start": 1441, "end": 1578 }
interface ____ { /** * Builder for endpoint for the AWS Eventbridge component. */ public
EventbridgeEndpointBuilderFactory
java
square__retrofit
retrofit-adapters/rxjava/src/main/java/retrofit2/adapter/rxjava/CallEnqueueOnSubscribe.java
{ "start": 809, "end": 1718 }
class ____<T> implements OnSubscribe<Response<T>> { private final Call<T> originalCall; CallEnqueueOnSubscribe(Call<T> originalCall) { this.originalCall = originalCall; } @Override public void call(Subscriber<? super Response<T>> subscriber) { // Since Call is a one-shot type, clone it for each new subscriber. Call<T> call = originalCall.clone(); final CallArbiter<T> arbiter = new CallArbiter<>(call, subscriber); subscriber.add(arbiter); subscriber.setProducer(arbiter); call.enqueue( new Callback<T>() { @Override public void onResponse(Call<T> call, Response<T> response) { arbiter.emitResponse(response); } @Override public void onFailure(Call<T> call, Throwable t) { Exceptions.throwIfFatal(t); arbiter.emitError(t); } }); } }
CallEnqueueOnSubscribe
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/federation/store/FederationApplicationHomeSubClusterStore.java
{ "start": 2383, "end": 5808 }
interface ____ { /** * Register the home {@code SubClusterId} of the newly submitted * {@code ApplicationId}. Currently response is empty if the operation was * successful, if not an exception reporting reason for a failure. If a * mapping for the application already existed, the {@code SubClusterId} in * this response will return the existing mapping which might be different * from that in the {@code AddApplicationHomeSubClusterRequest}. * * @param request the request to register a new application with its home * sub-cluster * @return upon successful registration of the application in the StateStore, * {@code AddApplicationHomeSubClusterRequest} containing the home * sub-cluster of the application. Otherwise, an exception reporting * reason for a failure * @throws YarnException if the request is invalid/fails */ AddApplicationHomeSubClusterResponse addApplicationHomeSubCluster( AddApplicationHomeSubClusterRequest request) throws YarnException; /** * Update the home {@code SubClusterId} of a previously submitted * {@code ApplicationId}. Currently response is empty if the operation was * successful, if not an exception reporting reason for a failure. * * @param request the request to update the home sub-cluster of an * application. * @return empty on successful update of the application in the StateStore, if * not an exception reporting reason for a failure * @throws YarnException if the request is invalid/fails */ UpdateApplicationHomeSubClusterResponse updateApplicationHomeSubCluster( UpdateApplicationHomeSubClusterRequest request) throws YarnException; /** * Get information about the application identified by the input * {@code ApplicationId}. * * @param request contains the application queried * @return {@code ApplicationHomeSubCluster} containing the application's home * subcluster * @throws YarnException if the request is invalid/fails */ GetApplicationHomeSubClusterResponse getApplicationHomeSubCluster( GetApplicationHomeSubClusterRequest request) throws YarnException; /** * Get the {@code ApplicationHomeSubCluster} list representing the mapping of * all submitted applications to it's home sub-cluster. * * @param request empty representing all applications * @return the mapping of all submitted application to it's home sub-cluster * @throws YarnException if the request is invalid/fails */ GetApplicationsHomeSubClusterResponse getApplicationsHomeSubCluster( GetApplicationsHomeSubClusterRequest request) throws YarnException; /** * Delete the mapping of home {@code SubClusterId} of a previously submitted * {@code ApplicationId}. Currently response is empty if the operation was * successful, if not an exception reporting reason for a failure. * * @param request the request to delete the home sub-cluster of an * application. * @return empty on successful update of the application in the StateStore, if * not an exception reporting reason for a failure * @throws YarnException if the request is invalid/fails */ DeleteApplicationHomeSubClusterResponse deleteApplicationHomeSubCluster( DeleteApplicationHomeSubClusterRequest request) throws YarnException; }
FederationApplicationHomeSubClusterStore
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/codec/CipherCodecUnitTests.java
{ "start": 874, "end": 4526 }
class ____ { private final SecretKeySpec key = new SecretKeySpec("1234567890123456".getBytes(), "AES"); private final IvParameterSpec iv = new IvParameterSpec("1234567890123456".getBytes()); private final String transform = "AES/CBC/PKCS5Padding"; CipherCodec.CipherSupplier encrypt = new CipherCodec.CipherSupplier() { @Override public Cipher get(CipherCodec.KeyDescriptor keyDescriptor) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance(transform); cipher.init(Cipher.ENCRYPT_MODE, key, iv); return cipher; } @Override public CipherCodec.KeyDescriptor encryptionKey() { return CipherCodec.KeyDescriptor.create("foobar", 142); } }; CipherCodec.CipherSupplier decrypt = (CipherCodec.KeyDescriptor keyDescriptor) -> { Cipher cipher = Cipher.getInstance(transform); cipher.init(Cipher.DECRYPT_MODE, key, iv); return cipher; }; @ParameterizedTest @MethodSource("cryptoTestValues") void shouldEncryptValue(CryptoTestArgs testArgs) { RedisCodec<String, String> crypto = CipherCodec.forValues(StringCodec.UTF8, encrypt, decrypt); ByteBuffer encrypted = crypto.encodeValue(testArgs.content); assertThat(encrypted).isNotEqualTo(ByteBuffer.wrap(testArgs.content.getBytes())); assertThat(new String(encrypted.array())).startsWith("$foobar+142$"); String decrypted = crypto.decodeValue(encrypted); assertThat(decrypted).isEqualTo(testArgs.content); assertThat(StringCodec.UTF8.encodeValue(testArgs.content)).isEqualTo(ByteBuffer.wrap(testArgs.content.getBytes())); } @ParameterizedTest @MethodSource("cryptoTestValues") void shouldEncryptValueToByteBuf(CryptoTestArgs testArgs) { RedisCodec<String, String> crypto = CipherCodec.forValues(StringCodec.UTF8, encrypt, decrypt); ToByteBufEncoder<String, String> direct = (ToByteBufEncoder<String, String>) crypto; ByteBufAllocator allocator = ByteBufAllocator.DEFAULT; ByteBuf target = allocator.buffer(); direct.encodeValue(testArgs.content, target); assertThat(target).isNotEqualTo(Unpooled.wrappedBuffer(testArgs.content.getBytes())); assertThat(target.toString(0, 20, StandardCharsets.US_ASCII)).startsWith("$foobar+142$"); String result = crypto.decodeValue(target.nioBuffer()); assertThat(result).isEqualTo(testArgs.content); } static List<CryptoTestArgs> cryptoTestValues() { StringBuilder hugeString = new StringBuilder(); for (int i = 0; i < 1000; i++) { hugeString.append(UUID.randomUUID().toString()); } return Arrays.asList(new CryptoTestArgs("foobar"), new CryptoTestArgs(hugeString.toString())); } @Test void shouldDecryptValue() { RedisCodec<String, String> crypto = CipherCodec.forValues(StringCodec.UTF8, encrypt, decrypt); ByteBuffer encrypted = ByteBuffer.wrap( new byte[] { 36, 43, 48, 36, -99, -39, 126, -106, -7, -88, 118, -74, 42, 98, 117, 81, 37, -124, 26, -88 });// crypto.encodeValue("foobar"); String result = crypto.decodeValue(encrypted); assertThat(result).isEqualTo("foobar"); } @Test void shouldRejectPlusAndDollarKeyNames() { assertThatThrownBy(() -> CipherCodec.KeyDescriptor.create("my+key")).isInstanceOf(IllegalArgumentException.class); assertThatThrownBy(() -> CipherCodec.KeyDescriptor.create("my$key")).isInstanceOf(IllegalArgumentException.class); } static
CipherCodecUnitTests
java
micronaut-projects__micronaut-core
http-server-netty/src/main/java/io/micronaut/http/server/netty/AbstractNettyHttpRequest.java
{ "start": 1854, "end": 9278 }
class ____<B> extends DefaultAttributeMap implements HttpRequest<B>, NettyHttpRequestBuilder { protected final io.netty.handler.codec.http.HttpRequest nettyRequest; protected final ConversionService conversionService; protected final HttpMethod httpMethod; protected final String unvalidatedUrl; protected final String httpMethodName; private volatile URI uri; private volatile NettyHttpParameters httpParameters; private volatile Charset charset; private volatile String path; /** * @param nettyRequest The Http netty request * @param conversionService The conversion service * @param escapeHtmlUrl {@link HttpServerConfiguration#isEscapeHtmlUrl()} */ public AbstractNettyHttpRequest(io.netty.handler.codec.http.HttpRequest nettyRequest, ConversionService conversionService, boolean escapeHtmlUrl) { this.nettyRequest = nettyRequest; this.conversionService = conversionService; String uri = nettyRequest.uri(); if (!UriUtil.isValidPath(uri)) { if (escapeHtmlUrl && UriUtil.isRelative(uri)) { uri = UriUtil.toValidPath(uri); } this.uri = createURI(uri); } this.unvalidatedUrl = uri; this.httpMethodName = nettyRequest.method().name(); this.httpMethod = HttpMethod.parse(httpMethodName); } @Override public io.netty.handler.codec.http.@NonNull HttpRequest toHttpRequest() { return this.nettyRequest; } @Override public io.netty.handler.codec.http.@NonNull FullHttpRequest toFullHttpRequest() { if (this.nettyRequest instanceof io.netty.handler.codec.http.FullHttpRequest request) { return request; } DefaultFullHttpRequest httpRequest = new DefaultFullHttpRequest( this.nettyRequest.protocolVersion(), this.nettyRequest.method(), this.nettyRequest.uri() ); httpRequest.headers().setAll(this.nettyRequest.headers()); return httpRequest; } @NonNull @Override public StreamedHttpRequest toStreamHttpRequest() { if (isStream()) { return (StreamedHttpRequest) this.nettyRequest; } else { if (this.nettyRequest instanceof io.netty.handler.codec.http.FullHttpRequest request) { return new DefaultStreamedHttpRequest( io.netty.handler.codec.http.HttpVersion.HTTP_1_1, this.nettyRequest.method(), this.nettyRequest.uri(), true, Publishers.just(new DefaultLastHttpContent(request.content())) ); } else { return new DefaultStreamedHttpRequest( io.netty.handler.codec.http.HttpVersion.HTTP_1_1, this.nettyRequest.method(), this.nettyRequest.uri(), true, Publishers.just(LastHttpContent.EMPTY_LAST_CONTENT) ); } } } @Override public boolean isStream() { return this.nettyRequest instanceof StreamedHttpRequest; } /** * @return The native netty request */ public io.netty.handler.codec.http.HttpRequest getNettyRequest() { return nettyRequest; } @Override public HttpParameters getParameters() { NettyHttpParameters params = this.httpParameters; if (params == null) { synchronized (this) { // double check params = this.httpParameters; if (params == null) { params = decodeParameters(); this.httpParameters = params; } } } return params; } @Override public Charset getCharacterEncoding() { if (charset == null) { charset = initCharset(HttpRequest.super.getCharacterEncoding()); } return charset; } @Override public HttpMethod getMethod() { return httpMethod; } @Override public URI getUri() { URI u = this.uri; if (u == null) { u = createURI(unvalidatedUrl); this.uri = u; } return u; } @Override public String getPath() { String p = this.path; if (p == null) { p = parsePath(unvalidatedUrl); this.path = p; } return p; } /** * @param characterEncoding The character encoding * @return The Charset */ protected abstract Charset initCharset(Charset characterEncoding); /** * @return the maximum number of parameters. */ protected abstract int getMaxParams(); /** * @return {@code true} if yes, {@code false} otherwise. */ protected abstract boolean isSemicolonIsNormalChar(); /** * @param uri The URI * @return The query string decoder */ @SuppressWarnings("ConstantConditions") protected final QueryStringDecoder createDecoder(URI uri) { Charset cs = getCharacterEncoding(); boolean semicolonIsNormalChar = isSemicolonIsNormalChar(); int maxParams = getMaxParams(); return cs != null ? new QueryStringDecoder(uri, cs, maxParams, semicolonIsNormalChar) : new QueryStringDecoder(uri, HttpConstants.DEFAULT_CHARSET, maxParams, semicolonIsNormalChar); } private NettyHttpParameters decodeParameters() { QueryStringDecoder queryStringDecoder = createDecoder(getUri()); return new NettyHttpParameters(queryStringDecoder.parameters(), conversionService, null); } @Override public String getMethodName() { return httpMethodName; } private static URI createURI(String url) { URI fullUri = URI.create(url); if (fullUri.getAuthority() != null || fullUri.getScheme() != null) { // https://example.com/foo -> /foo try { fullUri = new URI( null, // scheme null, // authority fullUri.getPath(), fullUri.getQuery(), fullUri.getFragment() ); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } } return fullUri; } /** * Extract the path out of the uri. * https://github.com/eclipse-vertx/vert.x/blob/master/src/main/java/io/vertx/core/http/impl/HttpUtils.java */ private static String parsePath(String uri) { if (uri.isEmpty()) { return ""; } int i; if (uri.charAt(0) == '/') { i = 0; } else { i = uri.indexOf("://"); if (i == -1) { i = 0; } else { i = uri.indexOf('/', i + 3); if (i == -1) { // contains no / return "/"; } } } int queryStart = uri.indexOf('?', i); if (queryStart == -1) { queryStart = uri.length(); if (i == 0) { return uri; } } return uri.substring(i, queryStart); } }
AbstractNettyHttpRequest
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/support/MessageSourceAccessor.java
{ "start": 986, "end": 1347 }
class ____ easy access to messages from a MessageSource, * providing various overloaded getMessage methods. * * <p>Available from ApplicationObjectSupport, but also reusable * as a standalone helper to delegate to in application objects. * * @author Juergen Hoeller * @since 23.10.2003 * @see ApplicationObjectSupport#getMessageSourceAccessor */ public
for
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/CamelCaseInsentiveHeadersTrueTest.java
{ "start": 1011, "end": 2097 }
class ____ extends ContextTestSupport { @Override protected CamelContext createCamelContext() throws Exception { CamelContext context = super.createCamelContext(); context.setCaseInsensitiveHeaders(true); return context; } @Test public void testCasesensitive() throws Exception { getMockEndpoint("mock:foo").expectedBodiesReceived("Hello foo", "Hello bar"); getMockEndpoint("mock:bar").expectedMessageCount(0); template.sendBodyAndHeader("direct:start", "Hello foo", "foo", "123"); template.sendBodyAndHeader("direct:start", "Hello bar", "FOO", "456"); assertMockEndpointsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .choice() .when(header("foo")).to("mock:foo") .otherwise().to("mock:bar"); } }; } }
CamelCaseInsentiveHeadersTrueTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskManagerRunnerStartupTest.java
{ "start": 3389, "end": 14070 }
class ____ { private static final String LOCAL_HOST = "localhost"; @RegisterExtension public static final AllCallbackWrapper<TestingRpcServiceExtension> RPC_SERVICE_EXTENSION_WRAPPER = new AllCallbackWrapper<>(new TestingRpcServiceExtension()); @TempDir public Path tempFolder; @TempDir public static File workingDirectoryFolder; @RegisterExtension private static final AllCallbackWrapper<WorkingDirectoryExtension> WORKING_DIRECTORY_EXTENSION_WRAPPER = new AllCallbackWrapper<>( new WorkingDirectoryExtension(() -> workingDirectoryFolder)); private final RpcService rpcService = RPC_SERVICE_EXTENSION_WRAPPER.getCustomExtension().getTestingRpcService(); private TestingHighAvailabilityServices highAvailabilityServices; @BeforeEach void setupTest() { highAvailabilityServices = new TestingHighAvailabilityServices(); highAvailabilityServices.setResourceManagerLeaderRetriever( new SettableLeaderRetrievalService()); } @AfterEach void tearDownTest() throws Exception { highAvailabilityServices.closeWithOptionalClean(true); highAvailabilityServices = null; } /** * Tests that the TaskManagerRunner startup fails synchronously when the I/O directories are not * writable. */ @Tag("org.apache.flink.testutils.junit.FailsInGHAContainerWithRootUser") @Test void testIODirectoryNotWritable() throws Exception { File nonWritable = TempDirUtils.newFolder(tempFolder); Assumptions.assumeTrue( nonWritable.setWritable(false, false), "Cannot create non-writable temporary file directory. Skipping test."); try { Configuration cfg = createFlinkConfiguration(); cfg.set(CoreOptions.TMP_DIRS, nonWritable.getAbsolutePath()); assertThatThrownBy( () -> startTaskManager( cfg, rpcService, highAvailabilityServices, WORKING_DIRECTORY_EXTENSION_WRAPPER .getCustomExtension() .createNewWorkingDirectory()), "Should fail synchronously with an IOException") .isInstanceOf(IOException.class); } finally { // noinspection ResultOfMethodCallIgnored nonWritable.setWritable(true, false); try { FileUtils.deleteDirectory(nonWritable); } catch (IOException e) { // best effort } } } /** * Tests that the TaskManagerRunner startup fails synchronously when the memory configuration is * wrong. */ @Test void testMemoryConfigWrong() { Configuration cfg = createFlinkConfiguration(); // something invalid cfg.set(TaskManagerOptions.NETWORK_MEMORY_MIN, MemorySize.parse("100m")); cfg.set(TaskManagerOptions.NETWORK_MEMORY_MAX, MemorySize.parse("10m")); assertThatThrownBy( () -> startTaskManager( cfg, rpcService, highAvailabilityServices, WORKING_DIRECTORY_EXTENSION_WRAPPER .getCustomExtension() .createNewWorkingDirectory())) .isInstanceOf(IllegalConfigurationException.class); } /** * Tests that the TaskManagerRunner startup fails if the network stack cannot be initialized. */ @Test void testStartupWhenNetworkStackFailsToInitialize() throws Exception { final ServerSocket blocker = new ServerSocket(0, 50, InetAddress.getByName(LOCAL_HOST)); try { final Configuration cfg = createFlinkConfiguration(); cfg.set(NettyShuffleEnvironmentOptions.DATA_PORT, blocker.getLocalPort()); cfg.set(TaskManagerOptions.BIND_HOST, LOCAL_HOST); assertThatThrownBy( () -> startTaskManager( cfg, rpcService, highAvailabilityServices, WORKING_DIRECTORY_EXTENSION_WRAPPER .getCustomExtension() .createNewWorkingDirectory()), "Should throw IOException when the network stack cannot be initialized.") .isInstanceOf(IOException.class); } finally { IOUtils.closeQuietly(blocker); } } /** Checks that all expected metrics are initialized. */ @Test void testMetricInitialization() throws Exception { Configuration cfg = createFlinkConfiguration(); List<String> registeredMetrics = new ArrayList<>(); startTaskManager( cfg, rpcService, highAvailabilityServices, WORKING_DIRECTORY_EXTENSION_WRAPPER .getCustomExtension() .createNewWorkingDirectory(), TestingMetricRegistry.builder() .setRegisterConsumer( (metric, metricName, group) -> registeredMetrics.add( group.getMetricIdentifier(metricName))) .setScopeFormats(ScopeFormats.fromConfig(cfg)) .build()); // GC-related metrics are not checked since their existence depends on the JVM used Set<String> expectedTaskManagerMetricsWithoutTaskManagerId = Sets.newHashSet( ".taskmanager..Status.JVM.ClassLoader.ClassesLoaded", ".taskmanager..Status.JVM.ClassLoader.ClassesUnloaded", ".taskmanager..Status.JVM.Memory.Heap.Used", ".taskmanager..Status.JVM.Memory.Heap.Committed", ".taskmanager..Status.JVM.Memory.Heap.Max", ".taskmanager..Status.JVM.Memory.NonHeap.Used", ".taskmanager..Status.JVM.Memory.NonHeap.Committed", ".taskmanager..Status.JVM.Memory.NonHeap.Max", ".taskmanager..Status.JVM.Memory.Direct.Count", ".taskmanager..Status.JVM.Memory.Direct.MemoryUsed", ".taskmanager..Status.JVM.Memory.Direct.TotalCapacity", ".taskmanager..Status.JVM.Memory.Mapped.Count", ".taskmanager..Status.JVM.Memory.Mapped.MemoryUsed", ".taskmanager..Status.JVM.Memory.Mapped.TotalCapacity", ".taskmanager..Status.Flink.Memory.Managed.Used", ".taskmanager..Status.Flink.Memory.Managed.Total", ".taskmanager..Status.JVM.Threads.Count", ".taskmanager..Status.JVM.CPU.Load", ".taskmanager..Status.JVM.CPU.Time", ".taskmanager..Status.Shuffle.Netty.TotalMemorySegments", ".taskmanager..Status.Shuffle.Netty.TotalMemory", ".taskmanager..Status.Shuffle.Netty.AvailableMemorySegments", ".taskmanager..Status.Shuffle.Netty.AvailableMemory", ".taskmanager..Status.Shuffle.Netty.UsedMemorySegments", ".taskmanager..Status.Shuffle.Netty.UsedMemory"); Pattern pattern = Pattern.compile("\\.taskmanager\\.([^.]+)\\..*"); Set<String> registeredMetricsWithoutTaskManagerId = registeredMetrics.stream() .map(pattern::matcher) .flatMap( matcher -> matcher.find() ? Stream.of( matcher.group(0) .replaceAll(matcher.group(1), "")) : Stream.empty()) .collect(Collectors.toSet()); assertThat(expectedTaskManagerMetricsWithoutTaskManagerId) .allSatisfy(ele -> assertThat(ele).isIn(registeredMetricsWithoutTaskManagerId)); } // ----------------------------------------------------------------------------------------------- private static Configuration createFlinkConfiguration() { return TaskExecutorResourceUtils.adjustForLocalExecution(new Configuration()); } private static void startTaskManager( Configuration configuration, RpcService rpcService, HighAvailabilityServices highAvailabilityServices, WorkingDirectory workingDirectory) throws Exception { startTaskManager( configuration, rpcService, highAvailabilityServices, workingDirectory, NoOpMetricRegistry.INSTANCE); } private static void startTaskManager( Configuration configuration, RpcService rpcService, HighAvailabilityServices highAvailabilityServices, WorkingDirectory workingDirectory, MetricRegistry metricRegistry) throws Exception { TaskManagerRunner.startTaskManager( configuration, ResourceID.generate(), rpcService, highAvailabilityServices, new TestingHeartbeatServices(), metricRegistry, NoOpTaskExecutorBlobService.INSTANCE, false, ExternalResourceInfoProvider.NO_EXTERNAL_RESOURCES, workingDirectory, error -> {}, new DelegationTokenReceiverRepository(configuration, null)); } }
TaskManagerRunnerStartupTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalExtendedStats.java
{ "start": 1362, "end": 10306 }
enum ____ { count, sum, min, max, avg, sum_of_squares, variance, variance_population, variance_sampling, std_deviation, std_deviation_population, std_deviation_sampling, std_upper, std_lower, std_upper_population, std_lower_population, std_upper_sampling, std_lower_sampling; public static Metrics resolve(String name) { return Metrics.valueOf(name); } public static boolean hasMetric(String name) { try { InternalExtendedStats.Metrics.resolve(name); return true; } catch (IllegalArgumentException iae) { return false; } } } static final Set<String> METRIC_NAMES = Collections.unmodifiableSet( Stream.of(Metrics.values()).map(Metrics::name).collect(Collectors.toSet()) ); private final double sumOfSqrs; private final double sigma; public InternalExtendedStats( String name, long count, double sum, double min, double max, double sumOfSqrs, double sigma, DocValueFormat formatter, Map<String, Object> metadata ) { super(name, count, sum, min, max, formatter, metadata); this.sumOfSqrs = sumOfSqrs; this.sigma = sigma; } /** * Read from a stream. */ public InternalExtendedStats(StreamInput in) throws IOException { super(in); sumOfSqrs = in.readDouble(); sigma = in.readDouble(); } @Override protected void writeOtherStatsTo(StreamOutput out) throws IOException { out.writeDouble(sumOfSqrs); out.writeDouble(sigma); } @Override public String getWriteableName() { return ExtendedStatsAggregationBuilder.NAME; } static InternalExtendedStats empty(String name, double sigma, DocValueFormat format, Map<String, Object> metadata) { return new InternalExtendedStats(name, 0, 0d, Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 0d, sigma, format, metadata); } @Override public double value(String name) { if ("sum_of_squares".equals(name)) { return sumOfSqrs; } if ("variance".equals(name)) { return getVariance(); } if ("variance_population".equals(name)) { return getVariancePopulation(); } if ("variance_sampling".equals(name)) { return getVarianceSampling(); } if ("std_deviation".equals(name)) { return getStdDeviation(); } if ("std_deviation_population".equals(name)) { return getStdDeviationPopulation(); } if ("std_deviation_sampling".equals(name)) { return getStdDeviationSampling(); } if ("std_upper".equals(name)) { return getStdDeviationBound(Bounds.UPPER); } if ("std_lower".equals(name)) { return getStdDeviationBound(Bounds.LOWER); } if ("std_upper_population".equals(name)) { return getStdDeviationBound(Bounds.UPPER_POPULATION); } if ("std_lower_population".equals(name)) { return getStdDeviationBound(Bounds.LOWER_POPULATION); } if ("std_upper_sampling".equals(name)) { return getStdDeviationBound(Bounds.UPPER_SAMPLING); } if ("std_lower_sampling".equals(name)) { return getStdDeviationBound(Bounds.LOWER_SAMPLING); } return super.value(name); } @Override public Iterable<String> valueNames() { return METRIC_NAMES; } public double getSigma() { return this.sigma; } @Override public double getSumOfSquares() { return sumOfSqrs; } @Override public double getVariance() { return getVariancePopulation(); } @Override public double getVariancePopulation() { double variance = (sumOfSqrs - ((sum * sum) / count)) / count; return variance < 0 ? 0 : variance; } @Override public double getVarianceSampling() { double variance = (sumOfSqrs - ((sum * sum) / count)) / (count - 1); return variance < 0 ? 0 : variance; } @Override public double getStdDeviation() { return getStdDeviationPopulation(); } @Override public double getStdDeviationPopulation() { return Math.sqrt(getVariancePopulation()); } @Override public double getStdDeviationSampling() { return Math.sqrt(getVarianceSampling()); } @Override public double getStdDeviationBound(Bounds bound) { return switch (bound) { case UPPER, UPPER_POPULATION -> getAvg() + (getStdDeviationPopulation() * sigma); case UPPER_SAMPLING -> getAvg() + (getStdDeviationSampling() * sigma); case LOWER, LOWER_POPULATION -> getAvg() - (getStdDeviationPopulation() * sigma); case LOWER_SAMPLING -> getAvg() - (getStdDeviationSampling() * sigma); }; } @Override public String getSumOfSquaresAsString() { return valueAsString(Metrics.sum_of_squares.name()); } @Override public String getVarianceAsString() { return valueAsString(Metrics.variance.name()); } @Override public String getVariancePopulationAsString() { return valueAsString(Metrics.variance_population.name()); } @Override public String getVarianceSamplingAsString() { return valueAsString(Metrics.variance_sampling.name()); } @Override public String getStdDeviationAsString() { return valueAsString(Metrics.std_deviation.name()); } @Override public String getStdDeviationPopulationAsString() { return valueAsString(Metrics.std_deviation_population.name()); } @Override public String getStdDeviationSamplingAsString() { return valueAsString(Metrics.std_deviation_sampling.name()); } private String getStdDeviationBoundAsString(Bounds bound) { return switch (bound) { case UPPER -> valueAsString(Metrics.std_upper.name()); case LOWER -> valueAsString(Metrics.std_lower.name()); case UPPER_POPULATION -> valueAsString(Metrics.std_upper_population.name()); case LOWER_POPULATION -> valueAsString(Metrics.std_lower_population.name()); case UPPER_SAMPLING -> valueAsString(Metrics.std_upper_sampling.name()); case LOWER_SAMPLING -> valueAsString(Metrics.std_lower_sampling.name()); }; } @Override protected AggregatorReducer getLeaderReducer(AggregationReduceContext reduceContext, int size) { final AggregatorReducer statsReducer = InternalStats.getReducer(name, format, getMetadata()); return new AggregatorReducer() { double sumOfSqrs = 0; double compensationOfSqrs = 0; @Override public void accept(InternalAggregation aggregation) { InternalExtendedStats stats = (InternalExtendedStats) aggregation; if (stats.sigma != sigma) { throw new IllegalStateException("Cannot reduce other stats aggregations that have a different sigma"); } double value = stats.getSumOfSquares(); if (Double.isFinite(value) == false) { sumOfSqrs += value; } else if (Double.isFinite(sumOfSqrs)) { double correctedOfSqrs = value - compensationOfSqrs; double newSumOfSqrs = sumOfSqrs + correctedOfSqrs; compensationOfSqrs = (newSumOfSqrs - sumOfSqrs) - correctedOfSqrs; sumOfSqrs = newSumOfSqrs; } statsReducer.accept(aggregation); } @Override public InternalAggregation get() { InternalStats stats = (InternalStats) statsReducer.get(); return new InternalExtendedStats( name, stats.getCount(), stats.getSum(), stats.getMin(), stats.getMax(), sumOfSqrs, sigma, format, getMetadata() ); } }; } @Override public InternalAggregation finalizeSampling(SamplingContext samplingContext) { return new InternalExtendedStats( name, samplingContext.scaleUp(count), samplingContext.scaleUp(sum), min, max, samplingContext.scaleUp(sumOfSqrs), sigma, format, getMetadata() ); } static
Metrics
java
assertj__assertj-core
assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/optional/OptionalAssert_containsInstanceOf_Test.java
{ "start": 1158, "end": 2728 }
class ____ { @Test void should_fail_when_optional_is_null() { // GIVEN @SuppressWarnings("OptionalAssignedToNull") Optional<Object> actual = null; // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).containsInstanceOf(Object.class)); // THEN then(assertionError).hasMessage(actualIsNull()); } @Test void should_fail_if_optional_is_empty() { // GIVEN Optional<Object> actual = Optional.empty(); // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).containsInstanceOf(Object.class)); // THEN then(assertionError).hasMessage(shouldBePresent(actual).create()); } @Test void should_pass_if_optional_contains_required_type() { // GIVEN Optional<String> optional = Optional.of("something"); // WHEN/THEN assertThat(optional).containsInstanceOf(String.class); } @Test void should_pass_if_optional_contains_required_type_subclass() { // GIVEN Optional<SubClass> optional = Optional.of(new SubClass()); // WHEN/THEN assertThat(optional).containsInstanceOf(ParentClass.class); } @Test void should_fail_if_optional_contains_other_type_than_required() { // GIVEN Optional<ParentClass> actual = Optional.of(new ParentClass()); // WHEN var assertionError = expectAssertionError(() -> assertThat(actual).containsInstanceOf(OtherClass.class)); // THEN then(assertionError).hasMessage(shouldContainInstanceOf(actual, OtherClass.class).create()); } private static
OptionalAssert_containsInstanceOf_Test
java
apache__camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/model/padding/Unity.java
{ "start": 1023, "end": 1603 }
class ____ { @DataField(pos = 1, pattern = "000") public float mandant; @DataField(pos = 2, pattern = "000") public float receiver; public float getMandant() { return mandant; } public void setMandant(float mandant) { this.mandant = mandant; } public float getReceiver() { return receiver; } public void setReceiver(float receiver) { this.receiver = receiver; } @Override public String toString() { return "Unity [mandant=" + mandant + ", receiver=" + receiver + "]"; } }
Unity
java
apache__rocketmq
proxy/src/main/java/org/apache/rocketmq/proxy/service/transaction/LocalTransactionService.java
{ "start": 1100, "end": 1929 }
class ____ extends AbstractTransactionService { protected final BrokerConfig brokerConfig; public LocalTransactionService(BrokerConfig brokerConfig) { this.brokerConfig = brokerConfig; } @Override public void addTransactionSubscription(ProxyContext ctx, String group, List<String> topicList) { } @Override public void addTransactionSubscription(ProxyContext ctx, String group, String topic) { } @Override public void replaceTransactionSubscription(ProxyContext ctx, String group, List<String> topicList) { } @Override public void unSubscribeAllTransactionTopic(ProxyContext ctx, String group) { } @Override protected String getBrokerNameByAddr(String brokerAddr) { return this.brokerConfig.getBrokerName(); } }
LocalTransactionService