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
mockito__mockito
mockito-integration-tests/junit-jupiter-parallel-tests/src/test/java/org/mockito/ParallelBugTest.java
{ "start": 341, "end": 1031 }
class ____ { @Mock private SomeService someService; @InjectMocks private AnotherService anotherService; @Test void test() { perform(); } private void perform() { // when anotherService.callSomeService(); // then Mockito.verify(someService).doSomething(); } @Test void test2() { perform(); } @Test void test3() { perform(); } @Test void test4() { perform(); } @Test void test5() { perform(); } @Test void test6() { perform(); } @Test void test7() { perform(); } public static
ParallelBugTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/cluster/coordination/CoordinationMetadata.java
{ "start": 1249, "end": 7370 }
class ____ implements Writeable, ToXContentFragment { public static final CoordinationMetadata EMPTY_METADATA = builder().build(); private final long term; private final VotingConfiguration lastCommittedConfiguration; private final VotingConfiguration lastAcceptedConfiguration; private final Set<VotingConfigExclusion> votingConfigExclusions; private static final ParseField TERM_PARSE_FIELD = new ParseField("term"); private static final ParseField LAST_COMMITTED_CONFIGURATION_FIELD = new ParseField("last_committed_config"); private static final ParseField LAST_ACCEPTED_CONFIGURATION_FIELD = new ParseField("last_accepted_config"); private static final ParseField VOTING_CONFIG_EXCLUSIONS_FIELD = new ParseField("voting_config_exclusions"); private static long term(Object[] termAndConfigs) { return (long) termAndConfigs[0]; } @SuppressWarnings("unchecked") private static VotingConfiguration lastCommittedConfig(Object[] fields) { List<String> nodeIds = (List<String>) fields[1]; return new VotingConfiguration(new HashSet<>(nodeIds)); } @SuppressWarnings("unchecked") private static VotingConfiguration lastAcceptedConfig(Object[] fields) { List<String> nodeIds = (List<String>) fields[2]; return new VotingConfiguration(new HashSet<>(nodeIds)); } @SuppressWarnings("unchecked") private static Set<VotingConfigExclusion> votingConfigExclusions(Object[] fields) { Set<VotingConfigExclusion> votingTombstones = new HashSet<>((List<VotingConfigExclusion>) fields[3]); return votingTombstones; } private static final ConstructingObjectParser<CoordinationMetadata, Void> PARSER = new ConstructingObjectParser<>( "coordination_metadata", fields -> new CoordinationMetadata( term(fields), lastCommittedConfig(fields), lastAcceptedConfig(fields), votingConfigExclusions(fields) ) ); static { PARSER.declareLong(ConstructingObjectParser.constructorArg(), TERM_PARSE_FIELD); PARSER.declareStringArray(ConstructingObjectParser.constructorArg(), LAST_COMMITTED_CONFIGURATION_FIELD); PARSER.declareStringArray(ConstructingObjectParser.constructorArg(), LAST_ACCEPTED_CONFIGURATION_FIELD); PARSER.declareObjectArray(ConstructingObjectParser.constructorArg(), VotingConfigExclusion.PARSER, VOTING_CONFIG_EXCLUSIONS_FIELD); } public CoordinationMetadata( long term, VotingConfiguration lastCommittedConfiguration, VotingConfiguration lastAcceptedConfiguration, Set<VotingConfigExclusion> votingConfigExclusions ) { this.term = term; this.lastCommittedConfiguration = lastCommittedConfiguration; this.lastAcceptedConfiguration = lastAcceptedConfiguration; this.votingConfigExclusions = Set.copyOf(votingConfigExclusions); } public CoordinationMetadata(StreamInput in) throws IOException { term = in.readLong(); lastCommittedConfiguration = new VotingConfiguration(in); lastAcceptedConfiguration = new VotingConfiguration(in); votingConfigExclusions = in.readCollectionAsImmutableSet(VotingConfigExclusion::new); } public static Builder builder() { return new Builder(); } public static Builder builder(CoordinationMetadata coordinationMetadata) { return new Builder(coordinationMetadata); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeLong(term); lastCommittedConfiguration.writeTo(out); lastAcceptedConfiguration.writeTo(out); out.writeCollection(votingConfigExclusions); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.field(TERM_PARSE_FIELD.getPreferredName(), term) .field(LAST_COMMITTED_CONFIGURATION_FIELD.getPreferredName(), lastCommittedConfiguration) .field(LAST_ACCEPTED_CONFIGURATION_FIELD.getPreferredName(), lastAcceptedConfiguration) .xContentList(VOTING_CONFIG_EXCLUSIONS_FIELD.getPreferredName(), votingConfigExclusions); } public static CoordinationMetadata fromXContent(XContentParser parser) throws IOException { return PARSER.parse(parser, null); } public long term() { return term; } public VotingConfiguration getLastAcceptedConfiguration() { return lastAcceptedConfiguration; } public VotingConfiguration getLastCommittedConfiguration() { return lastCommittedConfiguration; } public Set<VotingConfigExclusion> getVotingConfigExclusions() { return votingConfigExclusions; } @Override public boolean equals(Object o) { if (this == o) return true; if ((o instanceof CoordinationMetadata) == false) return false; CoordinationMetadata that = (CoordinationMetadata) o; if (term != that.term) return false; if (lastCommittedConfiguration.equals(that.lastCommittedConfiguration) == false) return false; if (lastAcceptedConfiguration.equals(that.lastAcceptedConfiguration) == false) return false; return votingConfigExclusions.equals(that.votingConfigExclusions); } @Override public int hashCode() { int result = (int) (term ^ (term >>> 32)); result = 31 * result + lastCommittedConfiguration.hashCode(); result = 31 * result + lastAcceptedConfiguration.hashCode(); result = 31 * result + votingConfigExclusions.hashCode(); return result; } @Override public String toString() { return "CoordinationMetadata{" + "term=" + term + ", lastCommittedConfiguration=" + lastCommittedConfiguration + ", lastAcceptedConfiguration=" + lastAcceptedConfiguration + ", votingConfigExclusions=" + votingConfigExclusions + '}'; } public static
CoordinationMetadata
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/telemetry/internals/MetricNamingStrategy.java
{ "start": 1715, "end": 1841 }
class ____ primarily used by the telemetry reporter, {@link MetricsCollector}, and * {@link MetricsEmitter} layers. */ public
is
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/proxy/BatchFetchProxyTest.java
{ "start": 2062, "end": 8136 }
class ____ { private static int NUMBER_OF_ENTITIES = 20; @Test @JiraKey("HHH-11147") public void testBatchAssociationFetch(SessionFactoryScope scope) { scope.inTransaction( session -> { final Statistics statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); List<Employee> employees = session.createQuery( "from Employee", Employee.class ).getResultList(); assertEquals( 1, statistics.getPrepareStatementCount() ); assertEquals( NUMBER_OF_ENTITIES, employees.size() ); for ( int i = 0; i < employees.size(); i++ ) { final Employer employer = employees.get( i ).employer; if ( i % 10 == 0 ) { assertFalse( Hibernate.isInitialized( employer ) ); Hibernate.initialize( employer ); } else { assertTrue( Hibernate.isInitialized( employer ) ); } assertEquals( "Employer #" + employer.id, employer.name ); } // assert that all 20 Employee and all 20 Employers have been loaded assertThat( statistics.getEntityLoadCount() ).isEqualTo( 40L ); // but assert that it only took 3 queries (the initial plus the 2 batch fetches) assertThat( statistics.getPrepareStatementCount() ).isEqualTo( 3L ); } ); } @Test @JiraKey("HHH-11147") public void testBatchAssociation(SessionFactoryScope scope) { scope.inTransaction( session -> { final Statistics statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); List<Employee> employees = session.createQuery( "from Employee", Employee.class ).getResultList(); assertEquals( 1, statistics.getPrepareStatementCount() ); assertEquals( NUMBER_OF_ENTITIES, employees.size() ); for ( int i = 0 ; i < employees.size() ; i++ ) { final Employer employer = employees.get( i ).employer; if ( i % 10 == 0 ) { assertFalse( Hibernate.isInitialized( employer ) ); Hibernate.initialize( employer ); } else { assertTrue( Hibernate.isInitialized( employer ) ); } assertEquals( "Employer #" + employer.id, employer.name ); } assertEquals( 3, statistics.getPrepareStatementCount() ); } ); } @Test @JiraKey("HHH-11147") public void testBatchEntityLoad(SessionFactoryScope scope) { scope.inTransaction( session -> { final Statistics statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); List<Employer> employers = new ArrayList<>(); for ( int i = 0 ; i < NUMBER_OF_ENTITIES ; i++ ) { employers.add( session.getReference( Employer.class, i + 1) ); } assertEquals( 0, statistics.getPrepareStatementCount() ); for ( int i = 0 ; i < NUMBER_OF_ENTITIES ; i++ ) { final Employer employer = employers.get( i ); if ( i % 10 == 0 ) { assertFalse( Hibernate.isInitialized( employer ) ); Hibernate.initialize( employer ); } else { assertTrue( Hibernate.isInitialized( employer ) ); } assertEquals( "Employer #" + employer.id, employer.name ); } assertEquals( 2, statistics.getPrepareStatementCount() ); } ); } @Test @JiraKey("HHH-11147") public void testBatchEntityLoadThenModify(SessionFactoryScope scope) { scope.inTransaction( session -> { final Statistics statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); List<Employer> employers = new ArrayList<>(); for ( int i = 0 ; i < NUMBER_OF_ENTITIES ; i++ ) { employers.add( session.getReference( Employer.class, i + 1) ); } assertEquals( 0, statistics.getPrepareStatementCount() ); for ( int i = 0 ; i < NUMBER_OF_ENTITIES ; i++ ) { final Employer employer = employers.get( i ); if ( i % 10 == 0 ) { assertFalse( Hibernate.isInitialized( employer ) ); Hibernate.initialize( employer ); } else { assertTrue( Hibernate.isInitialized( employer ) ); } assertEquals( "Employer #" + employer.id, employer.name ); employer.name = employer.name + " new"; } assertEquals( 2, statistics.getPrepareStatementCount() ); } ); scope.inTransaction( session -> { for ( int i = 0; i < NUMBER_OF_ENTITIES; i++ ) { final Employer employer = session.get( Employer.class, i + 1 ); assertEquals( "Employer #" + employer.id + " new", employer.name ); } } ); } @Test @JiraKey("HHH-11147") public void testBatchEntityRemoval(SessionFactoryScope scope) { scope.inTransaction( session -> { final Statistics statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); List<Employer> employers = new ArrayList<>(); for ( int i = 0 ; i < 5 ; i++ ) { employers.add( session.getReference( Employer.class, i + 1) ); } assertEquals( 0, statistics.getPrepareStatementCount() ); session.find( Employer.class, 0 ); session.find( Employer.class, 1 ); session.find( Employer.class, 2 ); session.find( Employer.class, 5 ); assertEquals( 1, statistics.getPrepareStatementCount() ); session.find( Employer.class, 6 ); session.find( Employer.class, 7 ); assertEquals( 3, statistics.getPrepareStatementCount() ); for ( Employer employer : employers ) { assertTrue( Hibernate.isInitialized( employer ) ); } } ); } @BeforeEach public void setUpData(SessionFactoryScope scope) { scope.inTransaction( session -> { for ( int i = 0 ; i < NUMBER_OF_ENTITIES ; i++ ) { final Employee employee = new Employee(); employee.id = i + 1; employee.name = "Employee #" + employee.id; final Employer employer = new Employer(); employer.id = i + 1; employer.name = "Employer #" + employer.id; employee.employer = employer; session.persist( employee ); } } ); } @AfterEach public void cleanupDate(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Entity(name = "Employee") public static
BatchFetchProxyTest
java
dropwizard__dropwizard
dropwizard-jackson/src/test/java/io/dropwizard/jackson/ExampleSPI.java
{ "start": 155, "end": 199 }
interface ____ extends ExampleTag { }
ExampleSPI
java
quarkusio__quarkus
extensions/hibernate-search-backend-elasticsearch-common/runtime/src/main/java/io/quarkus/hibernate/search/backend/elasticsearch/common/runtime/MapperContext.java
{ "start": 245, "end": 878 }
interface ____ { String toString(); Set<String> getBackendNamesForIndexedEntities(); Map<String, Set<String>> getBackendAndIndexNamesForSearchExtensions(); String backendPropertyKey(String backendName, String indexName, String propertyKeyRadical); <T> Optional<BeanReference<T>> singleExtensionBeanReferenceFor(Optional<String> override, Class<T> beanType, String backendName, String indexName); <T> Optional<List<BeanReference<T>>> multiExtensionBeanReferencesFor(Optional<List<String>> override, Class<T> beanType, String backendName, String indexName); }
MapperContext
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/LocalDateTimeAndEnumSchemaUpdateTest.java
{ "start": 4118, "end": 4154 }
enum ____ { Male, Female } }
Gender
java
alibaba__nacos
console/src/main/java/com/alibaba/nacos/console/handler/impl/remote/config/ConfigImportAndExportService.java
{ "start": 9218, "end": 10519 }
class ____ extends AbstractHttpClientResponseHandler<ResponseEntity<byte[]>> { private String contentDisposition; @Override public ResponseEntity<byte[]> handleResponse(ClassicHttpResponse response) throws IOException { try { contentDisposition = response.getHeader("Content-Disposition").getValue(); } catch (ProtocolException e) { throw new NacosRuntimeException(NacosException.SERVER_ERROR, "Export config from server, parse response file name failed; ", e); } return super.handleResponse(response); } @Override public ResponseEntity<byte[]> handleEntity(HttpEntity entity) throws IOException { InputStream inputStream = entity.getContent(); try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) { IoUtils.copy(inputStream, outputStream); byte[] responseBody = outputStream.toByteArray(); return ResponseEntity.ok().contentType(MediaType.APPLICATION_OCTET_STREAM) .header("Content-Disposition", contentDisposition).body(responseBody); } } } }
ExportHttpClientResponseHandler
java
elastic__elasticsearch
modules/lang-painless/src/test/java/org/elasticsearch/painless/MultiplicationTests.java
{ "start": 601, "end": 23016 }
class ____ extends ScriptTestCase { // TODO: short,byte,char public void testBasics() throws Exception { assertEquals(8, exec("int x = 4; char y = 2; return x*y;")); } public void testInt() throws Exception { assertEquals(1 * 1, exec("int x = 1; int y = 1; return x*y;")); assertEquals(2 * 3, exec("int x = 2; int y = 3; return x*y;")); assertEquals(5 * 10, exec("int x = 5; int y = 10; return x*y;")); assertEquals(1 * 1 * 2, exec("int x = 1; int y = 1; int z = 2; return x*y*z;")); assertEquals((1 * 1) * 2, exec("int x = 1; int y = 1; int z = 2; return (x*y)*z;")); assertEquals(1 * (1 * 2), exec("int x = 1; int y = 1; int z = 2; return x*(y*z);")); assertEquals(10 * 0, exec("int x = 10; int y = 0; return x*y;")); assertEquals(0 * 0, exec("int x = 0; int y = 0; return x*x;")); } public void testIntConst() throws Exception { assertEquals(1 * 1, exec("return 1*1;")); assertEquals(2 * 3, exec("return 2*3;")); assertEquals(5 * 10, exec("return 5*10;")); assertEquals(1 * 1 * 2, exec("return 1*1*2;")); assertEquals((1 * 1) * 2, exec("return (1*1)*2;")); assertEquals(1 * (1 * 2), exec("return 1*(1*2);")); assertEquals(10 * 0, exec("return 10*0;")); assertEquals(0 * 0, exec("return 0*0;")); } public void testByte() throws Exception { assertEquals((byte) 1 * (byte) 1, exec("byte x = 1; byte y = 1; return x*y;")); assertEquals((byte) 2 * (byte) 3, exec("byte x = 2; byte y = 3; return x*y;")); assertEquals((byte) 5 * (byte) 10, exec("byte x = 5; byte y = 10; return x*y;")); assertEquals((byte) 1 * (byte) 1 * (byte) 2, exec("byte x = 1; byte y = 1; byte z = 2; return x*y*z;")); assertEquals(((byte) 1 * (byte) 1) * (byte) 2, exec("byte x = 1; byte y = 1; byte z = 2; return (x*y)*z;")); assertEquals((byte) 1 * ((byte) 1 * (byte) 2), exec("byte x = 1; byte y = 1; byte z = 2; return x*(y*z);")); assertEquals((byte) 10 * (byte) 0, exec("byte x = 10; byte y = 0; return x*y;")); assertEquals((byte) 0 * (byte) 0, exec("byte x = 0; byte y = 0; return x*x;")); } public void testLong() throws Exception { assertEquals(1L * 1L, exec("long x = 1; long y = 1; return x*y;")); assertEquals(2L * 3L, exec("long x = 2; long y = 3; return x*y;")); assertEquals(5L * 10L, exec("long x = 5; long y = 10; return x*y;")); assertEquals(1L * 1L * 2L, exec("long x = 1; long y = 1; int z = 2; return x*y*z;")); assertEquals((1L * 1L) * 2L, exec("long x = 1; long y = 1; int z = 2; return (x*y)*z;")); assertEquals(1L * (1L * 2L), exec("long x = 1; long y = 1; int z = 2; return x*(y*z);")); assertEquals(10L * 0L, exec("long x = 10; long y = 0; return x*y;")); assertEquals(0L * 0L, exec("long x = 0; long y = 0; return x*x;")); } public void testLongConst() throws Exception { assertEquals(1L * 1L, exec("return 1L*1L;")); assertEquals(2L * 3L, exec("return 2L*3L;")); assertEquals(5L * 10L, exec("return 5L*10L;")); assertEquals(1L * 1L * 2L, exec("return 1L*1L*2L;")); assertEquals((1L * 1L) * 2L, exec("return (1L*1L)*2L;")); assertEquals(1L * (1L * 2L), exec("return 1L*(1L*2L);")); assertEquals(10L * 0L, exec("return 10L*0L;")); assertEquals(0L * 0L, exec("return 0L*0L;")); } public void testFloat() throws Exception { assertEquals(1F * 1F, exec("float x = 1; float y = 1; return x*y;")); assertEquals(2F * 3F, exec("float x = 2; float y = 3; return x*y;")); assertEquals(5F * 10F, exec("float x = 5; float y = 10; return x*y;")); assertEquals(1F * 1F * 2F, exec("float x = 1; float y = 1; float z = 2; return x*y*z;")); assertEquals((1F * 1F) * 2F, exec("float x = 1; float y = 1; float z = 2; return (x*y)*z;")); assertEquals(1F * (1F * 2F), exec("float x = 1; float y = 1; float z = 2; return x*(y*z);")); assertEquals(10F * 0F, exec("float x = 10; float y = 0; return x*y;")); assertEquals(0F * 0F, exec("float x = 0; float y = 0; return x*x;")); } public void testFloatConst() throws Exception { assertEquals(1F * 1F, exec("return 1F*1F;")); assertEquals(2F * 3F, exec("return 2F*3F;")); assertEquals(5F * 10F, exec("return 5F*10F;")); assertEquals(1F * 1F * 2F, exec("return 1F*1F*2F;")); assertEquals((1F * 1F) * 2F, exec("return (1F*1F)*2F;")); assertEquals(1F * (1F * 2F), exec("return 1F*(1F*2F);")); assertEquals(10F * 0F, exec("return 10F*0F;")); assertEquals(0F * 0F, exec("return 0F*0F;")); } public void testDouble() throws Exception { assertEquals(1D * 1D, exec("double x = 1; double y = 1; return x*y;")); assertEquals(2D * 3D, exec("double x = 2; double y = 3; return x*y;")); assertEquals(5D * 10D, exec("double x = 5; double y = 10; return x*y;")); assertEquals(1D * 1D * 2D, exec("double x = 1; double y = 1; double z = 2; return x*y*z;")); assertEquals((1D * 1D) * 2D, exec("double x = 1; double y = 1; double z = 2; return (x*y)*z;")); assertEquals(1D * (1D * 2D), exec("double x = 1; double y = 1; double z = 2; return x*(y*z);")); assertEquals(10D * 0D, exec("double x = 10; float y = 0; return x*y;")); assertEquals(0D * 0D, exec("double x = 0; float y = 0; return x*x;")); } public void testDoubleConst() throws Exception { assertEquals(1.0 * 1.0, exec("return 1.0*1.0;")); assertEquals(2.0 * 3.0, exec("return 2.0*3.0;")); assertEquals(5.0 * 10.0, exec("return 5.0*10.0;")); assertEquals(1.0 * 1.0 * 2.0, exec("return 1.0*1.0*2.0;")); assertEquals((1.0 * 1.0) * 2.0, exec("return (1.0*1.0)*2.0;")); assertEquals(1.0 * (1.0 * 2.0), exec("return 1.0*(1.0*2.0);")); assertEquals(10.0 * 0.0, exec("return 10.0*0.0;")); assertEquals(0.0 * 0.0, exec("return 0.0*0.0;")); } public void testDef() { assertEquals(4, exec("def x = (byte)2; def y = (byte)2; return x * y")); assertEquals(4, exec("def x = (short)2; def y = (byte)2; return x * y")); assertEquals(4, exec("def x = (char)2; def y = (byte)2; return x * y")); assertEquals(4, exec("def x = (int)2; def y = (byte)2; return x * y")); assertEquals(4L, exec("def x = (long)2; def y = (byte)2; return x * y")); assertEquals(4F, exec("def x = (float)2; def y = (byte)2; return x * y")); assertEquals(4D, exec("def x = (double)2; def y = (byte)2; return x * y")); assertEquals(4, exec("def x = (byte)2; def y = (short)2; return x * y")); assertEquals(4, exec("def x = (short)2; def y = (short)2; return x * y")); assertEquals(4, exec("def x = (char)2; def y = (short)2; return x * y")); assertEquals(4, exec("def x = (int)2; def y = (short)2; return x * y")); assertEquals(4L, exec("def x = (long)2; def y = (short)2; return x * y")); assertEquals(4F, exec("def x = (float)2; def y = (short)2; return x * y")); assertEquals(4D, exec("def x = (double)2; def y = (short)2; return x * y")); assertEquals(4, exec("def x = (byte)2; def y = (char)2; return x * y")); assertEquals(4, exec("def x = (short)2; def y = (char)2; return x * y")); assertEquals(4, exec("def x = (char)2; def y = (char)2; return x * y")); assertEquals(4, exec("def x = (int)2; def y = (char)2; return x * y")); assertEquals(4L, exec("def x = (long)2; def y = (char)2; return x * y")); assertEquals(4F, exec("def x = (float)2; def y = (char)2; return x * y")); assertEquals(4D, exec("def x = (double)2; def y = (char)2; return x * y")); assertEquals(4, exec("def x = (byte)2; def y = (int)2; return x * y")); assertEquals(4, exec("def x = (short)2; def y = (int)2; return x * y")); assertEquals(4, exec("def x = (char)2; def y = (int)2; return x * y")); assertEquals(4, exec("def x = (int)2; def y = (int)2; return x * y")); assertEquals(4L, exec("def x = (long)2; def y = (int)2; return x * y")); assertEquals(4F, exec("def x = (float)2; def y = (int)2; return x * y")); assertEquals(4D, exec("def x = (double)2; def y = (int)2; return x * y")); assertEquals(4L, exec("def x = (byte)2; def y = (long)2; return x * y")); assertEquals(4L, exec("def x = (short)2; def y = (long)2; return x * y")); assertEquals(4L, exec("def x = (char)2; def y = (long)2; return x * y")); assertEquals(4L, exec("def x = (int)2; def y = (long)2; return x * y")); assertEquals(4L, exec("def x = (long)2; def y = (long)2; return x * y")); assertEquals(4F, exec("def x = (float)2; def y = (long)2; return x * y")); assertEquals(4D, exec("def x = (double)2; def y = (long)2; return x * y")); assertEquals(4F, exec("def x = (byte)2; def y = (float)2; return x * y")); assertEquals(4F, exec("def x = (short)2; def y = (float)2; return x * y")); assertEquals(4F, exec("def x = (char)2; def y = (float)2; return x * y")); assertEquals(4F, exec("def x = (int)2; def y = (float)2; return x * y")); assertEquals(4F, exec("def x = (long)2; def y = (float)2; return x * y")); assertEquals(4F, exec("def x = (float)2; def y = (float)2; return x * y")); assertEquals(4D, exec("def x = (double)2; def y = (float)2; return x * y")); assertEquals(4D, exec("def x = (byte)2; def y = (double)2; return x * y")); assertEquals(4D, exec("def x = (short)2; def y = (double)2; return x * y")); assertEquals(4D, exec("def x = (char)2; def y = (double)2; return x * y")); assertEquals(4D, exec("def x = (int)2; def y = (double)2; return x * y")); assertEquals(4D, exec("def x = (long)2; def y = (double)2; return x * y")); assertEquals(4D, exec("def x = (float)2; def y = (double)2; return x * y")); assertEquals(4D, exec("def x = (double)2; def y = (double)2; return x * y")); assertEquals(4, exec("def x = (byte)2; def y = (byte)2; return x * y")); assertEquals(4, exec("def x = (short)2; def y = (short)2; return x * y")); assertEquals(4, exec("def x = (char)2; def y = (char)2; return x * y")); assertEquals(4, exec("def x = (int)2; def y = (int)2; return x * y")); assertEquals(4L, exec("def x = (long)2; def y = (long)2; return x * y")); assertEquals(4F, exec("def x = (float)2; def y = (float)2; return x * y")); assertEquals(4D, exec("def x = (double)2; def y = (double)2; return x * y")); } public void testDefTypedLHS() { assertEquals(4, exec("byte x = (byte)2; def y = (byte)2; return x * y")); assertEquals(4, exec("short x = (short)2; def y = (byte)2; return x * y")); assertEquals(4, exec("char x = (char)2; def y = (byte)2; return x * y")); assertEquals(4, exec("int x = (int)2; def y = (byte)2; return x * y")); assertEquals(4L, exec("long x = (long)2; def y = (byte)2; return x * y")); assertEquals(4F, exec("float x = (float)2; def y = (byte)2; return x * y")); assertEquals(4D, exec("double x = (double)2; def y = (byte)2; return x * y")); assertEquals(4, exec("byte x = (byte)2; def y = (short)2; return x * y")); assertEquals(4, exec("short x = (short)2; def y = (short)2; return x * y")); assertEquals(4, exec("char x = (char)2; def y = (short)2; return x * y")); assertEquals(4, exec("int x = (int)2; def y = (short)2; return x * y")); assertEquals(4L, exec("long x = (long)2; def y = (short)2; return x * y")); assertEquals(4F, exec("float x = (float)2; def y = (short)2; return x * y")); assertEquals(4D, exec("double x = (double)2; def y = (short)2; return x * y")); assertEquals(4, exec("byte x = (byte)2; def y = (char)2; return x * y")); assertEquals(4, exec("short x = (short)2; def y = (char)2; return x * y")); assertEquals(4, exec("char x = (char)2; def y = (char)2; return x * y")); assertEquals(4, exec("int x = (int)2; def y = (char)2; return x * y")); assertEquals(4L, exec("long x = (long)2; def y = (char)2; return x * y")); assertEquals(4F, exec("float x = (float)2; def y = (char)2; return x * y")); assertEquals(4D, exec("double x = (double)2; def y = (char)2; return x * y")); assertEquals(4, exec("byte x = (byte)2; def y = (int)2; return x * y")); assertEquals(4, exec("short x = (short)2; def y = (int)2; return x * y")); assertEquals(4, exec("char x = (char)2; def y = (int)2; return x * y")); assertEquals(4, exec("int x = (int)2; def y = (int)2; return x * y")); assertEquals(4L, exec("long x = (long)2; def y = (int)2; return x * y")); assertEquals(4F, exec("float x = (float)2; def y = (int)2; return x * y")); assertEquals(4D, exec("double x = (double)2; def y = (int)2; return x * y")); assertEquals(4L, exec("byte x = (byte)2; def y = (long)2; return x * y")); assertEquals(4L, exec("short x = (short)2; def y = (long)2; return x * y")); assertEquals(4L, exec("char x = (char)2; def y = (long)2; return x * y")); assertEquals(4L, exec("int x = (int)2; def y = (long)2; return x * y")); assertEquals(4L, exec("long x = (long)2; def y = (long)2; return x * y")); assertEquals(4F, exec("float x = (float)2; def y = (long)2; return x * y")); assertEquals(4D, exec("double x = (double)2; def y = (long)2; return x * y")); assertEquals(4F, exec("byte x = (byte)2; def y = (float)2; return x * y")); assertEquals(4F, exec("short x = (short)2; def y = (float)2; return x * y")); assertEquals(4F, exec("char x = (char)2; def y = (float)2; return x * y")); assertEquals(4F, exec("int x = (int)2; def y = (float)2; return x * y")); assertEquals(4F, exec("long x = (long)2; def y = (float)2; return x * y")); assertEquals(4F, exec("float x = (float)2; def y = (float)2; return x * y")); assertEquals(4D, exec("double x = (double)2; def y = (float)2; return x * y")); assertEquals(4D, exec("byte x = (byte)2; def y = (double)2; return x * y")); assertEquals(4D, exec("short x = (short)2; def y = (double)2; return x * y")); assertEquals(4D, exec("char x = (char)2; def y = (double)2; return x * y")); assertEquals(4D, exec("int x = (int)2; def y = (double)2; return x * y")); assertEquals(4D, exec("long x = (long)2; def y = (double)2; return x * y")); assertEquals(4D, exec("float x = (float)2; def y = (double)2; return x * y")); assertEquals(4D, exec("double x = (double)2; def y = (double)2; return x * y")); assertEquals(4, exec("byte x = (byte)2; def y = (byte)2; return x * y")); assertEquals(4, exec("short x = (short)2; def y = (short)2; return x * y")); assertEquals(4, exec("char x = (char)2; def y = (char)2; return x * y")); assertEquals(4, exec("int x = (int)2; def y = (int)2; return x * y")); assertEquals(4L, exec("long x = (long)2; def y = (long)2; return x * y")); assertEquals(4F, exec("float x = (float)2; def y = (float)2; return x * y")); assertEquals(4D, exec("double x = (double)2; def y = (double)2; return x * y")); } public void testDefTypedRHS() { assertEquals(4, exec("def x = (byte)2; byte y = (byte)2; return x * y")); assertEquals(4, exec("def x = (short)2; byte y = (byte)2; return x * y")); assertEquals(4, exec("def x = (char)2; byte y = (byte)2; return x * y")); assertEquals(4, exec("def x = (int)2; byte y = (byte)2; return x * y")); assertEquals(4L, exec("def x = (long)2; byte y = (byte)2; return x * y")); assertEquals(4F, exec("def x = (float)2; byte y = (byte)2; return x * y")); assertEquals(4D, exec("def x = (double)2; byte y = (byte)2; return x * y")); assertEquals(4, exec("def x = (byte)2; short y = (short)2; return x * y")); assertEquals(4, exec("def x = (short)2; short y = (short)2; return x * y")); assertEquals(4, exec("def x = (char)2; short y = (short)2; return x * y")); assertEquals(4, exec("def x = (int)2; short y = (short)2; return x * y")); assertEquals(4L, exec("def x = (long)2; short y = (short)2; return x * y")); assertEquals(4F, exec("def x = (float)2; short y = (short)2; return x * y")); assertEquals(4D, exec("def x = (double)2; short y = (short)2; return x * y")); assertEquals(4, exec("def x = (byte)2; char y = (char)2; return x * y")); assertEquals(4, exec("def x = (short)2; char y = (char)2; return x * y")); assertEquals(4, exec("def x = (char)2; char y = (char)2; return x * y")); assertEquals(4, exec("def x = (int)2; char y = (char)2; return x * y")); assertEquals(4L, exec("def x = (long)2; char y = (char)2; return x * y")); assertEquals(4F, exec("def x = (float)2; char y = (char)2; return x * y")); assertEquals(4D, exec("def x = (double)2; char y = (char)2; return x * y")); assertEquals(4, exec("def x = (byte)2; int y = (int)2; return x * y")); assertEquals(4, exec("def x = (short)2; int y = (int)2; return x * y")); assertEquals(4, exec("def x = (char)2; int y = (int)2; return x * y")); assertEquals(4, exec("def x = (int)2; int y = (int)2; return x * y")); assertEquals(4L, exec("def x = (long)2; int y = (int)2; return x * y")); assertEquals(4F, exec("def x = (float)2; int y = (int)2; return x * y")); assertEquals(4D, exec("def x = (double)2; int y = (int)2; return x * y")); assertEquals(4L, exec("def x = (byte)2; long y = (long)2; return x * y")); assertEquals(4L, exec("def x = (short)2; long y = (long)2; return x * y")); assertEquals(4L, exec("def x = (char)2; long y = (long)2; return x * y")); assertEquals(4L, exec("def x = (int)2; long y = (long)2; return x * y")); assertEquals(4L, exec("def x = (long)2; long y = (long)2; return x * y")); assertEquals(4F, exec("def x = (float)2; long y = (long)2; return x * y")); assertEquals(4D, exec("def x = (double)2; long y = (long)2; return x * y")); assertEquals(4F, exec("def x = (byte)2; float y = (float)2; return x * y")); assertEquals(4F, exec("def x = (short)2; float y = (float)2; return x * y")); assertEquals(4F, exec("def x = (char)2; float y = (float)2; return x * y")); assertEquals(4F, exec("def x = (int)2; float y = (float)2; return x * y")); assertEquals(4F, exec("def x = (long)2; float y = (float)2; return x * y")); assertEquals(4F, exec("def x = (float)2; float y = (float)2; return x * y")); assertEquals(4D, exec("def x = (double)2; float y = (float)2; return x * y")); assertEquals(4D, exec("def x = (byte)2; double y = (double)2; return x * y")); assertEquals(4D, exec("def x = (short)2; double y = (double)2; return x * y")); assertEquals(4D, exec("def x = (char)2; double y = (double)2; return x * y")); assertEquals(4D, exec("def x = (int)2; double y = (double)2; return x * y")); assertEquals(4D, exec("def x = (long)2; double y = (double)2; return x * y")); assertEquals(4D, exec("def x = (float)2; double y = (double)2; return x * y")); assertEquals(4D, exec("def x = (double)2; double y = (double)2; return x * y")); assertEquals(4, exec("def x = (byte)2; byte y = (byte)2; return x * y")); assertEquals(4, exec("def x = (short)2; short y = (short)2; return x * y")); assertEquals(4, exec("def x = (char)2; char y = (char)2; return x * y")); assertEquals(4, exec("def x = (int)2; int y = (int)2; return x * y")); assertEquals(4L, exec("def x = (long)2; long y = (long)2; return x * y")); assertEquals(4F, exec("def x = (float)2; float y = (float)2; return x * y")); assertEquals(4D, exec("def x = (double)2; double y = (double)2; return x * y")); } public void testCompoundAssignment() { // byte assertEquals((byte) 15, exec("byte x = 5; x *= 3; return x;")); assertEquals((byte) -5, exec("byte x = 5; x *= -1; return x;")); // short assertEquals((short) 15, exec("short x = 5; x *= 3; return x;")); assertEquals((short) -5, exec("short x = 5; x *= -1; return x;")); // char assertEquals((char) 15, exec("char x = 5; x *= 3; return x;")); // int assertEquals(15, exec("int x = 5; x *= 3; return x;")); assertEquals(-5, exec("int x = 5; x *= -1; return x;")); // long assertEquals(15L, exec("long x = 5; x *= 3; return x;")); assertEquals(-5L, exec("long x = 5; x *= -1; return x;")); // float assertEquals(15F, exec("float x = 5f; x *= 3; return x;")); assertEquals(-5F, exec("float x = 5f; x *= -1; return x;")); // double assertEquals(15D, exec("double x = 5.0; x *= 3; return x;")); assertEquals(-5D, exec("double x = 5.0; x *= -1; return x;")); } public void testDefCompoundAssignment() { // byte assertEquals((byte) 15, exec("def x = (byte)5; x *= 3; return x;")); assertEquals((byte) -5, exec("def x = (byte)5; x *= -1; return x;")); // short assertEquals((short) 15, exec("def x = (short)5; x *= 3; return x;")); assertEquals((short) -5, exec("def x = (short)5; x *= -1; return x;")); // char assertEquals((char) 15, exec("def x = (char)5; x *= 3; return x;")); // int assertEquals(15, exec("def x = 5; x *= 3; return x;")); assertEquals(-5, exec("def x = 5; x *= -1; return x;")); // long assertEquals(15L, exec("def x = 5L; x *= 3; return x;")); assertEquals(-5L, exec("def x = 5L; x *= -1; return x;")); // float assertEquals(15F, exec("def x = 5f; x *= 3; return x;")); assertEquals(-5F, exec("def x = 5f; x *= -1; return x;")); // double assertEquals(15D, exec("def x = 5.0; x *= 3; return x;")); assertEquals(-5D, exec("def x = 5.0; x *= -1; return x;")); } }
MultiplicationTests
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/http/HttpMethod.java
{ "start": 1036, "end": 6200 }
class ____ implements Comparable<HttpMethod> { private static final String GET_STRING = "GET"; private static final String POST_STRING = "POST"; /** * The OPTIONS method represents a request for information about the communication options * available on the request/response chain identified by the Request-URI. This method allows * the client to determine the options and/or requirements associated with a resource, or the * capabilities of a server, without implying a resource action or initiating a resource * retrieval. */ public static final HttpMethod OPTIONS = new HttpMethod("OPTIONS"); /** * The GET method means retrieve whatever information (in the form of an entity) is identified * by the Request-URI. If the Request-URI refers to a data-producing process, it is the * produced data which shall be returned as the entity in the response and not the source text * of the process, unless that text happens to be the output of the process. */ public static final HttpMethod GET = new HttpMethod(GET_STRING); /** * The HEAD method is identical to GET except that the server MUST NOT return a message-body * in the response. */ public static final HttpMethod HEAD = new HttpMethod("HEAD"); /** * The POST method is used to request that the origin server accept the entity enclosed in the * request as a new subordinate of the resource identified by the Request-URI in the * Request-Line. */ public static final HttpMethod POST = new HttpMethod(POST_STRING); /** * The PUT method requests that the enclosed entity be stored under the supplied Request-URI. */ public static final HttpMethod PUT = new HttpMethod("PUT"); /** * The PATCH method requests that a set of changes described in the * request entity be applied to the resource identified by the Request-URI. */ public static final HttpMethod PATCH = new HttpMethod("PATCH"); /** * The DELETE method requests that the origin server delete the resource identified by the * Request-URI. */ public static final HttpMethod DELETE = new HttpMethod("DELETE"); /** * The TRACE method is used to invoke a remote, application-layer loop- back of the request * message. */ public static final HttpMethod TRACE = new HttpMethod("TRACE"); /** * This specification reserves the method name CONNECT for use with a proxy that can dynamically * switch to being a tunnel */ public static final HttpMethod CONNECT = new HttpMethod("CONNECT"); /** * Returns the {@link HttpMethod} represented by the specified name. * If the specified name is a standard HTTP method name, a cached instance * will be returned. Otherwise, a new instance will be returned. */ public static HttpMethod valueOf(String name) { switch (name) { case "OPTIONS": return HttpMethod.OPTIONS; case "GET": return HttpMethod.GET; case "HEAD": return HttpMethod.HEAD; case "POST": return HttpMethod.POST; case "PUT": return HttpMethod.PUT; case "PATCH": return HttpMethod.PATCH; case "DELETE": return HttpMethod.DELETE; case "TRACE": return HttpMethod.TRACE; case "CONNECT": return HttpMethod.CONNECT; default: return new HttpMethod(name); } } private final AsciiString name; /** * Creates a new HTTP method with the specified name. You will not need to * create a new method unless you are implementing a protocol derived from * HTTP, such as * <a href="https://en.wikipedia.org/wiki/Real_Time_Streaming_Protocol">RTSP</a> and * <a href="https://en.wikipedia.org/wiki/Internet_Content_Adaptation_Protocol">ICAP</a> */ public HttpMethod(String name) { name = checkNonEmptyAfterTrim(name, "name"); int index = HttpUtil.validateToken(name); if (index != -1) { throw new IllegalArgumentException( "Illegal character in HTTP Method: 0x" + Integer.toHexString(name.charAt(index))); } this.name = AsciiString.cached(name); } /** * Returns the name of this method. */ public String name() { return name.toString(); } /** * Returns the name of this method. */ public AsciiString asciiName() { return name; } @Override public int hashCode() { return name().hashCode(); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof HttpMethod)) { return false; } HttpMethod that = (HttpMethod) o; return name().equals(that.name()); } @Override public String toString() { return name.toString(); } @Override public int compareTo(HttpMethod o) { if (o == this) { return 0; } return name().compareTo(o.name()); } }
HttpMethod
java
quarkusio__quarkus
extensions/elytron-security-common/runtime/src/main/java/io/quarkus/elytron/security/common/runtime/ElytronCommonRecorder.java
{ "start": 241, "end": 354 }
class ____ provides methods for creating RuntimeValues for the deployment security objects. */ @Recorder public
that
java
apache__spark
sql/api/src/main/scala/org/apache/spark/sql/internal/types/GeographicSpatialReferenceSystemMapper.java
{ "start": 997, "end": 1692 }
class ____ extends SpatialReferenceSystemMapper { // Returns the string ID corresponding to the input SRID. If not supported, returns `null`. public static String getStringId(int srid) { SpatialReferenceSystemInformation srsInfo = srsCache.getSrsInfo(srid); return srsInfo != null && srsInfo.isGeographic() ? srsInfo.stringId() : null; } // Returns the SRID corresponding to the input string ID. If not supported, returns `null`. public static Integer getSrid(String stringId) { SpatialReferenceSystemInformation srsInfo = srsCache.getSrsInfo(stringId); return srsInfo != null && srsInfo.isGeographic() ? srsInfo.srid() : null; } }
GeographicSpatialReferenceSystemMapper
java
google__error-prone
core/src/main/java/com/google/errorprone/refaster/Template.java
{ "start": 15905, "end": 21836 }
class ____ extends Exception { final Collection<JCDiagnostic> diagnostics; InferException(Collection<JCDiagnostic> diagnostics) { this.diagnostics = diagnostics; } @Override public String getMessage() { return "Inference failed with the following error(s): " + diagnostics; } } /** * Returns the inferred method type of the template based on the given actual argument types. * * @throws InferException if no instances of the specified type variables would allow the {@code * actualArgTypes} to match the {@code expectedArgTypes} */ private Type infer( Warner warner, Inliner inliner, List<Type> freeTypeVariables, List<Type> expectedArgTypes, Type returnType, List<Type> actualArgTypes) throws InferException { Symtab symtab = inliner.symtab(); Type methodType = new MethodType(expectedArgTypes, returnType, List.<Type>nil(), symtab.methodClass); if (!freeTypeVariables.isEmpty()) { methodType = new ForAll(freeTypeVariables, methodType); } Enter enter = inliner.enter(); MethodSymbol methodSymbol = new MethodSymbol(0, inliner.asName("__m__"), methodType, symtab.unknownSymbol); Type site = symtab.methodClass.type; Env<AttrContext> env = enter.getTopLevelEnv(TreeMaker.instance(inliner.getContext()).TopLevel(List.<JCTree>nil())); // Set up the resolution phase: try { Field field = AttrContext.class.getDeclaredField("pendingResolutionPhase"); field.setAccessible(true); field.set(env.info, newMethodResolutionPhase(autoboxing())); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } Object resultInfo; try { Class<?> resultInfoClass = Class.forName("com.sun.tools.javac.comp.Attr$ResultInfo"); Constructor<?> resultInfoCtor = resultInfoClass.getDeclaredConstructor(Attr.class, KindSelector.class, Type.class); resultInfoCtor.setAccessible(true); resultInfo = resultInfoCtor.newInstance( Attr.instance(inliner.getContext()), KindSelector.PCK, Type.noType); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } // Type inference sometimes produces diagnostics, so we need to catch them to avoid interfering // with the enclosing compilation. Log.DeferredDiagnosticHandler handler = deferredDiagnosticHandler(Log.instance(inliner.getContext())); try { MethodType result = callCheckMethod(warner, inliner, resultInfo, actualArgTypes, methodSymbol, site, env); Collection<JCDiagnostic> diagnostics = getDiagnostics(handler); if (!diagnostics.isEmpty()) { throw new InferException(diagnostics); } return result; } finally { Log.instance(inliner.getContext()).popDiagnosticHandler(handler); } } /** Reflectively instantiate the package-private {@code MethodResolutionPhase} enum. */ private static @Nullable Object newMethodResolutionPhase(boolean autoboxing) { for (Class<?> c : Resolve.class.getDeclaredClasses()) { if (!c.getName().equals("com.sun.tools.javac.comp.Resolve$MethodResolutionPhase")) { continue; } for (Object e : c.getEnumConstants()) { if (e.toString().equals(autoboxing ? "BOX" : "BASIC")) { return e; } } } return null; } /** * Reflectively invoke Resolve.checkMethod(), which despite being package-private is apparently * the only useful entry-point into javac8's type inference implementation. */ private MethodType callCheckMethod( Warner warner, Inliner inliner, Object resultInfo, List<Type> actualArgTypes, MethodSymbol methodSymbol, Type site, Env<AttrContext> env) throws InferException { try { Method checkMethod; checkMethod = Resolve.class.getDeclaredMethod( "checkMethod", Env.class, Type.class, Symbol.class, Class.forName( "com.sun.tools.javac.comp.Attr$ResultInfo"), // ResultInfo is package-private List.class, List.class, Warner.class); checkMethod.setAccessible(true); return (MethodType) checkMethod.invoke( Resolve.instance(inliner.getContext()), env, site, methodSymbol, resultInfo, actualArgTypes, /* freeTypeVariables */ List.<Type>nil(), warner); } catch (InvocationTargetException e) { if (e.getCause() instanceof Resolve.InapplicableMethodException) { throw new InferException( ImmutableList.of( ((Resolve.InapplicableMethodException) e.getTargetException()).getDiagnostic())); } throw new LinkageError(e.getMessage(), e.getCause()); } catch (ReflectiveOperationException e) { throw new LinkageError(e.getMessage(), e); } } /** * Returns a list of the elements of {@code typeVariables} that are <em>not</em> bound in the * specified {@link Unifier}. */ private ImmutableList<UTypeVar> freeTypeVars(Unifier unifier) { ImmutableList.Builder<UTypeVar> builder = ImmutableList.builder(); for (UTypeVar var : typeVariables(unifier.getContext())) { if (unifier.getBinding(var.key()) == null) { builder.add(var); } } return builder.build(); } protected static Fix addImports(Inliner inliner, SuggestedFix.Builder fix) { for (String importToAdd : inliner.getImportsToAdd()) { fix.addImport(importToAdd); } for (String staticImportToAdd : inliner.getStaticImportsToAdd()) { fix.addStaticImport(staticImportToAdd); } return fix.build(); } }
InferException
java
apache__hadoop
hadoop-tools/hadoop-gridmix/src/test/java/org/apache/hadoop/mapred/gridmix/TestCompressionEmulationUtils.java
{ "start": 2405, "end": 22781 }
class ____ extends GenerateData.GenDataFormat { @Override public List<InputSplit> getSplits(JobContext jobCtxt) throws IOException { // get the total data to be generated long toGen = jobCtxt.getConfiguration().getLong(GenerateData.GRIDMIX_GEN_BYTES, -1); if (toGen < 0) { throw new IOException("Invalid/missing generation bytes: " + toGen); } // get the total number of mappers configured int totalMappersConfigured = jobCtxt.getConfiguration().getInt(MRJobConfig.NUM_MAPS, -1); if (totalMappersConfigured < 0) { throw new IOException("Invalid/missing num mappers: " + totalMappersConfigured); } final long bytesPerTracker = toGen / totalMappersConfigured; final ArrayList<InputSplit> splits = new ArrayList<InputSplit>(totalMappersConfigured); for (int i = 0; i < totalMappersConfigured; ++i) { splits.add(new GenSplit(bytesPerTracker, new String[] { "tracker_local" })); } return splits; } } /** * Test {@link RandomTextDataMapper} via {@link CompressionEmulationUtil}. */ @Test public void testRandomCompressedTextDataGenerator() throws Exception { int wordSize = 10; int listSize = 20; long dataSize = 10*1024*1024; Configuration conf = new Configuration(); CompressionEmulationUtil.setCompressionEmulationEnabled(conf, true); CompressionEmulationUtil.setInputCompressionEmulationEnabled(conf, true); // configure the RandomTextDataGenerator to generate desired sized data conf.setInt(RandomTextDataGenerator.GRIDMIX_DATAGEN_RANDOMTEXT_LISTSIZE, listSize); conf.setInt(RandomTextDataGenerator.GRIDMIX_DATAGEN_RANDOMTEXT_WORDSIZE, wordSize); conf.setLong(GenerateData.GRIDMIX_GEN_BYTES, dataSize); conf.set("mapreduce.job.hdfs-servers", ""); FileSystem lfs = FileSystem.getLocal(conf); // define the test's root temp directory Path rootTempDir = new Path(System.getProperty("test.build.data", "/tmp")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); Path tempDir = new Path(rootTempDir, "TestRandomCompressedTextDataGenr"); lfs.delete(tempDir, true); runDataGenJob(conf, tempDir); // validate the output data FileStatus[] files = lfs.listStatus(tempDir, new Utils.OutputFileUtils.OutputFilesFilter()); long size = 0; long maxLineSize = 0; for (FileStatus status : files) { InputStream in = CompressionEmulationUtil .getPossiblyDecompressedInputStream(status.getPath(), conf, 0); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String line = reader.readLine(); if (line != null) { long lineSize = line.getBytes().length; if (lineSize > maxLineSize) { maxLineSize = lineSize; } while (line != null) { for (String word : line.split("\\s")) { size += word.getBytes().length; } line = reader.readLine(); } } reader.close(); } assertTrue(size >= dataSize); assertTrue(size <= dataSize + maxLineSize); } /** * Runs a GridMix data-generation job. */ private static void runDataGenJob(Configuration conf, Path tempDir) throws IOException, ClassNotFoundException, InterruptedException { JobClient client = new JobClient(conf); // get the local job runner conf.setInt(MRJobConfig.NUM_MAPS, 1); Job job = Job.getInstance(conf); CompressionEmulationUtil.configure(job); job.setInputFormatClass(CustomInputFormat.class); // set the output path FileOutputFormat.setOutputPath(job, tempDir); // submit and wait for completion job.submit(); int ret = job.waitForCompletion(true) ? 0 : 1; assertEquals(0, ret, "Job Failed"); } /** * Test if {@link RandomTextDataGenerator} can generate random text data * with the desired compression ratio. This involves * - using {@link CompressionEmulationUtil} to configure the MR job for * generating the random text data with the desired compression ratio * - running the MR job * - test {@link RandomTextDataGenerator}'s output and match the output size * (compressed) with the expected compression ratio. */ private void testCompressionRatioConfigure(float ratio) throws Exception { long dataSize = 10*1024*1024; Configuration conf = new Configuration(); CompressionEmulationUtil.setCompressionEmulationEnabled(conf, true); CompressionEmulationUtil.setInputCompressionEmulationEnabled(conf, true); conf.setLong(GenerateData.GRIDMIX_GEN_BYTES, dataSize); conf.set("mapreduce.job.hdfs-servers", ""); float expectedRatio = CompressionEmulationUtil.DEFAULT_COMPRESSION_RATIO; if (ratio > 0) { // set the compression ratio in the conf CompressionEmulationUtil.setMapInputCompressionEmulationRatio(conf, ratio); expectedRatio = CompressionEmulationUtil.standardizeCompressionRatio(ratio); } // invoke the utility to map from ratio to word-size CompressionEmulationUtil.setupDataGeneratorConfig(conf); FileSystem lfs = FileSystem.getLocal(conf); // define the test's root temp directory Path rootTempDir = new Path(System.getProperty("test.build.data", "/tmp")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); Path tempDir = new Path(rootTempDir, "TestCustomRandomCompressedTextDataGenr"); lfs.delete(tempDir, true); runDataGenJob(conf, tempDir); // validate the output data FileStatus[] files = lfs.listStatus(tempDir, new Utils.OutputFileUtils.OutputFilesFilter()); long size = 0; for (FileStatus status : files) { size += status.getLen(); } float compressionRatio = ((float)size)/dataSize; float stdRatio = CompressionEmulationUtil.standardizeCompressionRatio(compressionRatio); assertEquals(expectedRatio, stdRatio, 0.0D); } /** * Test compression ratio with multiple compression ratios. */ @Test public void testCompressionRatios() throws Exception { // test default compression ratio i.e 0.5 testCompressionRatioConfigure(0F); // test for a sample compression ratio of 0.2 testCompressionRatioConfigure(0.2F); // test for a sample compression ratio of 0.4 testCompressionRatioConfigure(0.4F); // test for a sample compression ratio of 0.65 testCompressionRatioConfigure(0.65F); // test for a compression ratio of 0.682 which should be standardized // to round(0.682) i.e 0.68 testCompressionRatioConfigure(0.682F); // test for a compression ratio of 0.567 which should be standardized // to round(0.567) i.e 0.57 testCompressionRatioConfigure(0.567F); // test with a compression ratio of 0.01 which less than the min supported // value of 0.07 boolean failed = false; try { testCompressionRatioConfigure(0.01F); } catch (RuntimeException re) { failed = true; } assertTrue(failed, "Compression ratio min value (0.07) check failed!"); // test with a compression ratio of 0.01 which less than the max supported // value of 0.68 failed = false; try { testCompressionRatioConfigure(0.7F); } catch (RuntimeException re) { failed = true; } assertTrue(failed, "Compression ratio max value (0.68) check failed!"); } /** * Test compression ratio standardization. */ @Test public void testCompressionRatioStandardization() throws Exception { assertEquals(0.55F, CompressionEmulationUtil.standardizeCompressionRatio(0.55F), 0.0D); assertEquals(0.65F, CompressionEmulationUtil.standardizeCompressionRatio(0.652F), 0.0D); assertEquals(0.78F, CompressionEmulationUtil.standardizeCompressionRatio(0.777F), 0.0D); assertEquals(0.86F, CompressionEmulationUtil.standardizeCompressionRatio(0.855F), 0.0D); } /** * Test map input compression ratio configuration utilities. */ @Test public void testInputCompressionRatioConfiguration() throws Exception { Configuration conf = new Configuration(); float ratio = 0.567F; CompressionEmulationUtil.setMapInputCompressionEmulationRatio(conf, ratio); assertEquals(ratio, CompressionEmulationUtil.getMapInputCompressionEmulationRatio(conf), 0.0D); } /** * Test map output compression ratio configuration utilities. */ @Test public void testIntermediateCompressionRatioConfiguration() throws Exception { Configuration conf = new Configuration(); float ratio = 0.567F; CompressionEmulationUtil.setMapOutputCompressionEmulationRatio(conf, ratio); assertEquals(ratio, CompressionEmulationUtil.getMapOutputCompressionEmulationRatio(conf), 0.0D); } /** * Test reduce output compression ratio configuration utilities. */ @Test public void testOutputCompressionRatioConfiguration() throws Exception { Configuration conf = new Configuration(); float ratio = 0.567F; CompressionEmulationUtil.setJobOutputCompressionEmulationRatio(conf, ratio); assertEquals(ratio, CompressionEmulationUtil.getJobOutputCompressionEmulationRatio(conf), 0.0D); } /** * Test compressible {@link GridmixRecord}. */ @Test public void testCompressibleGridmixRecord() throws IOException { JobConf conf = new JobConf(); CompressionEmulationUtil.setCompressionEmulationEnabled(conf, true); CompressionEmulationUtil.setInputCompressionEmulationEnabled(conf, true); FileSystem lfs = FileSystem.getLocal(conf); int dataSize = 1024 * 1024 * 10; // 10 MB float ratio = 0.357F; // define the test's root temp directory Path rootTempDir = new Path(System.getProperty("test.build.data", "/tmp")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); Path tempDir = new Path(rootTempDir, "TestPossiblyCompressibleGridmixRecord"); lfs.delete(tempDir, true); // define a compressible GridmixRecord GridmixRecord record = new GridmixRecord(dataSize, 0); record.setCompressibility(true, ratio); // enable compression conf.setClass(FileOutputFormat.COMPRESS_CODEC, GzipCodec.class, CompressionCodec.class); org.apache.hadoop.mapred.FileOutputFormat.setCompressOutput(conf, true); // write the record to a file Path recordFile = new Path(tempDir, "record"); OutputStream outStream = CompressionEmulationUtil .getPossiblyCompressedOutputStream(recordFile, conf); DataOutputStream out = new DataOutputStream(outStream); record.write(out); out.close(); outStream.close(); // open the compressed stream for reading Path actualRecordFile = recordFile.suffix(".gz"); InputStream in = CompressionEmulationUtil .getPossiblyDecompressedInputStream(actualRecordFile, conf, 0); // get the compressed file size long compressedFileSize = lfs.listStatus(actualRecordFile)[0].getLen(); GridmixRecord recordRead = new GridmixRecord(); recordRead.readFields(new DataInputStream(in)); assertEquals(dataSize, recordRead.getSize(), "Record size mismatch in a compressible GridmixRecord"); assertTrue(recordRead.getSize() > compressedFileSize, "Failed to generate a compressible GridmixRecord"); // check if the record can generate data with the desired compression ratio float seenRatio = ((float)compressedFileSize)/dataSize; assertEquals(CompressionEmulationUtil.standardizeCompressionRatio(ratio), CompressionEmulationUtil.standardizeCompressionRatio(seenRatio), 1.0D); } /** * Test * {@link CompressionEmulationUtil#isCompressionEmulationEnabled( * org.apache.hadoop.conf.Configuration)}. */ @Test public void testIsCompressionEmulationEnabled() { Configuration conf = new Configuration(); // Check default values assertTrue(CompressionEmulationUtil.isCompressionEmulationEnabled(conf)); // Check disabled CompressionEmulationUtil.setCompressionEmulationEnabled(conf, false); assertFalse(CompressionEmulationUtil.isCompressionEmulationEnabled(conf)); // Check enabled CompressionEmulationUtil.setCompressionEmulationEnabled(conf, true); assertTrue(CompressionEmulationUtil.isCompressionEmulationEnabled(conf)); } /** * Test * {@link CompressionEmulationUtil#getPossiblyDecompressedInputStream(Path, * Configuration, long)} * and * {@link CompressionEmulationUtil#getPossiblyCompressedOutputStream(Path, * Configuration)}. */ @Test public void testPossiblyCompressedDecompressedStreams() throws IOException { JobConf conf = new JobConf(); FileSystem lfs = FileSystem.getLocal(conf); String inputLine = "Hi Hello!"; CompressionEmulationUtil.setCompressionEmulationEnabled(conf, true); CompressionEmulationUtil.setInputCompressionEmulationEnabled(conf, true); conf.setBoolean(FileOutputFormat.COMPRESS, true); conf.setClass(FileOutputFormat.COMPRESS_CODEC, GzipCodec.class, CompressionCodec.class); // define the test's root temp directory Path rootTempDir = new Path(System.getProperty("test.build.data", "/tmp")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); Path tempDir = new Path(rootTempDir, "TestPossiblyCompressedDecompressedStreams"); lfs.delete(tempDir, true); // create a compressed file Path compressedFile = new Path(tempDir, "test"); OutputStream out = CompressionEmulationUtil.getPossiblyCompressedOutputStream(compressedFile, conf); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputLine); writer.close(); // now read back the data from the compressed stream compressedFile = compressedFile.suffix(".gz"); InputStream in = CompressionEmulationUtil .getPossiblyDecompressedInputStream(compressedFile, conf, 0); BufferedReader reader = new BufferedReader(new InputStreamReader(in)); String readLine = reader.readLine(); assertEquals(inputLine, readLine, "Compression/Decompression error"); reader.close(); } /** * Test if * {@link CompressionEmulationUtil#configureCompressionEmulation( * org.apache.hadoop.mapred.JobConf, org.apache.hadoop.mapred.JobConf)} * can extract compression related configuration parameters. */ @Test public void testExtractCompressionConfigs() { JobConf source = new JobConf(); JobConf target = new JobConf(); // set the default values source.setBoolean(FileOutputFormat.COMPRESS, false); source.set(FileOutputFormat.COMPRESS_CODEC, "MyDefaultCodec"); source.set(FileOutputFormat.COMPRESS_TYPE, "MyDefaultType"); source.setBoolean(MRJobConfig.MAP_OUTPUT_COMPRESS, false); source.set(MRJobConfig.MAP_OUTPUT_COMPRESS_CODEC, "MyDefaultCodec2"); CompressionEmulationUtil.configureCompressionEmulation(source, target); // check default values assertFalse(target.getBoolean(FileOutputFormat.COMPRESS, true)); assertEquals("MyDefaultCodec", target.get(FileOutputFormat.COMPRESS_CODEC)); assertEquals("MyDefaultType", target.get(FileOutputFormat.COMPRESS_TYPE)); assertFalse(target.getBoolean(MRJobConfig.MAP_OUTPUT_COMPRESS, true)); assertEquals("MyDefaultCodec2", target.get(MRJobConfig.MAP_OUTPUT_COMPRESS_CODEC)); assertFalse(CompressionEmulationUtil .isInputCompressionEmulationEnabled(target)); // set new values source.setBoolean(FileOutputFormat.COMPRESS, true); source.set(FileOutputFormat.COMPRESS_CODEC, "MyCodec"); source.set(FileOutputFormat.COMPRESS_TYPE, "MyType"); source.setBoolean(MRJobConfig.MAP_OUTPUT_COMPRESS, true); source.set(MRJobConfig.MAP_OUTPUT_COMPRESS_CODEC, "MyCodec2"); org.apache.hadoop.mapred.FileInputFormat.setInputPaths(source, "file.gz"); target = new JobConf(); // reset CompressionEmulationUtil.configureCompressionEmulation(source, target); // check new values assertTrue(target.getBoolean(FileOutputFormat.COMPRESS, false)); assertEquals("MyCodec", target.get(FileOutputFormat.COMPRESS_CODEC)); assertEquals("MyType", target.get(FileOutputFormat.COMPRESS_TYPE)); assertTrue(target.getBoolean(MRJobConfig.MAP_OUTPUT_COMPRESS, false)); assertEquals("MyCodec2", target.get(MRJobConfig.MAP_OUTPUT_COMPRESS_CODEC)); assertTrue(CompressionEmulationUtil .isInputCompressionEmulationEnabled(target)); } /** * Test of {@link FileQueue} can identify compressed file and provide * readers to extract uncompressed data only if input-compression is enabled. */ @Test public void testFileQueueDecompression() throws IOException { JobConf conf = new JobConf(); FileSystem lfs = FileSystem.getLocal(conf); String inputLine = "Hi Hello!"; CompressionEmulationUtil.setCompressionEmulationEnabled(conf, true); CompressionEmulationUtil.setInputCompressionEmulationEnabled(conf, true); org.apache.hadoop.mapred.FileOutputFormat.setCompressOutput(conf, true); org.apache.hadoop.mapred.FileOutputFormat.setOutputCompressorClass(conf, GzipCodec.class); // define the test's root temp directory Path rootTempDir = new Path(System.getProperty("test.build.data", "/tmp")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); Path tempDir = new Path(rootTempDir, "TestFileQueueDecompression"); lfs.delete(tempDir, true); // create a compressed file Path compressedFile = new Path(tempDir, "test"); OutputStream out = CompressionEmulationUtil.getPossiblyCompressedOutputStream(compressedFile, conf); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputLine); writer.close(); compressedFile = compressedFile.suffix(".gz"); // now read back the data from the compressed stream using FileQueue long fileSize = lfs.listStatus(compressedFile)[0].getLen(); CombineFileSplit split = new CombineFileSplit(new Path[] {compressedFile}, new long[] {fileSize}); FileQueue queue = new FileQueue(split, conf); byte[] bytes = new byte[inputLine.getBytes().length]; queue.read(bytes); queue.close(); String readLine = new String(bytes); assertEquals(inputLine, readLine, "Compression/Decompression error"); } /** * Tests the computation logic of uncompressed input bytes by * {@link LoadJob#getUncompressedInputBytes(long, Configuration)} */ @Test public void testComputeUncompressedInputBytes() { long possiblyCompressedInputBytes = 100000; float compressionRatio = 0.45F; Configuration conf = new Configuration(); CompressionEmulationUtil.setMapInputCompressionEmulationRatio(conf, compressionRatio); // By default, input compression emulation is diabled. Verify the // computation of uncompressed input bytes. long result = CompressionEmulationUtil.getUncompressedInputBytes( possiblyCompressedInputBytes, conf); assertEquals(possiblyCompressedInputBytes, result); // Enable input compression emulation and verify uncompressed // input bytes computation logic CompressionEmulationUtil.setInputCompressionEmulationEnabled(conf, true); result = CompressionEmulationUtil.getUncompressedInputBytes( possiblyCompressedInputBytes, conf); assertEquals((long)(possiblyCompressedInputBytes/compressionRatio), result); } }
CustomInputFormat
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/GetConsumerListByGroupRequestHeader.java
{ "start": 1464, "end": 2069 }
class ____ extends RpcRequestHeader { @CFNotNull @RocketMQResource(ResourceType.GROUP) private String consumerGroup; @Override public void checkFields() throws RemotingCommandException { } public String getConsumerGroup() { return consumerGroup; } public void setConsumerGroup(String consumerGroup) { this.consumerGroup = consumerGroup; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("consumerGroup", consumerGroup) .toString(); } }
GetConsumerListByGroupRequestHeader
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/internal/DelayedParameterizedTypeBean.java
{ "start": 442, "end": 1172 }
class ____<T> implements ManagedBean<T> { private final ManagedBean<T> underlyingBean; private final Properties properties; private T instance; public DelayedParameterizedTypeBean(ManagedBean<T> underlyingBean, Properties properties) { assert ParameterizedType.class.isAssignableFrom( underlyingBean.getBeanClass() ); this.underlyingBean = underlyingBean; this.properties = properties; } @Override public Class<T> getBeanClass() { return underlyingBean.getBeanClass(); } @Override public T getBeanInstance() { if ( instance == null ) { instance = underlyingBean.getBeanInstance(); ( (ParameterizedType) instance ).setParameterValues( properties ); } return instance; } }
DelayedParameterizedTypeBean
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/multipleinput/output/CopyingFirstInputOfTwoInputStreamOperatorOutput.java
{ "start": 1337, "end": 2477 }
class ____ extends FirstInputOfTwoInputStreamOperatorOutput { private final TwoInputStreamOperator<RowData, RowData, RowData> operator; private final TypeSerializer<RowData> serializer; public CopyingFirstInputOfTwoInputStreamOperatorOutput( TwoInputStreamOperator<RowData, RowData, RowData> operator, TypeSerializer<RowData> serializer) { super(operator); this.operator = operator; this.serializer = serializer; } protected <X> void pushToOperator(StreamRecord<X> record) { try { // we know that the given outputTag matches our OutputTag so the record // must be of the type that our operator expects. @SuppressWarnings("unchecked") StreamRecord<RowData> castRecord = (StreamRecord<RowData>) record; StreamRecord<RowData> copy = castRecord.copy(serializer.copy(castRecord.getValue())); operator.processElement1(copy); } catch (Exception e) { throw new ExceptionInMultipleInputOperatorException(e); } } }
CopyingFirstInputOfTwoInputStreamOperatorOutput
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/bean/override/mockito/MockitoBeanOverrideHandlerTests.java
{ "start": 8980, "end": 9064 }
class ____ { } @MockitoBean(types = String.class) static
ClassLevelStringMockByName3
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2356/Issue2356Mapper.java
{ "start": 497, "end": 669 }
class ____ { //CHECKSTYLE:OFF public String brand; public String model; public String modelInternational; //CHECKSTYLE:ON }
Car
java
apache__maven
compat/maven-resolver-provider/src/main/java/org/apache/maven/repository/internal/ArtifactDescriptorUtils.java
{ "start": 1436, "end": 4096 }
class ____ { public static Artifact toPomArtifact(Artifact artifact) { Artifact pomArtifact = artifact; if (!pomArtifact.getClassifier().isEmpty() || !"pom".equals(pomArtifact.getExtension())) { pomArtifact = new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), "pom", artifact.getVersion()); } return pomArtifact; } /** * Creates POM artifact out of passed in artifact by dropping classifier (if exists) and rewriting extension to * "pom". Unconditionally, unlike {@link #toPomArtifact(Artifact)} that does this only for artifacts without * classifiers. * * @since 4.0.0 */ public static Artifact toPomArtifactUnconditionally(Artifact artifact) { return new DefaultArtifact(artifact.getGroupId(), artifact.getArtifactId(), "pom", artifact.getVersion()); } public static RemoteRepository toRemoteRepository(Repository repository) { RemoteRepository.Builder builder = new RemoteRepository.Builder(repository.getId(), repository.getLayout(), repository.getUrl()); builder.setSnapshotPolicy(toRepositoryPolicy(repository.getSnapshots())); builder.setReleasePolicy(toRepositoryPolicy(repository.getReleases())); return builder.build(); } public static RepositoryPolicy toRepositoryPolicy(org.apache.maven.model.RepositoryPolicy policy) { boolean enabled = true; String checksums = toRepositoryChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_WARN); // the default String updates = RepositoryPolicy.UPDATE_POLICY_DAILY; if (policy != null) { enabled = policy.isEnabled(); if (policy.getUpdatePolicy() != null) { updates = policy.getUpdatePolicy(); } if (policy.getChecksumPolicy() != null) { checksums = policy.getChecksumPolicy(); } } return new RepositoryPolicy(enabled, updates, checksums); } public static String toRepositoryChecksumPolicy(final String artifactRepositoryPolicy) { return switch (artifactRepositoryPolicy) { case RepositoryPolicy.CHECKSUM_POLICY_FAIL -> RepositoryPolicy.CHECKSUM_POLICY_FAIL; case RepositoryPolicy.CHECKSUM_POLICY_IGNORE -> RepositoryPolicy.CHECKSUM_POLICY_IGNORE; case RepositoryPolicy.CHECKSUM_POLICY_WARN -> RepositoryPolicy.CHECKSUM_POLICY_WARN; default -> throw new IllegalArgumentException("unknown repository checksum policy: " + artifactRepositoryPolicy); }; } }
ArtifactDescriptorUtils
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/StreamOperatorStateHandlerTest.java
{ "start": 2986, "end": 8932 }
class ____ { /** * Tests that a failing snapshot method call to the keyed state backend will trigger the closing * of the StateSnapshotContextSynchronousImpl and the cancellation of the * OperatorSnapshotResult. The latter is supposed to also cancel all assigned futures. */ @Test void testFailingBackendSnapshotMethod() throws Exception { final long checkpointId = 42L; final long timestamp = 1L; try (CloseableRegistry closeableRegistry = new CloseableRegistry()) { RunnableFuture<SnapshotResult<KeyedStateHandle>> keyedStateManagedFuture = new CancelableFuture<>(); RunnableFuture<SnapshotResult<KeyedStateHandle>> keyedStateRawFuture = new CancelableFuture<>(); RunnableFuture<SnapshotResult<OperatorStateHandle>> operatorStateManagedFuture = new CancelableFuture<>(); RunnableFuture<SnapshotResult<OperatorStateHandle>> operatorStateRawFuture = new CancelableFuture<>(); RunnableFuture<SnapshotResult<StateObjectCollection<InputStateHandle>>> inputChannelStateFuture = new CancelableFuture<>(); RunnableFuture<SnapshotResult<StateObjectCollection<OutputStateHandle>>> resultSubpartitionStateFuture = new CancelableFuture<>(); OperatorSnapshotFutures operatorSnapshotResult = new OperatorSnapshotFutures( keyedStateManagedFuture, keyedStateRawFuture, operatorStateManagedFuture, operatorStateRawFuture, inputChannelStateFuture, resultSubpartitionStateFuture); StateSnapshotContextSynchronousImpl context = new TestStateSnapshotContextSynchronousImpl( checkpointId, timestamp, closeableRegistry); context.getRawKeyedOperatorStateOutput(); context.getRawOperatorStateOutput(); StreamTaskStateInitializerImpl stateInitializer = new StreamTaskStateInitializerImpl( new MockEnvironmentBuilder().build(), new HashMapStateBackend()); StreamOperatorStateContext stateContext = stateInitializer.streamOperatorStateContext( new OperatorID(), "whatever", new TestProcessingTimeService(), new UnUsedKeyContext(), IntSerializer.INSTANCE, closeableRegistry, new InterceptingOperatorMetricGroup(), 1.0, false, false); StreamOperatorStateHandler stateHandler = new StreamOperatorStateHandler( stateContext, new ExecutionConfig(), closeableRegistry); final String keyedStateField = "keyedStateField"; final String operatorStateField = "operatorStateField"; CheckpointedStreamOperator checkpointedStreamOperator = new CheckpointedStreamOperator() { @Override public void initializeState(StateInitializationContext context) throws Exception { context.getKeyedStateStore() .getState( new ValueStateDescriptor<>( keyedStateField, LongSerializer.INSTANCE)) .update(42L); context.getOperatorStateStore() .getListState( new ListStateDescriptor<>( operatorStateField, LongSerializer.INSTANCE)) .add(42L); } @Override public void snapshotState(StateSnapshotContext context) throws Exception { throw new ExpectedTestException(); } }; stateHandler.setCurrentKey("44"); stateHandler.initializeOperatorState(checkpointedStreamOperator); assertThat(stateContext.operatorStateBackend().getRegisteredStateNames()).isNotEmpty(); assertThat( ((AbstractKeyedStateBackend<?>) stateContext.keyedStateBackend()) .numKeyValueStatesByName()) .isOne(); assertThatThrownBy( () -> stateHandler.snapshotState( checkpointedStreamOperator, Optional.of(stateContext.internalTimerServiceManager()), "42", 42, 42, CheckpointOptions.forCheckpointWithDefaultLocation(), new MemCheckpointStreamFactory(1024), operatorSnapshotResult, context, false, false)) .isInstanceOfSatisfying( CheckpointException.class, // We can not check for ExpectedTestException
StreamOperatorStateHandlerTest
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/action/TransportDeleteInferenceEndpointActionTests.java
{ "start": 2095, "end": 17367 }
class ____ extends ESTestCase { private static final TimeValue TIMEOUT = TimeValue.timeValueSeconds(30); private TransportDeleteInferenceEndpointAction action; private ThreadPool threadPool; private ModelRegistry mockModelRegistry; private InferenceServiceRegistry mockInferenceServiceRegistry; @Before public void setUp() throws Exception { super.setUp(); threadPool = createThreadPool(inferenceUtilityExecutors()); mockModelRegistry = mock(ModelRegistry.class); mockInferenceServiceRegistry = mock(InferenceServiceRegistry.class); action = new TransportDeleteInferenceEndpointAction( mock(TransportService.class), mock(ClusterService.class), threadPool, mock(ActionFilters.class), mockModelRegistry, mockInferenceServiceRegistry, TestProjectResolvers.DEFAULT_PROJECT_ONLY ); } @After public void tearDown() throws Exception { super.tearDown(); terminate(threadPool); } public void testFailsToDelete_ADefaultEndpoint_WithoutPassingForceQueryParameter() { doAnswer(invocationOnMock -> { ActionListener<UnparsedModel> listener = invocationOnMock.getArgument(1); listener.onResponse(new UnparsedModel("model_id", TaskType.COMPLETION, "service", Map.of(), Map.of())); return Void.TYPE; }).when(mockModelRegistry).getModel(anyString(), any()); when(mockModelRegistry.containsPreconfiguredInferenceEndpointId(anyString())).thenReturn(true); var listener = new PlainActionFuture<DeleteInferenceEndpointAction.Response>(); action.masterOperation( mock(Task.class), new DeleteInferenceEndpointAction.Request("model-id", TaskType.COMPLETION, false, false), ClusterState.EMPTY_STATE, listener ); var exception = expectThrows(ElasticsearchStatusException.class, () -> listener.actionGet(TIMEOUT)); assertThat( exception.getMessage(), is("[model-id] is a reserved inference endpoint. Use the force=true query parameter to delete the inference endpoint.") ); } public void testDeletesDefaultEndpoint_WhenForceIsTrue() { doAnswer(invocationOnMock -> { ActionListener<UnparsedModel> listener = invocationOnMock.getArgument(1); listener.onResponse(new UnparsedModel("model_id", TaskType.COMPLETION, "service", Map.of(), Map.of())); return Void.TYPE; }).when(mockModelRegistry).getModel(anyString(), any()); when(mockModelRegistry.containsPreconfiguredInferenceEndpointId(anyString())).thenReturn(true); doAnswer(invocationOnMock -> { ActionListener<Boolean> listener = invocationOnMock.getArgument(1); listener.onResponse(true); return Void.TYPE; }).when(mockModelRegistry).deleteModel(anyString(), any()); var mockService = mock(InferenceService.class); doAnswer(invocationOnMock -> { ActionListener<Boolean> listener = invocationOnMock.getArgument(1); listener.onResponse(true); return Void.TYPE; }).when(mockService).stop(any(), any()); when(mockInferenceServiceRegistry.getService(anyString())).thenReturn(Optional.of(mockService)); var listener = new PlainActionFuture<DeleteInferenceEndpointAction.Response>(); action.masterOperation( mock(Task.class), new DeleteInferenceEndpointAction.Request("model-id", TaskType.COMPLETION, true, false), ClusterState.EMPTY_STATE, listener ); var response = listener.actionGet(TIMEOUT); assertTrue(response.isAcknowledged()); } public void testFailsToDeleteUnparsableEndpoint_WhenForceIsFalse() { var inferenceEndpointId = randomAlphaOfLengthBetween(5, 10); var serviceName = randomAlphanumericOfLength(10); var taskType = randomFrom(TaskType.values()); var mockService = mock(InferenceService.class); mockUnparsableModel(inferenceEndpointId, serviceName, taskType, mockService); when(mockModelRegistry.containsPreconfiguredInferenceEndpointId(inferenceEndpointId)).thenReturn(false); var listener = new PlainActionFuture<DeleteInferenceEndpointAction.Response>(); action.masterOperation( mock(Task.class), new DeleteInferenceEndpointAction.Request(inferenceEndpointId, taskType, false, false), ClusterState.EMPTY_STATE, listener ); var exception = expectThrows(ElasticsearchStatusException.class, () -> listener.actionGet(TIMEOUT)); assertThat(exception.getMessage(), containsString("Failed to parse model configuration for inference endpoint")); verify(mockModelRegistry).getModel(eq(inferenceEndpointId), any()); verify(mockInferenceServiceRegistry).getService(eq(serviceName)); verify(mockModelRegistry).containsPreconfiguredInferenceEndpointId(eq(inferenceEndpointId)); verify(mockService).parsePersistedConfig(eq(inferenceEndpointId), eq(taskType), any()); verifyNoMoreInteractions(mockModelRegistry, mockInferenceServiceRegistry, mockService); } public void testDeletesUnparsableEndpoint_WhenForceIsTrue() { var inferenceEndpointId = randomAlphaOfLengthBetween(5, 10); var serviceName = randomAlphanumericOfLength(10); var taskType = randomFrom(TaskType.values()); var mockService = mock(InferenceService.class); mockUnparsableModel(inferenceEndpointId, serviceName, taskType, mockService); doAnswer(invocationOnMock -> { ActionListener<Boolean> listener = invocationOnMock.getArgument(1); listener.onResponse(true); return Void.TYPE; }).when(mockModelRegistry).deleteModel(eq(inferenceEndpointId), any()); var listener = new PlainActionFuture<DeleteInferenceEndpointAction.Response>(); action.masterOperation( mock(Task.class), new DeleteInferenceEndpointAction.Request(inferenceEndpointId, taskType, true, false), ClusterState.EMPTY_STATE, listener ); var response = listener.actionGet(TIMEOUT); assertTrue(response.isAcknowledged()); verify(mockModelRegistry).getModel(eq(inferenceEndpointId), any()); verify(mockInferenceServiceRegistry).getService(eq(serviceName)); verify(mockService).parsePersistedConfig(eq(inferenceEndpointId), eq(taskType), any()); verify(mockModelRegistry).deleteModel(eq(inferenceEndpointId), any()); verifyNoMoreInteractions(mockModelRegistry, mockInferenceServiceRegistry, mockService); } private void mockUnparsableModel(String inferenceEndpointId, String serviceName, TaskType taskType, InferenceService mockService) { doAnswer(invocationOnMock -> { ActionListener<UnparsedModel> listener = invocationOnMock.getArgument(1); listener.onResponse(new UnparsedModel(inferenceEndpointId, taskType, serviceName, Map.of(), Map.of())); return Void.TYPE; }).when(mockModelRegistry).getModel(eq(inferenceEndpointId), any()); doThrow(new ElasticsearchStatusException(randomAlphanumericOfLength(10), RestStatus.INTERNAL_SERVER_ERROR)).when(mockService) .parsePersistedConfig(eq(inferenceEndpointId), eq(taskType), any()); when(mockInferenceServiceRegistry.getService(serviceName)).thenReturn(Optional.of(mockService)); } public void testDeletesEndpointWithNoService_WhenForceIsTrue() { var inferenceEndpointId = randomAlphaOfLengthBetween(5, 10); var serviceName = randomAlphanumericOfLength(10); var taskType = randomFrom(TaskType.values()); mockNoService(inferenceEndpointId, serviceName, taskType); doAnswer(invocationOnMock -> { ActionListener<Boolean> listener = invocationOnMock.getArgument(1); listener.onResponse(true); return Void.TYPE; }).when(mockModelRegistry).deleteModel(anyString(), any()); var listener = new PlainActionFuture<DeleteInferenceEndpointAction.Response>(); action.masterOperation( mock(Task.class), new DeleteInferenceEndpointAction.Request(inferenceEndpointId, taskType, true, false), ClusterState.EMPTY_STATE, listener ); var response = listener.actionGet(TIMEOUT); assertTrue(response.isAcknowledged()); verify(mockModelRegistry).getModel(eq(inferenceEndpointId), any()); verify(mockInferenceServiceRegistry).getService(eq(serviceName)); verify(mockModelRegistry).deleteModel(eq(inferenceEndpointId), any()); verifyNoMoreInteractions(mockModelRegistry, mockInferenceServiceRegistry); } public void testFailsToDeleteEndpointWithNoService_WhenForceIsFalse() { var inferenceEndpointId = randomAlphaOfLengthBetween(5, 10); var serviceName = randomAlphanumericOfLength(10); var taskType = randomFrom(TaskType.values()); mockNoService(inferenceEndpointId, serviceName, taskType); when(mockModelRegistry.containsPreconfiguredInferenceEndpointId(inferenceEndpointId)).thenReturn(false); var listener = new PlainActionFuture<DeleteInferenceEndpointAction.Response>(); action.masterOperation( mock(Task.class), new DeleteInferenceEndpointAction.Request(inferenceEndpointId, taskType, false, false), ClusterState.EMPTY_STATE, listener ); var exception = expectThrows(ElasticsearchStatusException.class, () -> listener.actionGet(TIMEOUT)); assertThat(exception.getMessage(), containsString("No service found for this inference endpoint")); verify(mockModelRegistry).getModel(eq(inferenceEndpointId), any()); verify(mockInferenceServiceRegistry).getService(eq(serviceName)); verify(mockModelRegistry).containsPreconfiguredInferenceEndpointId(eq(inferenceEndpointId)); verifyNoMoreInteractions(mockModelRegistry, mockInferenceServiceRegistry); } private void mockNoService(String inferenceEndpointId, String serviceName, TaskType taskType) { doAnswer(invocationOnMock -> { ActionListener<UnparsedModel> listener = invocationOnMock.getArgument(1); listener.onResponse(new UnparsedModel(inferenceEndpointId, taskType, serviceName, Map.of(), Map.of())); return Void.TYPE; }).when(mockModelRegistry).getModel(eq(inferenceEndpointId), any()); when(mockInferenceServiceRegistry.getService(serviceName)).thenReturn(Optional.empty()); } public void testFailsToDeleteEndpointIfModelDeploymentStopFails_WhenForceIsFalse() { var inferenceEndpointId = randomAlphaOfLengthBetween(5, 10); var serviceName = randomAlphanumericOfLength(10); var taskType = randomFrom(TaskType.values()); var mockService = mock(InferenceService.class); var mockModel = mock(Model.class); mockStopDeploymentFails(inferenceEndpointId, serviceName, taskType, mockService, mockModel); when(mockModelRegistry.containsPreconfiguredInferenceEndpointId(inferenceEndpointId)).thenReturn(false); var listener = new PlainActionFuture<DeleteInferenceEndpointAction.Response>(); action.masterOperation( mock(Task.class), new DeleteInferenceEndpointAction.Request(inferenceEndpointId, taskType, false, false), ClusterState.EMPTY_STATE, listener ); var exception = expectThrows(ElasticsearchStatusException.class, () -> listener.actionGet(TIMEOUT)); assertThat(exception.getMessage(), containsString("Failed to stop model deployment")); verify(mockModelRegistry).getModel(eq(inferenceEndpointId), any()); verify(mockInferenceServiceRegistry).getService(eq(serviceName)); verify(mockModelRegistry).containsPreconfiguredInferenceEndpointId(eq(inferenceEndpointId)); verify(mockService).parsePersistedConfig(eq(inferenceEndpointId), eq(taskType), any()); verify(mockService).stop(eq(mockModel), any()); verifyNoMoreInteractions(mockModelRegistry, mockInferenceServiceRegistry, mockService, mockModel); } public void testDeletesEndpointIfModelDeploymentStopFails_WhenForceIsTrue() { var inferenceEndpointId = randomAlphaOfLengthBetween(5, 10); var serviceName = randomAlphanumericOfLength(10); var taskType = randomFrom(TaskType.values()); var mockService = mock(InferenceService.class); var mockModel = mock(Model.class); mockStopDeploymentFails(inferenceEndpointId, serviceName, taskType, mockService, mockModel); doAnswer(invocationOnMock -> { ActionListener<Boolean> listener = invocationOnMock.getArgument(1); listener.onResponse(true); return Void.TYPE; }).when(mockModelRegistry).deleteModel(eq(inferenceEndpointId), any()); var listener = new PlainActionFuture<DeleteInferenceEndpointAction.Response>(); action.masterOperation( mock(Task.class), new DeleteInferenceEndpointAction.Request(inferenceEndpointId, taskType, true, false), ClusterState.EMPTY_STATE, listener ); var response = listener.actionGet(TIMEOUT); assertTrue(response.isAcknowledged()); verify(mockModelRegistry).getModel(eq(inferenceEndpointId), any()); verify(mockInferenceServiceRegistry).getService(eq(serviceName)); verify(mockService).parsePersistedConfig(eq(inferenceEndpointId), eq(taskType), any()); verify(mockService).stop(eq(mockModel), any()); verify(mockModelRegistry).deleteModel(eq(inferenceEndpointId), any()); verifyNoMoreInteractions(mockModelRegistry, mockInferenceServiceRegistry, mockService, mockModel); } private void mockStopDeploymentFails( String inferenceEndpointId, String serviceName, TaskType taskType, InferenceService mockService, Model mockModel ) { doAnswer(invocationOnMock -> { ActionListener<UnparsedModel> listener = invocationOnMock.getArgument(1); listener.onResponse(new UnparsedModel(inferenceEndpointId, taskType, serviceName, Map.of(), Map.of())); return Void.TYPE; }).when(mockModelRegistry).getModel(eq(inferenceEndpointId), any()); when(mockInferenceServiceRegistry.getService(serviceName)).thenReturn(Optional.of(mockService)); doReturn(mockModel).when(mockService).parsePersistedConfig(eq(inferenceEndpointId), eq(taskType), any()); doAnswer(invocationOnMock -> { ActionListener<Boolean> listener = invocationOnMock.getArgument(1); listener.onFailure(new ElasticsearchStatusException("Failed to stop model deployment", RestStatus.INTERNAL_SERVER_ERROR)); return Void.TYPE; }).when(mockService).stop(eq(mockModel), any()); } }
TransportDeleteInferenceEndpointActionTests
java
apache__avro
lang/java/ipc/src/test/java/org/apache/avro/TestCompare.java
{ "start": 1411, "end": 4334 }
class ____ { @Test void specificRecord() throws Exception { TestRecord s1 = new TestRecord(); TestRecord s2 = new TestRecord(); s1.setName("foo"); s1.setKind(Kind.BAZ); s1.setHash(new MD5(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 })); s2.setName("bar"); s2.setKind(Kind.BAR); s2.setHash(new MD5(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 6 })); Schema schema = SpecificData.get().getSchema(TestRecord.class); check(schema, s1, s2, true, new SpecificDatumWriter<>(schema), SpecificData.get()); s2.setKind(Kind.BAZ); check(schema, s1, s2, true, new SpecificDatumWriter<>(schema), SpecificData.get()); } private static <T> void check(Schema schema, T o1, T o2, boolean comparable, DatumWriter<T> writer, GenericData comparator) throws Exception { byte[] b1 = render(o1, schema, writer); byte[] b2 = render(o2, schema, writer); assertEquals(-1, BinaryData.compare(b1, 0, b2, 0, schema)); assertEquals(1, BinaryData.compare(b2, 0, b1, 0, schema)); assertEquals(0, BinaryData.compare(b1, 0, b1, 0, schema)); assertEquals(0, BinaryData.compare(b2, 0, b2, 0, schema)); assertEquals(-1, compare(o1, o2, schema, comparable, comparator)); assertEquals(1, compare(o2, o1, schema, comparable, comparator)); assertEquals(0, compare(o1, o1, schema, comparable, comparator)); assertEquals(0, compare(o2, o2, schema, comparable, comparator)); assert (o1.equals(o1)); assert (o2.equals(o2)); assert (!o1.equals(o2)); assert (!o2.equals(o1)); assert (!o1.equals(new Object())); assert (!o2.equals(new Object())); assert (!o1.equals(null)); assert (!o2.equals(null)); assert (o1.hashCode() != o2.hashCode()); // check BinaryData.hashCode against Object.hashCode if (schema.getType() != Schema.Type.ENUM) { assertEquals(o1.hashCode(), BinaryData.hashCode(b1, 0, b1.length, schema)); assertEquals(o2.hashCode(), BinaryData.hashCode(b2, 0, b2.length, schema)); } // check BinaryData.hashCode against GenericData.hashCode assertEquals(comparator.hashCode(o1, schema), BinaryData.hashCode(b1, 0, b1.length, schema)); assertEquals(comparator.hashCode(o2, schema), BinaryData.hashCode(b2, 0, b2.length, schema)); } @SuppressWarnings(value = "unchecked") private static int compare(Object o1, Object o2, Schema schema, boolean comparable, GenericData comparator) { return comparable ? ((Comparable<Object>) o1).compareTo(o2) : comparator.compare(o1, o2, schema); } private static <T> byte[] render(T datum, Schema schema, DatumWriter<T> writer) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); writer.setSchema(schema); Encoder enc = new EncoderFactory().directBinaryEncoder(out, null); writer.write(datum, enc); enc.flush(); return out.toByteArray(); } }
TestCompare
java
quarkusio__quarkus
core/devmode-spi/src/main/java/io/quarkus/dev/console/BasicConsole.java
{ "start": 295, "end": 5333 }
class ____ extends QuarkusConsole { private static final Logger log = Logger.getLogger(BasicConsole.class.getName()); private static final ThreadLocal<Boolean> DISABLE_FILTER = new ThreadLocal<>() { @Override protected Boolean initialValue() { return false; } }; final Consumer<String> output; final Supplier<Integer> input; final boolean inputSupport; final boolean color; volatile boolean readingLine; public BasicConsole(boolean color, boolean inputSupport, PrintStream printStream, Console console) { this(color, inputSupport, (s) -> { if (TerminalUtils.isTerminal(console)) { console.writer().print(s); console.writer().flush(); } else { printStream.print(s); } }, () -> { try { return System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } }); } public BasicConsole(boolean color, boolean inputSupport, Consumer<String> output) { this(color, inputSupport, output, () -> { try { return System.in.read(); } catch (IOException e) { throw new RuntimeException(e); } }); } public BasicConsole(boolean color, boolean inputSupport, Consumer<String> output, Supplier<Integer> inputProvider) { this.color = color; this.inputSupport = inputSupport; this.output = output; this.input = inputProvider; if (inputSupport) { Objects.requireNonNull(inputProvider); Thread t = new Thread(new Runnable() { @Override public void run() { while (true) { try { int val = input.get(); if (val == -1) { return; } if (readingLine) { //when doing a read line we want to discard the first \n //as this was the one that was needed to activate this mode if (val == '\n' || val == '\r') { readingLine = false; continue; } } var handler = inputHandler; if (handler != null) { handler.accept(new int[] { val }); } } catch (Exception e) { log.error("Failed to read user input", e); return; } } } }, "Quarkus Terminal Reader"); t.setDaemon(true); t.start(); } } @Override public void doReadLine() { readingLine = true; output.accept(">"); } public StatusLine registerStatusLine(int priority) { return new StatusLine() { boolean closed; String old; @Override public void setMessage(String message) { if (closed) { return; } if (message == null) { old = null; return; } if (message.equals(old)) { return; } old = message; DISABLE_FILTER.set(true); try { System.out.println(message); } finally { DISABLE_FILTER.set(false); } } @Override public void close() { closed = true; } }; } @Override public void setPromptMessage(String prompt) { if (!inputSupport) { return; } if (prompt == null) { return; } DISABLE_FILTER.set(true); try { System.out.println(prompt); } finally { DISABLE_FILTER.set(false); } } @Override public void write(boolean errorStream, String s) { if (!shouldWrite(errorStream, s)) { //we still test, the output filter may be recording output if (!DISABLE_FILTER.get()) { return; } } if (!color) { output.accept(stripAnsiCodes(s)); } else { output.accept(s); } } @Override public void write(boolean errorStream, byte[] buf, int off, int len) { write(errorStream, new String(buf, off, len, StandardCharsets.UTF_8)); } @Override public boolean isInputSupported() { return inputSupport; } }
BasicConsole
java
redisson__redisson
redisson/src/test/java/org/redisson/RedissonRemoteServiceTest.java
{ "start": 3221, "end": 3463 }
interface ____ { RFuture<Void> voidMethod1(String name, Long param); RFuture<Long> resultMethod(Long value); } @RRemoteAsync(RemoteInterface.class) public
RemoteInterfaceWrongMethodAsync
java
redisson__redisson
redisson-spring-boot-starter/src/main/java/org/redisson/spring/starter/RedissonAutoConfigurationCustomizer.java
{ "start": 918, "end": 1139 }
interface ____ { /** * Customize the RedissonClient configuration. * @param configuration the {@link Config} to customize */ void customize(Config configuration); }
RedissonAutoConfigurationCustomizer
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnnecessaryAsyncTest.java
{ "start": 7214, "end": 7410 }
class ____ { int test() { int ai = 0; ai = ai + 1; return ai; } } """) .doTest(); } }
Test
java
spring-projects__spring-boot
module/spring-boot-zipkin/src/test/java/org/springframework/boot/zipkin/autoconfigure/ZipkinHttpSenderTests.java
{ "start": 1091, "end": 1226 }
class ____ is used for testing the different implementations of the * {@link HttpSender}. * * @author Stefan Bratanov */ abstract
which
java
quarkusio__quarkus
integration-tests/opentelemetry-exporter-logging/src/test/java/org/acme/LoggingMetricsNotPresentTest.java
{ "start": 474, "end": 1984 }
class ____ { @Test void testHelloEndpoint() throws InterruptedException { final TestingJulHandler julHandler = new TestingJulHandler(); final Logger rootLogger = LogManager.getLogManager().getLogger(""); rootLogger.addHandler(julHandler); Thread.sleep(100);// give time to export metrics records (but must not be there) given() .when().get("/hello") .then() .statusCode(200) .body(is("Hello from Quarkus REST")); await().untilAsserted(() -> { assertThat(julHandler.logRecords).hasSizeGreaterThanOrEqualTo(1); }); ArrayList<LogRecord> logRecords = julHandler.logRecords; rootLogger.removeHandler(julHandler); assertThat(logRecords.stream() .anyMatch(logRecord -> logRecord.getLoggerName().startsWith(GreetingResource.class.getName()))) .as("Log line from the service must be logged") .isTrue(); // Only present if opentelemetry-exporter-logging is used // But we are turning it off if metrics are disabled assertThat(logRecords.stream() .noneMatch(logRecord -> logRecord.getLoggerName() .startsWith("io.opentelemetry.exporter.logging.LoggingMetricExporter"))) .as("Log lines from the OTel logging metrics exporter must NOT be logged") .isTrue(); } private static
LoggingMetricsNotPresentTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/tmall/Head.java
{ "start": 338, "end": 2336 }
class ____ { @JSONField(name = "Status") private String status; @JSONField(name = "SearchTime") private String searchTime; @JSONField(name = "Version") private String version; @JSONField(name = "DocsFound") private String docsFound; @JSONField(name = "DocsRestrict") private String docsRestrict; @JSONField(name = "DocsReturn") private String docsReturn; @JSONField(name = "DocsSearch") private String docsSearch; @JSONField(name="HasPrePage") private String hasPrePage; @JSONField(name="HasNextPage") private String hasNextPage; public String getHasPrePage() { return hasPrePage; } public void setHasPrePage(String hasPrePage) { this.hasPrePage = hasPrePage; } public String getHasNextPage() { return hasNextPage; } public void setHasNextPage(String hasNextPage) { this.hasNextPage = hasNextPage; } public String getDocsFound() { return docsFound; } public void setDocsFound(String docsFound) { this.docsFound = docsFound; } public String getDocsRestrict() { return docsRestrict; } public void setDocsRestrict(String docsRestrict) { this.docsRestrict = docsRestrict; } public String getDocsReturn() { return docsReturn; } public void setDocsReturn(String docsReturn) { this.docsReturn = docsReturn; } public String getDocsSearch() { return docsSearch; } public void setDocsSearch(String docsSearch) { this.docsSearch = docsSearch; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getSearchTime() { return searchTime; } public void setSearchTime(String searchTime) { this.searchTime = searchTime; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } }
Head
java
resilience4j__resilience4j
resilience4j-reactor/src/main/java/io/github/resilience4j/reactor/retry/RetryOperator.java
{ "start": 3780, "end": 4113 }
class ____ extends RuntimeException { private final long waitDurationMillis; RetryDueToResultException(long waitDurationMillis) { super("retry due to retryOnResult predicate"); this.waitDurationMillis = waitDurationMillis; } } } }
RetryDueToResultException
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/web/TestWebHdfsWithAuthenticationFilter.java
{ "start": 1753, "end": 1865 }
class ____ { private static boolean authorized = false; public static final
TestWebHdfsWithAuthenticationFilter
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/HeapBroadcastState.java
{ "start": 1649, "end": 5447 }
class ____<K, V> implements BackendWritableBroadcastState<K, V> { /** Meta information of the state, including state name, assignment mode, and serializer. */ private RegisteredBroadcastStateBackendMetaInfo<K, V> stateMetaInfo; /** The internal map the holds the elements of the state. */ private final Map<K, V> backingMap; /** A serializer that allows to perform deep copies of internal map state. */ private MapSerializer<K, V> internalMapCopySerializer; HeapBroadcastState(RegisteredBroadcastStateBackendMetaInfo<K, V> stateMetaInfo) { this(stateMetaInfo, new HashMap<>()); } private HeapBroadcastState( final RegisteredBroadcastStateBackendMetaInfo<K, V> stateMetaInfo, final Map<K, V> internalMap) { this.stateMetaInfo = Preconditions.checkNotNull(stateMetaInfo); this.backingMap = Preconditions.checkNotNull(internalMap); this.internalMapCopySerializer = new MapSerializer<>( stateMetaInfo.getKeySerializer(), stateMetaInfo.getValueSerializer()); } private HeapBroadcastState(HeapBroadcastState<K, V> toCopy) { this( toCopy.stateMetaInfo.deepCopy(), toCopy.internalMapCopySerializer.copy(toCopy.backingMap)); } @Override public void setStateMetaInfo(RegisteredBroadcastStateBackendMetaInfo<K, V> stateMetaInfo) { this.internalMapCopySerializer = new MapSerializer<>( stateMetaInfo.getKeySerializer(), stateMetaInfo.getValueSerializer()); this.stateMetaInfo = stateMetaInfo; } @Override public RegisteredBroadcastStateBackendMetaInfo<K, V> getStateMetaInfo() { return stateMetaInfo; } @Override public HeapBroadcastState<K, V> deepCopy() { return new HeapBroadcastState<>(this); } @Override public void clear() { backingMap.clear(); } @Override public String toString() { return "HeapBroadcastState{" + "stateMetaInfo=" + stateMetaInfo + ", backingMap=" + backingMap + ", internalMapCopySerializer=" + internalMapCopySerializer + '}'; } @Override public long write(FSDataOutputStream out) throws IOException { long partitionOffset = out.getPos(); DataOutputView dov = new DataOutputViewStreamWrapper(out); dov.writeInt(backingMap.size()); for (Map.Entry<K, V> entry : backingMap.entrySet()) { getStateMetaInfo().getKeySerializer().serialize(entry.getKey(), dov); getStateMetaInfo().getValueSerializer().serialize(entry.getValue(), dov); } return partitionOffset; } @Override public V get(K key) { return backingMap.get(key); } @Override public void put(K key, V value) { backingMap.put(key, value); } @Override public void putAll(Map<K, V> map) { backingMap.putAll(map); } @Override public void remove(K key) { backingMap.remove(key); } @Override public boolean contains(K key) { return backingMap.containsKey(key); } @Override public Iterator<Map.Entry<K, V>> iterator() { return backingMap.entrySet().iterator(); } @Override public Iterable<Map.Entry<K, V>> entries() { return backingMap.entrySet(); } @Override public Iterable<Map.Entry<K, V>> immutableEntries() { return Collections.unmodifiableSet(backingMap.entrySet()); } @VisibleForTesting public MapSerializer<K, V> getInternalMapCopySerializer() { return internalMapCopySerializer; } }
HeapBroadcastState
java
quarkusio__quarkus
extensions/hibernate-orm/deployment/src/main/java/io/quarkus/hibernate/orm/deployment/HibernateOrmConfigPersistenceUnit.java
{ "start": 23126, "end": 23922 }
interface ____ { String DEFAULT_CHARSET = "UTF-8"; /** * The charset of the database. * <p> * Used for DDL generation and also for the SQL import scripts. */ @WithDefault(DEFAULT_CHARSET) Charset charset(); /** * Whether Hibernate should quote all identifiers. * * @deprecated {@link #quoteIdentifiers} should be used to configure quoting strategy. */ @Deprecated @WithDefault("false") boolean globallyQuotedIdentifiers(); default boolean isAnyPropertySet() { return !DEFAULT_CHARSET.equals(charset().name()) || globallyQuotedIdentifiers(); } } @ConfigGroup
HibernateOrmConfigPersistenceUnitDatabase
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/RangeTest.java
{ "start": 1900, "end": 16702 }
class ____ extends AbstractComparable { // empty } private Range<Byte> byteRange; private Range<Byte> byteRange2; private Range<Byte> byteRange3; private Range<Double> doubleRange; private Range<Float> floatRange; private Range<Integer> intRange; private Range<Long> longRange; @BeforeEach public void setUp() { byteRange = Range.of((byte) 0, (byte) 5); byteRange2 = Range.of((byte) 0, (byte) 5); byteRange3 = Range.of((byte) 0, (byte) 10); intRange = Range.of(10, 20); longRange = Range.of(10L, 20L); floatRange = Range.of((float) 10, (float) 20); doubleRange = Range.of((double) 10, (double) 20); } @Test void testBetweenWithCompare() { // all integers are equal final Comparator<Integer> c = (o1, o2) -> 0; final Comparator<String> lengthComp = Comparator.comparingInt(String::length); Range<Integer> rb = Range.between(-10, 20); assertFalse(rb.contains(null), "should not contain null"); assertTrue(rb.contains(10), "should contain 10"); assertTrue(rb.contains(-10), "should contain -10"); assertFalse(rb.contains(21), "should not contain 21"); assertFalse(rb.contains(-11), "should not contain -11"); rb = Range.between(-10, 20, c); assertFalse(rb.contains(null), "should not contain null"); assertTrue(rb.contains(10), "should contain 10"); assertTrue(rb.contains(-10), "should contain -10"); assertTrue(rb.contains(21), "should contain 21"); assertTrue(rb.contains(-11), "should contain -11"); Range<String> rbstr = Range.between("house", "i"); assertFalse(rbstr.contains(null), "should not contain null"); assertTrue(rbstr.contains("house"), "should contain house"); assertTrue(rbstr.contains("i"), "should contain i"); assertFalse(rbstr.contains("hose"), "should not contain hose"); assertFalse(rbstr.contains("ice"), "should not contain ice"); rbstr = Range.between("house", "i", lengthComp); assertFalse(rbstr.contains(null), "should not contain null"); assertTrue(rbstr.contains("house"), "should contain house"); assertTrue(rbstr.contains("i"), "should contain i"); assertFalse(rbstr.contains("houses"), "should not contain houses"); assertFalse(rbstr.contains(""), "should not contain ''"); assertNullPointerException(() -> Range.between(null, null, lengthComp)); } @SuppressWarnings({"rawtypes", "unchecked"}) @Test void testComparableConstructors() { final Comparable c = other -> 1; final Range r1 = Range.is(c); final Range r2 = Range.between(c, c); assertTrue(r1.isNaturalOrdering()); assertTrue(r2.isNaturalOrdering()); } @Test void testConstructorSignatureWithAbstractComparableClasses() { final DerivedComparableA derivedComparableA = new DerivedComparableA(); final DerivedComparableB derivedComparableB = new DerivedComparableB(); final Range<AbstractComparable> mixed = Range.between(derivedComparableA, derivedComparableB, null); assertTrue(mixed.contains(derivedComparableA)); final Range<AbstractComparable> same = Range.between(derivedComparableA, derivedComparableA, null); assertTrue(same.contains(derivedComparableA)); final Range<DerivedComparableA> rangeA = Range.between(derivedComparableA, derivedComparableA, null); assertTrue(rangeA.contains(derivedComparableA)); final Range<DerivedComparableB> rangeB = Range.is(derivedComparableB, null); assertTrue(rangeB.contains(derivedComparableB)); } @Test void testContains() { assertFalse(intRange.contains(null)); assertFalse(intRange.contains(5)); assertTrue(intRange.contains(10)); assertTrue(intRange.contains(15)); assertTrue(intRange.contains(20)); assertFalse(intRange.contains(25)); } @Test void testContainsRange() { // null handling assertFalse(intRange.containsRange(null)); // easy inside range assertTrue(intRange.containsRange(Range.between(12, 18))); // outside range on each side assertFalse(intRange.containsRange(Range.between(32, 45))); assertFalse(intRange.containsRange(Range.between(2, 8))); // equals range assertTrue(intRange.containsRange(Range.between(10, 20))); // overlaps assertFalse(intRange.containsRange(Range.between(9, 14))); assertFalse(intRange.containsRange(Range.between(16, 21))); // touches lower boundary assertTrue(intRange.containsRange(Range.between(10, 19))); assertFalse(intRange.containsRange(Range.between(10, 21))); // touches upper boundary assertTrue(intRange.containsRange(Range.between(11, 20))); assertFalse(intRange.containsRange(Range.between(9, 20))); // negative assertFalse(intRange.containsRange(Range.between(-11, -18))); } @Test void testElementCompareTo() { assertNullPointerException(() -> intRange.elementCompareTo(null)); assertEquals(-1, intRange.elementCompareTo(5)); assertEquals(0, intRange.elementCompareTo(10)); assertEquals(0, intRange.elementCompareTo(15)); assertEquals(0, intRange.elementCompareTo(20)); assertEquals(1, intRange.elementCompareTo(25)); } @Test void testEqualsObject() { assertEquals(byteRange, byteRange); assertEquals(byteRange, byteRange2); assertEquals(byteRange2, byteRange2); assertEquals(byteRange, byteRange); assertEquals(byteRange2, byteRange2); assertEquals(byteRange3, byteRange3); assertNotEquals(byteRange2, byteRange3); assertNotEquals(null, byteRange2); assertNotEquals("Ni!", byteRange2); } @Test void testFit() { assertEquals(intRange.getMinimum(), intRange.fit(Integer.MIN_VALUE)); assertEquals(intRange.getMinimum(), intRange.fit(intRange.getMinimum())); assertEquals(intRange.getMaximum(), intRange.fit(Integer.MAX_VALUE)); assertEquals(intRange.getMaximum(), intRange.fit(intRange.getMaximum())); assertEquals(15, intRange.fit(15)); } @Test void testFitNull() { assertNullPointerException(() -> { intRange.fit(null); }); } @Test void testGetMaximum() { assertEquals(20, (int) intRange.getMaximum()); assertEquals(20L, (long) longRange.getMaximum()); assertEquals(20f, floatRange.getMaximum(), 0.00001f); assertEquals(20d, doubleRange.getMaximum(), 0.00001d); } @Test void testGetMinimum() { assertEquals(10, (int) intRange.getMinimum()); assertEquals(10L, (long) longRange.getMinimum()); assertEquals(10f, floatRange.getMinimum(), 0.00001f); assertEquals(10d, doubleRange.getMinimum(), 0.00001d); } @Test void testHashCode() { assertEquals(byteRange.hashCode(), byteRange2.hashCode()); assertNotEquals(byteRange.hashCode(), byteRange3.hashCode()); assertEquals(intRange.hashCode(), intRange.hashCode()); assertTrue(intRange.hashCode() != 0); } @Test void testIntersectionWith() { assertSame(intRange, intRange.intersectionWith(intRange)); assertSame(byteRange, byteRange.intersectionWith(byteRange)); assertSame(longRange, longRange.intersectionWith(longRange)); assertSame(floatRange, floatRange.intersectionWith(floatRange)); assertSame(doubleRange, doubleRange.intersectionWith(doubleRange)); assertEquals(Range.between(10, 15), intRange.intersectionWith(Range.between(5, 15))); } @Test void testIntersectionWithNonOverlapping() { assertIllegalArgumentException(() -> intRange.intersectionWith(Range.between(0, 9))); } @Test void testIntersectionWithNull() { assertIllegalArgumentException(() -> intRange.intersectionWith(null)); } @Test void testIsAfter() { assertFalse(intRange.isAfter(null)); assertTrue(intRange.isAfter(5)); assertFalse(intRange.isAfter(10)); assertFalse(intRange.isAfter(15)); assertFalse(intRange.isAfter(20)); assertFalse(intRange.isAfter(25)); } @Test void testIsAfterRange() { assertFalse(intRange.isAfterRange(null)); assertTrue(intRange.isAfterRange(Range.between(5, 9))); assertFalse(intRange.isAfterRange(Range.between(5, 10))); assertFalse(intRange.isAfterRange(Range.between(5, 20))); assertFalse(intRange.isAfterRange(Range.between(5, 25))); assertFalse(intRange.isAfterRange(Range.between(15, 25))); assertFalse(intRange.isAfterRange(Range.between(21, 25))); assertFalse(intRange.isAfterRange(Range.between(10, 20))); } @Test void testIsBefore() { assertFalse(intRange.isBefore(null)); assertFalse(intRange.isBefore(5)); assertFalse(intRange.isBefore(10)); assertFalse(intRange.isBefore(15)); assertFalse(intRange.isBefore(20)); assertTrue(intRange.isBefore(25)); } @Test void testIsBeforeRange() { assertFalse(intRange.isBeforeRange(null)); assertFalse(intRange.isBeforeRange(Range.between(5, 9))); assertFalse(intRange.isBeforeRange(Range.between(5, 10))); assertFalse(intRange.isBeforeRange(Range.between(5, 20))); assertFalse(intRange.isBeforeRange(Range.between(5, 25))); assertFalse(intRange.isBeforeRange(Range.between(15, 25))); assertTrue(intRange.isBeforeRange(Range.between(21, 25))); assertFalse(intRange.isBeforeRange(Range.between(10, 20))); } @Test void testIsEndedBy() { assertFalse(intRange.isEndedBy(null)); assertFalse(intRange.isEndedBy(5)); assertFalse(intRange.isEndedBy(10)); assertFalse(intRange.isEndedBy(15)); assertTrue(intRange.isEndedBy(20)); assertFalse(intRange.isEndedBy(25)); } @Test void testIsOverlappedBy() { // null handling assertFalse(intRange.isOverlappedBy(null)); // easy inside range assertTrue(intRange.isOverlappedBy(Range.between(12, 18))); // outside range on each side assertFalse(intRange.isOverlappedBy(Range.between(32, 45))); assertFalse(intRange.isOverlappedBy(Range.between(2, 8))); // equals range assertTrue(intRange.isOverlappedBy(Range.between(10, 20))); // overlaps assertTrue(intRange.isOverlappedBy(Range.between(9, 14))); assertTrue(intRange.isOverlappedBy(Range.between(16, 21))); // touches lower boundary assertTrue(intRange.isOverlappedBy(Range.between(10, 19))); assertTrue(intRange.isOverlappedBy(Range.between(10, 21))); // touches upper boundary assertTrue(intRange.isOverlappedBy(Range.between(11, 20))); assertTrue(intRange.isOverlappedBy(Range.between(9, 20))); // negative assertFalse(intRange.isOverlappedBy(Range.between(-11, -18))); // outside range whole range assertTrue(intRange.isOverlappedBy(Range.between(9, 21))); } @Test void testIsStartedBy() { assertFalse(intRange.isStartedBy(null)); assertFalse(intRange.isStartedBy(5)); assertTrue(intRange.isStartedBy(10)); assertFalse(intRange.isStartedBy(15)); assertFalse(intRange.isStartedBy(20)); assertFalse(intRange.isStartedBy(25)); } @Test void testIsWithCompare() { // all integers are equal final Comparator<Integer> c = (o1, o2) -> 0; Range<Integer> ri = Range.is(10); assertFalse(ri.contains(null), "should not contain null"); assertTrue(ri.contains(10), "should contain 10"); assertFalse(ri.contains(11), "should not contain 11"); ri = Range.is(10, c); assertFalse(ri.contains(null), "should not contain null"); assertTrue(ri.contains(10), "should contain 10"); assertTrue(ri.contains(11), "should contain 11"); } @Test void testOfWithCompare() { // all integers are equal final Comparator<Integer> c = (o1, o2) -> 0; final Comparator<String> lengthComp = Comparator.comparingInt(String::length); Range<Integer> rb = Range.of(-10, 20); assertFalse(rb.contains(null), "should not contain null"); assertTrue(rb.contains(10), "should contain 10"); assertTrue(rb.contains(-10), "should contain -10"); assertFalse(rb.contains(21), "should not contain 21"); assertFalse(rb.contains(-11), "should not contain -11"); rb = Range.of(-10, 20, c); assertFalse(rb.contains(null), "should not contain null"); assertTrue(rb.contains(10), "should contain 10"); assertTrue(rb.contains(-10), "should contain -10"); assertTrue(rb.contains(21), "should contain 21"); assertTrue(rb.contains(-11), "should contain -11"); Range<String> rbstr = Range.of("house", "i"); assertFalse(rbstr.contains(null), "should not contain null"); assertTrue(rbstr.contains("house"), "should contain house"); assertTrue(rbstr.contains("i"), "should contain i"); assertFalse(rbstr.contains("hose"), "should not contain hose"); assertFalse(rbstr.contains("ice"), "should not contain ice"); rbstr = Range.of("house", "i", lengthComp); assertFalse(rbstr.contains(null), "should not contain null"); assertTrue(rbstr.contains("house"), "should contain house"); assertTrue(rbstr.contains("i"), "should contain i"); assertFalse(rbstr.contains("houses"), "should not contain houses"); assertFalse(rbstr.contains(""), "should not contain ''"); assertNullPointerException(() -> Range.of(null, null, lengthComp)); } @Test void testRangeOfChars() { final Range<Character> chars = Range.between('a', 'z'); assertTrue(chars.contains('b')); assertFalse(chars.contains('B')); } @Test void testSerializing() { SerializationUtils.clone(intRange); } @Test void testToString() { assertNotNull(byteRange.toString()); final String str = intRange.toString(); assertEquals("[10..20]", str); assertEquals("[-20..-10]", Range.between(-20, -10).toString()); } @Test void testToStringFormat() { final String str = intRange.toString("From %1$s to %2$s"); assertEquals("From 10 to 20", str); } }
DerivedComparableB
java
quarkusio__quarkus
integration-tests/oidc-wiremock/src/main/java/io/quarkus/it/keycloak/DefaultTenantTokenCustomizer.java
{ "start": 295, "end": 1049 }
class ____ implements TokenCustomizer { volatile int rs256Count; @Override public JsonObject customizeHeaders(JsonObject headers) { if (!headers.containsKey("customize")) { return null; } String alg = headers.getString("alg"); if ("RS256".equals(alg)) { if (0 == rs256Count++) { return null; } else { return Json.createObjectBuilder(headers).remove("customize").build(); } } else if ("RS384".equals(alg)) { return null; } else if ("RS512".equals(alg)) { return Json.createObjectBuilder(headers).add("alg", "RS256").build(); } return null; } }
DefaultTenantTokenCustomizer
java
quarkusio__quarkus
integration-tests/main/src/test/java/io/quarkus/it/main/ResourcesITCase.java
{ "start": 185, "end": 752 }
class ____ extends ResourcesTestCase { @Test public void excludedNative() { RestAssured.when() .get("/resources/test-resources/file.adoc") .then() .statusCode(404); RestAssured.when() .get("/resources/test-resources/excluded/unwanted.txt") .then() .statusCode(404); RestAssured.when() .get("/resources/META-INF/quarkus-native-resources.txt") .then() .statusCode(404); } }
ResourcesITCase
java
apache__camel
dsl/camel-yaml-dsl/camel-yaml-dsl-deserializers/src/generated/java/org/apache/camel/dsl/yaml/deserializers/ModelDeserializers.java
{ "start": 1047110, "end": 1049645 }
class ____ extends YamlDeserializerBase<SetVariablesDefinition> { public SetVariablesDefinitionDeserializer() { super(SetVariablesDefinition.class); } @Override protected SetVariablesDefinition newInstance() { return new SetVariablesDefinition(); } @Override protected boolean setProperty(SetVariablesDefinition target, String propertyKey, String propertyName, Node node) { propertyKey = org.apache.camel.util.StringHelper.dashToCamelCase(propertyKey); switch(propertyKey) { case "disabled": { String val = asText(node); target.setDisabled(val); break; } case "variables": { java.util.List<org.apache.camel.model.SetVariableDefinition> val = asFlatList(node, org.apache.camel.model.SetVariableDefinition.class); target.setVariables(val); break; } case "id": { String val = asText(node); target.setId(val); break; } case "description": { String val = asText(node); target.setDescription(val); break; } case "note": { String val = asText(node); target.setNote(val); break; } default: { return false; } } return true; } } @YamlType( nodes = "simple", inline = true, types = org.apache.camel.model.language.SimpleExpression.class, order = org.apache.camel.dsl.yaml.common.YamlDeserializerResolver.ORDER_LOWEST - 1, displayName = "Simple", description = "Evaluates a Camel simple expression.", deprecated = false, properties = { @YamlProperty(name = "expression", type = "string", required = true, description = "The expression value in your chosen language syntax", displayName = "Expression"), @YamlProperty(name = "id", type = "string", description = "Sets the id of this node", displayName = "Id"), @YamlProperty(name = "resultType", type = "string", description = "Sets the
SetVariablesDefinitionDeserializer
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/JavaBeanMappingTest.java
{ "start": 155, "end": 288 }
class ____ extends TestCase { public void test_0 () throws Exception { ParserConfig.getGlobalInstance(); } }
JavaBeanMappingTest
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/SkipForDialects.java
{ "start": 694, "end": 751 }
interface ____ { SkipForDialect[] value(); }
SkipForDialects
java
playframework__playframework
web/play-filters-helpers/src/main/java/play/filters/components/AllowedHostsComponents.java
{ "start": 476, "end": 839 }
interface ____ extends ConfigurationComponents, HttpErrorHandlerComponents { default AllowedHostsConfig allowedHostsConfig() { return AllowedHostsConfig.fromConfiguration(configuration()); } default AllowedHostsFilter allowedHostsFilter() { return new AllowedHostsFilter(allowedHostsConfig(), scalaHttpErrorHandler()); } }
AllowedHostsComponents
java
apache__hadoop
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/TreePath.java
{ "start": 1135, "end": 1746 }
class ____ { final TreePath parent; final String fieldName; final int index; public TreePath(TreePath parent, String fieldName) { super(); this.parent = parent; this.fieldName = fieldName; this.index = -1; } public TreePath(TreePath parent, String fieldName, int index) { super(); this.parent = parent; this.fieldName = fieldName; this.index = index; } @Override public String toString() { String mySegment = fieldName + (index == -1 ? "" : ("[" + index + "]")); return ((parent == null) ? "" : parent.toString() + "-->") + mySegment; } }
TreePath
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/stream/keyselector/AttributeBasedJoinKeyExtractor.java
{ "start": 35306, "end": 35664 }
class ____ two separate {@link RowData.FieldGetter} instances because a key extractor * may need to extract a field from the left (already joined) side, which is a wide, * concatenated row, or the right (current input) side, which is a single source row. The field * indices for these two cases are different. */ private static final
uses
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/core/ConverterTest.java
{ "start": 808, "end": 5684 }
class ____ extends RxJavaTest { @Test public void flowableConverterThrows() { try { Flowable.just(1).to(new FlowableConverter<Integer, Integer>() { @Override public Integer apply(Flowable<Integer> v) { throw new TestException("Forced failure"); } }); fail("Should have thrown!"); } catch (TestException ex) { assertEquals("Forced failure", ex.getMessage()); } } @Test public void observableConverterThrows() { try { Observable.just(1).to(new ObservableConverter<Integer, Integer>() { @Override public Integer apply(Observable<Integer> v) { throw new TestException("Forced failure"); } }); fail("Should have thrown!"); } catch (TestException ex) { assertEquals("Forced failure", ex.getMessage()); } } @Test public void singleConverterThrows() { try { Single.just(1).to(new SingleConverter<Integer, Integer>() { @Override public Integer apply(Single<Integer> v) { throw new TestException("Forced failure"); } }); fail("Should have thrown!"); } catch (TestException ex) { assertEquals("Forced failure", ex.getMessage()); } } @Test public void maybeConverterThrows() { try { Maybe.just(1).to(new MaybeConverter<Integer, Integer>() { @Override public Integer apply(Maybe<Integer> v) { throw new TestException("Forced failure"); } }); fail("Should have thrown!"); } catch (TestException ex) { assertEquals("Forced failure", ex.getMessage()); } } @Test public void completableConverterThrows() { try { Completable.complete().to(new CompletableConverter<Completable>() { @Override public Completable apply(Completable v) { throw new TestException("Forced failure"); } }); fail("Should have thrown!"); } catch (TestException ex) { assertEquals("Forced failure", ex.getMessage()); } } // Test demos for signature generics in compose() methods. Just needs to compile. @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void observableGenericsSignatureTest() { A<String, Integer> a = new A<String, Integer>() { }; Observable.just(a).to((ObservableConverter)ConverterTest.testObservableConverterCreator()); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void singleGenericsSignatureTest() { A<String, Integer> a = new A<String, Integer>() { }; Single.just(a).to((SingleConverter)ConverterTest.<String>testSingleConverterCreator()); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void maybeGenericsSignatureTest() { A<String, Integer> a = new A<String, Integer>() { }; Maybe.just(a).to((MaybeConverter)ConverterTest.<String>testMaybeConverterCreator()); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void flowableGenericsSignatureTest() { A<String, Integer> a = new A<String, Integer>() { }; Flowable.just(a).to((FlowableConverter)ConverterTest.<String>testFlowableConverterCreator()); } @SuppressWarnings({ "rawtypes", "unchecked" }) @Test public void parallelFlowableGenericsSignatureTest() { A<String, Integer> a = new A<String, Integer>() { }; Flowable.just(a).parallel().to((ParallelFlowableConverter)ConverterTest.<String>testParallelFlowableConverterCreator()); } @Test public void compositeTest() { CompositeConverter converter = new CompositeConverter(); Flowable.just(1) .to(converter) .test() .assertValue(1); Observable.just(1) .to(converter) .test() .assertValue(1); Maybe.just(1) .to(converter) .test() .assertValue(1); Single.just(1) .to(converter) .test() .assertValue(1); Completable.complete() .to(converter) .test() .assertComplete(); Flowable.just(1) .parallel() .to(converter) .test() .assertValue(1); } /** * Two argument type. * @param <T> the input type * @param <R> the output type */
ConverterTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/container/ContainerImpl.java
{ "start": 64234, "end": 64830 }
class ____ extends ContainerTransition { @Override public void transition(ContainerImpl container, ContainerEvent event) { ContainerResourceFailedEvent failedEvent = (ContainerResourceFailedEvent) event; container.resourceSet .resourceLocalizationFailed(failedEvent.getResource(), failedEvent.getDiagnosticMessage()); container.addDiagnostics(failedEvent.getDiagnosticMessage()); } } /** * Resource localization failed while the container is reinitializing. */ static
ResourceLocalizationFailedWhileRunningTransition
java
apache__maven
api/maven-api-spi/src/main/java/org/apache/maven/api/spi/LifecycleProvider.java
{ "start": 1411, "end": 1612 }
interface ____ be discovered through the Java ServiceLoader mechanism * and their provided lifecycles will be available throughout the Maven build process. * <p> * Example usage: * <pre> * public
will
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/context/request/async/WebAsyncUtils.java
{ "start": 1110, "end": 3254 }
class ____ { /** * The name attribute containing the {@link WebAsyncManager}. */ public static final String WEB_ASYNC_MANAGER_ATTRIBUTE = WebAsyncManager.class.getName() + ".WEB_ASYNC_MANAGER"; /** * Obtain the {@link WebAsyncManager} for the current request, or if not * found, create and associate it with the request. */ public static WebAsyncManager getAsyncManager(ServletRequest servletRequest) { WebAsyncManager asyncManager = null; Object asyncManagerAttr = servletRequest.getAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE); if (asyncManagerAttr instanceof WebAsyncManager wam) { asyncManager = wam; } if (asyncManager == null) { asyncManager = new WebAsyncManager(); servletRequest.setAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE, asyncManager); } return asyncManager; } /** * Obtain the {@link WebAsyncManager} for the current request, or if not * found, create and associate it with the request. */ public static WebAsyncManager getAsyncManager(WebRequest webRequest) { int scope = RequestAttributes.SCOPE_REQUEST; WebAsyncManager asyncManager = null; Object asyncManagerAttr = webRequest.getAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE, scope); if (asyncManagerAttr instanceof WebAsyncManager wam) { asyncManager = wam; } if (asyncManager == null) { asyncManager = new WebAsyncManager(); webRequest.setAttribute(WEB_ASYNC_MANAGER_ATTRIBUTE, asyncManager, scope); } return asyncManager; } /** * Create an AsyncWebRequest instance. By default, an instance of * {@link StandardServletAsyncWebRequest} gets created. * @param request the current request * @param response the current response * @return an AsyncWebRequest instance (never {@code null}) */ public static AsyncWebRequest createAsyncWebRequest(HttpServletRequest request, HttpServletResponse response) { AsyncWebRequest prev = getAsyncManager(request).getAsyncWebRequest(); return (prev instanceof StandardServletAsyncWebRequest standardRequest ? new StandardServletAsyncWebRequest(request, response, standardRequest) : new StandardServletAsyncWebRequest(request, response)); } }
WebAsyncUtils
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/rm/TestRMContainerAllocator.java
{ "start": 142697, "end": 145872 }
class ____ implements ApplicationMasterProtocol { ApplicationAttemptId attemptId; long nextContainerId = 10; List<ResourceRequest> lastAsk = null; int lastAnyAskMap = 0; int lastAnyAskReduce = 0; List<ContainerStatus> containersToComplete = new ArrayList<ContainerStatus>(); List<Container> containersToAllocate = new ArrayList<Container>(); public MockScheduler(ApplicationAttemptId attemptId) { this.attemptId = attemptId; } @Override public RegisterApplicationMasterResponse registerApplicationMaster( RegisterApplicationMasterRequest request) throws YarnException, IOException { return RegisterApplicationMasterResponse.newInstance( Resource.newInstance(512, 1), Resource.newInstance(512000, 1024), Collections.emptyMap(), ByteBuffer.wrap("fake_key".getBytes()), Collections.<Container>emptyList(), "default", Collections.<NMToken>emptyList()); } @Override public FinishApplicationMasterResponse finishApplicationMaster( FinishApplicationMasterRequest request) throws YarnException, IOException { return FinishApplicationMasterResponse.newInstance(false); } @Override public AllocateResponse allocate(AllocateRequest request) throws YarnException, IOException { lastAsk = request.getAskList(); for (ResourceRequest req : lastAsk) { if (ResourceRequest.ANY.equals(req.getResourceName())) { Priority priority = req.getPriority(); if (priority.equals(RMContainerAllocator.PRIORITY_MAP)) { lastAnyAskMap = req.getNumContainers(); } else if (priority.equals(RMContainerAllocator.PRIORITY_REDUCE)){ lastAnyAskReduce = req.getNumContainers(); } } } AllocateResponse response = AllocateResponse.newInstance( request.getResponseId(), containersToComplete, containersToAllocate, Collections.<NodeReport>emptyList(), Resource.newInstance(512000, 1024), null, 10, null, Collections.<NMToken>emptyList()); // RM will always ensure that a default priority is sent to AM response.setApplicationPriority(Priority.newInstance(0)); containersToComplete.clear(); containersToAllocate.clear(); return response; } public ContainerId assignContainer(String nodeName, boolean isReduce) { ContainerId containerId = ContainerId.newContainerId(attemptId, nextContainerId++); Priority priority = isReduce ? RMContainerAllocator.PRIORITY_REDUCE : RMContainerAllocator.PRIORITY_MAP; Container container = Container.newInstance(containerId, NodeId.newInstance(nodeName, 1234), nodeName + ":5678", Resource.newInstance(1024, 1), priority, null); containersToAllocate.add(container); return containerId; } public void completeContainer(ContainerId containerId) { containersToComplete.add(ContainerStatus.newInstance(containerId, ContainerState.COMPLETE, "", 0)); } } private final static
MockScheduler
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/subjects/MaybeSubject.java
{ "start": 5403, "end": 11453 }
class ____<T> extends Maybe<T> implements MaybeObserver<T> { final AtomicReference<MaybeDisposable<T>[]> observers; @SuppressWarnings("rawtypes") static final MaybeDisposable[] EMPTY = new MaybeDisposable[0]; @SuppressWarnings("rawtypes") static final MaybeDisposable[] TERMINATED = new MaybeDisposable[0]; final AtomicBoolean once; T value; Throwable error; /** * Creates a fresh MaybeSubject. * @param <T> the value type received and emitted * @return the new MaybeSubject instance */ @CheckReturnValue @NonNull public static <T> MaybeSubject<T> create() { return new MaybeSubject<>(); } @SuppressWarnings("unchecked") MaybeSubject() { once = new AtomicBoolean(); observers = new AtomicReference<>(EMPTY); } @Override public void onSubscribe(Disposable d) { if (observers.get() == TERMINATED) { d.dispose(); } } @SuppressWarnings("unchecked") @Override public void onSuccess(T value) { ExceptionHelper.nullCheck(value, "onSuccess called with a null value."); if (once.compareAndSet(false, true)) { this.value = value; for (MaybeDisposable<T> md : observers.getAndSet(TERMINATED)) { md.downstream.onSuccess(value); } } } @SuppressWarnings("unchecked") @Override public void onError(Throwable e) { ExceptionHelper.nullCheck(e, "onError called with a null Throwable."); if (once.compareAndSet(false, true)) { this.error = e; for (MaybeDisposable<T> md : observers.getAndSet(TERMINATED)) { md.downstream.onError(e); } } else { RxJavaPlugins.onError(e); } } @SuppressWarnings("unchecked") @Override public void onComplete() { if (once.compareAndSet(false, true)) { for (MaybeDisposable<T> md : observers.getAndSet(TERMINATED)) { md.downstream.onComplete(); } } } @Override protected void subscribeActual(MaybeObserver<? super T> observer) { MaybeDisposable<T> md = new MaybeDisposable<>(observer, this); observer.onSubscribe(md); if (add(md)) { if (md.isDisposed()) { remove(md); } } else { Throwable ex = error; if (ex != null) { observer.onError(ex); } else { T v = value; if (v == null) { observer.onComplete(); } else { observer.onSuccess(v); } } } } boolean add(MaybeDisposable<T> inner) { for (;;) { MaybeDisposable<T>[] a = observers.get(); if (a == TERMINATED) { return false; } int n = a.length; @SuppressWarnings("unchecked") MaybeDisposable<T>[] b = new MaybeDisposable[n + 1]; System.arraycopy(a, 0, b, 0, n); b[n] = inner; if (observers.compareAndSet(a, b)) { return true; } } } @SuppressWarnings("unchecked") void remove(MaybeDisposable<T> inner) { for (;;) { MaybeDisposable<T>[] a = observers.get(); int n = a.length; if (n == 0) { return; } int j = -1; for (int i = 0; i < n; i++) { if (a[i] == inner) { j = i; break; } } if (j < 0) { return; } MaybeDisposable<T>[] b; if (n == 1) { b = EMPTY; } else { b = new MaybeDisposable[n - 1]; System.arraycopy(a, 0, b, 0, j); System.arraycopy(a, j + 1, b, j, n - j - 1); } if (observers.compareAndSet(a, b)) { return; } } } /** * Returns the success value if this MaybeSubject was terminated with a success value. * @return the success value or null */ @Nullable public T getValue() { if (observers.get() == TERMINATED) { return value; } return null; } /** * Returns true if this MaybeSubject was terminated with a success value. * @return true if this MaybeSubject was terminated with a success value */ public boolean hasValue() { return observers.get() == TERMINATED && value != null; } /** * Returns the terminal error if this MaybeSubject has been terminated with an error, null otherwise. * @return the terminal error or null if not terminated or not with an error */ @Nullable public Throwable getThrowable() { if (observers.get() == TERMINATED) { return error; } return null; } /** * Returns true if this MaybeSubject has been terminated with an error. * @return true if this MaybeSubject has been terminated with an error */ public boolean hasThrowable() { return observers.get() == TERMINATED && error != null; } /** * Returns true if this MaybeSubject has been completed. * @return true if this MaybeSubject has been completed */ public boolean hasComplete() { return observers.get() == TERMINATED && value == null && error == null; } /** * Returns true if this MaybeSubject has observers. * @return true if this MaybeSubject has observers */ public boolean hasObservers() { return observers.get().length != 0; } /** * Returns the number of current observers. * @return the number of current observers */ /* test */ int observerCount() { return observers.get().length; } static final
MaybeSubject
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/EnabledIfTests.java
{ "start": 1466, "end": 3650 }
class ____ { @Test @EnabledIf("false") void enabledIfWithStringFalse() { fail("This test must be disabled"); } @Test @EnabledIf(" false ") void enabledIfWithStringFalseWithSurroundingWhitespace() { fail("This test must be disabled"); } @Test @EnabledIf("FaLsE") void enabledIfWithStringFalseIgnoreCase() { fail("This test must be disabled"); } @Test @EnabledIf("${__EnigmaPropertyShouldNotExist__:false}") void enabledIfWithPropertyPlaceholderForNonexistentPropertyWithDefaultValue() { fail("This test must be disabled"); } @Test @EnabledIf(expression = "${foo}", loadContext = true) void enabledIfWithPropertyPlaceholder() { fail("This test must be disabled"); } @Test @EnabledIf(expression = "\t${foo} ", loadContext = true) void enabledIfWithPropertyPlaceholderWithSurroundingWhitespace() { fail("This test must be disabled"); } @Test @EnabledIf("#{T(Boolean).FALSE}") void enabledIfWithSpelBoolean() { fail("This test must be disabled"); } @Test @EnabledIf(" #{T(Boolean).FALSE} ") void enabledIfWithSpelBooleanWithSurroundingWhitespace() { fail("This test must be disabled"); } @Test @EnabledIf("#{'fal' + 'se'}") void enabledIfWithSpelStringConcatenation() { fail("This test must be disabled"); } @Test @EnabledIf("#{1 + 2 == 4}") void enabledIfWithSpelArithmeticComparison() { fail("This test must be disabled"); } @Test @EnabledOnMac void enabledIfWithSpelOsCheckInCustomComposedAnnotation() { String os = System.getProperty("os.name").toLowerCase(); assertThat(os).as("This test must be enabled on Mac OS").contains("mac"); assertThat(os).as("This test must be disabled on Windows").doesNotContain("win"); } @Test @EnabledIf(expression = "#{@booleanFalseBean}", loadContext = true) void enabledIfWithSpelBooleanFalseBean() { fail("This test must be disabled"); } @Test @EnabledIf(expression = "#{@stringFalseBean}", loadContext = true) void enabledIfWithSpelStringFalseBean() { fail("This test must be disabled"); } } @SpringJUnitConfig(Config.class) @Nested @EnabledIf("false")
EnabledIfOnMethodTests
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/hql/CoalesceTest.java
{ "start": 1073, "end": 2877 }
class ____ { final String QRY_STR = "from EntityOfBasics e where e.theString = coalesce(:p , e.theString)"; @Test public void testCoalesce(SessionFactoryScope sessions) { sessions.inTransaction( (session) -> { final List<EntityOfBasics> resultList = session.createQuery( QRY_STR, EntityOfBasics.class ) .setParameter("p", "a string") .getResultList(); assertThat( resultList ).hasSize( 1 ); } ); sessions.inTransaction( (session) -> { final List<EntityOfBasics> resultList = session.createQuery( QRY_STR, EntityOfBasics.class ) .setParameter("p", "$^&@#") .getResultList(); assertThat( resultList ).hasSize( 0 ); } ); } @Test public void testCoalesceWithNull(SessionFactoryScope sessions) { sessions.inTransaction( (session) -> { final List<EntityOfBasics> resultList = session.createQuery( QRY_STR, EntityOfBasics.class ) .setParameter("p", null) .getResultList(); assertThat( resultList ).hasSize( 1 ); } ); } @Test public void testCoalesceWithCast(SessionFactoryScope sessions) { final String qryStr = "from EntityOfBasics e where e.theString = coalesce(cast(:p as string) , e.theString)"; sessions.inTransaction( (session) -> { final List<EntityOfBasics> resultList = session.createQuery( qryStr, EntityOfBasics.class ) .setParameter("p", null) .getResultList(); assertThat( resultList ).hasSize( 1 ); } ); } @BeforeEach public void createTestData(SessionFactoryScope sessions) { sessions.inTransaction( (session) -> { final EntityOfBasics entity = new EntityOfBasics( 1 ); entity.setTheString( "a string" ); entity.setTheField( "another string" ); session.persist( entity ); } ); } @AfterEach void dropTestData(SessionFactoryScope sessions) { sessions.dropData(); } }
CoalesceTest
java
quarkusio__quarkus
test-framework/junit5/src/main/java/io/quarkus/test/junit/QuarkusIntegrationTest.java
{ "start": 1810, "end": 2060 }
class ____ with {@link QuarkusIntegrationTest}, the field is populated * with an implementation that allows accessing contextual test information * * @deprecated Use {@link DevServicesContext} instead. */ @Deprecated
annotated
java
mockito__mockito
mockito-core/src/test/java/org/mockitousage/stubbing/StubbingWithExtraAnswersTest.java
{ "start": 557, "end": 2013 }
class ____ extends TestBase { @Mock private IMethods mock; @Test public void shouldWorkAsStandardMockito() throws Exception { // when List<Integer> list = asList(1, 2, 3); when(mock.objectReturningMethodNoArgs()) .thenAnswer(AdditionalAnswers.returnsElementsOf(list)); // then assertEquals(1, mock.objectReturningMethodNoArgs()); assertEquals(2, mock.objectReturningMethodNoArgs()); assertEquals(3, mock.objectReturningMethodNoArgs()); // last element is returned continuously assertEquals(3, mock.objectReturningMethodNoArgs()); assertEquals(3, mock.objectReturningMethodNoArgs()); } @Test public void shouldReturnNullIfNecessary() throws Exception { // when List<Integer> list = asList(1, null); when(mock.objectReturningMethodNoArgs()) .thenAnswer(AdditionalAnswers.returnsElementsOf(list)); // then assertEquals(1, mock.objectReturningMethodNoArgs()); assertEquals(null, mock.objectReturningMethodNoArgs()); assertEquals(null, mock.objectReturningMethodNoArgs()); } @Test public void shouldScreamWhenNullPassed() throws Exception { try { // when AdditionalAnswers.returnsElementsOf(null); // then fail(); } catch (MockitoException e) { } } }
StubbingWithExtraAnswersTest
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/test/java/org/springframework/security/oauth2/server/authorization/web/authentication/OAuth2AccessTokenResponseAuthenticationSuccessHandlerTests.java
{ "start": 2805, "end": 9120 }
class ____ { private final RegisteredClient registeredClient = TestRegisteredClients.registeredClient().build(); private final HttpMessageConverter<OAuth2AccessTokenResponse> accessTokenHttpResponseConverter = new OAuth2AccessTokenResponseHttpMessageConverter(); private final OAuth2ClientAuthenticationToken clientPrincipal = new OAuth2ClientAuthenticationToken( this.registeredClient, ClientAuthenticationMethod.CLIENT_SECRET_BASIC, this.registeredClient.getClientSecret()); private final OAuth2AccessTokenResponseAuthenticationSuccessHandler authenticationSuccessHandler = new OAuth2AccessTokenResponseAuthenticationSuccessHandler(); @Test public void setAccessTokenResponseCustomizerWhenNullThenThrowIllegalArgumentException() { // @formatter:off assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> this.authenticationSuccessHandler.setAccessTokenResponseCustomizer(null)) .withMessage("accessTokenResponseCustomizer cannot be null"); // @formatter:on } @Test public void onAuthenticationSuccessWhenAuthenticationProvidedThenAccessTokenResponse() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(this.registeredClient).build(); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken(); Map<String, Object> additionalParameters = Collections.singletonMap("param1", "value1"); Authentication authentication = new OAuth2AccessTokenAuthenticationToken(this.registeredClient, this.clientPrincipal, accessToken, refreshToken, additionalParameters); this.authenticationSuccessHandler.onAuthenticationSuccess(request, response, authentication); OAuth2AccessTokenResponse accessTokenResponse = readAccessTokenResponse(response); assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo(accessToken.getTokenValue()); assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(accessToken.getTokenType()); assertThat(accessTokenResponse.getAccessToken().getIssuedAt()) .isBetween(accessToken.getIssuedAt().minusSeconds(1), accessToken.getIssuedAt().plusSeconds(1)); assertThat(accessTokenResponse.getAccessToken().getExpiresAt()) .isBetween(accessToken.getExpiresAt().minusSeconds(1), accessToken.getExpiresAt().plusSeconds(1)); assertThat(accessTokenResponse.getRefreshToken()).isNotNull(); assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo(refreshToken.getTokenValue()); assertThat(accessTokenResponse.getAdditionalParameters()) .containsExactlyInAnyOrderEntriesOf(Map.of("param1", "value1")); } @Test public void onAuthenticationSuccessWhenInvalidAuthenticationTypeThenThrowOAuth2AuthenticationException() { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); assertThatExceptionOfType(OAuth2AuthenticationException.class) .isThrownBy(() -> this.authenticationSuccessHandler.onAuthenticationSuccess(request, response, new TestingAuthenticationToken(this.clientPrincipal, null))) .extracting(OAuth2AuthenticationException::getError) .extracting("errorCode") .isEqualTo(OAuth2ErrorCodes.SERVER_ERROR); } @Test public void onAuthenticationSuccessWhenAccessTokenResponseCustomizerSetThenAccessTokenResponseCustomized() throws Exception { MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); OAuth2Authorization authorization = TestOAuth2Authorizations.authorization(this.registeredClient).build(); OAuth2AccessToken accessToken = authorization.getAccessToken().getToken(); OAuth2RefreshToken refreshToken = authorization.getRefreshToken().getToken(); Map<String, Object> additionalParameters = Collections.singletonMap("param1", "value1"); Authentication authentication = new OAuth2AccessTokenAuthenticationToken(this.registeredClient, this.clientPrincipal, accessToken, refreshToken, additionalParameters); Consumer<OAuth2AccessTokenAuthenticationContext> accessTokenResponseCustomizer = (authenticationContext) -> { OAuth2AccessTokenAuthenticationToken accessTokenAuthentication = authenticationContext.getAuthentication(); Map<String, Object> additionalParams = new HashMap<>(accessTokenAuthentication.getAdditionalParameters()); additionalParams.put("authorization_id", authorization.getId()); authenticationContext.getAccessTokenResponse().additionalParameters(additionalParams); }; this.authenticationSuccessHandler.setAccessTokenResponseCustomizer(accessTokenResponseCustomizer); this.authenticationSuccessHandler.onAuthenticationSuccess(request, response, authentication); OAuth2AccessTokenResponse accessTokenResponse = readAccessTokenResponse(response); assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo(accessToken.getTokenValue()); assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(accessToken.getTokenType()); assertThat(accessTokenResponse.getAccessToken().getIssuedAt()) .isBetween(accessToken.getIssuedAt().minusSeconds(1), accessToken.getIssuedAt().plusSeconds(1)); assertThat(accessTokenResponse.getAccessToken().getExpiresAt()) .isBetween(accessToken.getExpiresAt().minusSeconds(1), accessToken.getExpiresAt().plusSeconds(1)); assertThat(accessTokenResponse.getRefreshToken()).isNotNull(); assertThat(accessTokenResponse.getRefreshToken().getTokenValue()).isEqualTo(refreshToken.getTokenValue()); assertThat(accessTokenResponse.getAdditionalParameters()) .containsExactlyInAnyOrderEntriesOf(Map.of("param1", "value1", "authorization_id", "id")); } private OAuth2AccessTokenResponse readAccessTokenResponse(MockHttpServletResponse response) throws Exception { MockClientHttpResponse httpResponse = new MockClientHttpResponse(response.getContentAsByteArray(), HttpStatus.valueOf(response.getStatus())); return this.accessTokenHttpResponseConverter.read(OAuth2AccessTokenResponse.class, httpResponse); } }
OAuth2AccessTokenResponseAuthenticationSuccessHandlerTests
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/discovery/DiscoverySelectors.java
{ "start": 37128, "end": 37326 }
class ____ and its enclosing * classes' names. * * @param enclosingClassNames the names of the enclosing classes; never {@code null} or empty * @param nestedClassName the name of the nested
name
java
apache__flink
flink-metrics/flink-metrics-statsd/src/main/java/org/apache/flink/metrics/statsd/StatsDReporterFactory.java
{ "start": 1114, "end": 1309 }
class ____ implements MetricReporterFactory { @Override public MetricReporter createMetricReporter(Properties properties) { return new StatsDReporter(); } }
StatsDReporterFactory
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/stream/StreamExecDeduplicate.java
{ "start": 5483, "end": 12560 }
class ____ extends ExecNodeBase<RowData> implements StreamExecNode<RowData>, SingleTransformationTranslator<RowData> { public static final String DEDUPLICATE_TRANSFORMATION = "deduplicate"; public static final String FIELD_NAME_UNIQUE_KEYS = "uniqueKeys"; public static final String FIELD_NAME_IS_ROWTIME = "isRowtime"; public static final String FIELD_NAME_KEEP_LAST_ROW = "keepLastRow"; public static final String FIELD_NAME_GENERATE_UPDATE_BEFORE = "generateUpdateBefore"; public static final String STATE_NAME = "deduplicateState"; public static final String FIELD_NAME_OUTPUT_INSERT_ONLY = "outputInsertOnly"; @JsonProperty(FIELD_NAME_UNIQUE_KEYS) private final int[] uniqueKeys; @JsonProperty(FIELD_NAME_IS_ROWTIME) private final boolean isRowtime; @JsonProperty(FIELD_NAME_KEEP_LAST_ROW) private final boolean keepLastRow; @JsonProperty(FIELD_NAME_GENERATE_UPDATE_BEFORE) private final boolean generateUpdateBefore; @Nullable @JsonProperty(FIELD_NAME_STATE) @JsonInclude(JsonInclude.Include.NON_NULL) private final List<StateMetadata> stateMetadataList; /** * For backward compatibility, if plan was generated without insert-only requirement, insertOnly * will be absent in the json (null) and we interpret that as false to use old code path and * avoid a problematic migration from {@link RowTimeDeduplicateFunction} to {@link * RowTimeDeduplicateKeepFirstRowFunction}. */ @Nullable @JsonProperty(FIELD_NAME_OUTPUT_INSERT_ONLY) @JsonInclude(JsonInclude.Include.NON_NULL) private final Boolean outputInsertOnly; public StreamExecDeduplicate( ReadableConfig tableConfig, int[] uniqueKeys, boolean isRowtime, boolean keepLastRow, boolean outputInsertOnly, boolean generateUpdateBefore, InputProperty inputProperty, RowType outputType, String description) { this( ExecNodeContext.newNodeId(), ExecNodeContext.newContext(StreamExecDeduplicate.class), ExecNodeContext.newPersistedConfig(StreamExecDeduplicate.class, tableConfig), uniqueKeys, isRowtime, keepLastRow, outputInsertOnly, generateUpdateBefore, StateMetadata.getOneInputOperatorDefaultMeta(tableConfig, STATE_NAME), Collections.singletonList(inputProperty), outputType, description); } @JsonCreator public StreamExecDeduplicate( @JsonProperty(FIELD_NAME_ID) int id, @JsonProperty(FIELD_NAME_TYPE) ExecNodeContext context, @JsonProperty(FIELD_NAME_CONFIGURATION) ReadableConfig persistedConfig, @JsonProperty(FIELD_NAME_UNIQUE_KEYS) int[] uniqueKeys, @JsonProperty(FIELD_NAME_IS_ROWTIME) boolean isRowtime, @JsonProperty(FIELD_NAME_KEEP_LAST_ROW) boolean keepLastRow, @Nullable @JsonProperty(FIELD_NAME_OUTPUT_INSERT_ONLY) Boolean outputInsertOnly, @JsonProperty(FIELD_NAME_GENERATE_UPDATE_BEFORE) boolean generateUpdateBefore, @Nullable @JsonProperty(FIELD_NAME_STATE) List<StateMetadata> stateMetadataList, @JsonProperty(FIELD_NAME_INPUT_PROPERTIES) List<InputProperty> inputProperties, @JsonProperty(FIELD_NAME_OUTPUT_TYPE) RowType outputType, @JsonProperty(FIELD_NAME_DESCRIPTION) String description) { super(id, context, persistedConfig, inputProperties, outputType, description); checkArgument(inputProperties.size() == 1); this.uniqueKeys = checkNotNull(uniqueKeys); this.isRowtime = isRowtime; this.keepLastRow = keepLastRow; this.outputInsertOnly = outputInsertOnly == null ? false : outputInsertOnly; this.generateUpdateBefore = generateUpdateBefore; this.stateMetadataList = stateMetadataList; } @SuppressWarnings("unchecked") @Override protected Transformation<RowData> translateToPlanInternal( PlannerBase planner, ExecNodeConfig config) { final ExecEdge inputEdge = getInputEdges().get(0); final Transformation<RowData> inputTransform = (Transformation<RowData>) inputEdge.translateToPlan(planner); final RowType inputRowType = (RowType) inputEdge.getOutputType(); final InternalTypeInfo<RowData> rowTypeInfo = (InternalTypeInfo<RowData>) inputTransform.getOutputType(); final TypeSerializer<RowData> rowSerializer = rowTypeInfo.createSerializer( planner.getExecEnv().getConfig().getSerializerConfig()); final OneInputStreamOperator<RowData, RowData> operator; long stateRetentionTime = StateMetadata.getStateTtlForOneInputOperator(config, stateMetadataList); if (isRowtime) { operator = new RowtimeDeduplicateOperatorTranslator( config, rowTypeInfo, rowSerializer, inputRowType, keepLastRow, outputInsertOnly, generateUpdateBefore, stateRetentionTime) .createDeduplicateOperator(); } else { operator = new ProcTimeDeduplicateOperatorTranslator( config, planner.getFlinkContext().getClassLoader(), rowTypeInfo, rowSerializer, inputRowType, keepLastRow, outputInsertOnly, generateUpdateBefore, stateRetentionTime) .createDeduplicateOperator(); } final OneInputTransformation<RowData, RowData> transform = ExecNodeUtil.createOneInputTransformation( inputTransform, createTransformationMeta(DEDUPLICATE_TRANSFORMATION, config), operator, rowTypeInfo, inputTransform.getParallelism(), false); final RowDataKeySelector selector = KeySelectorUtil.getRowDataSelector( planner.getFlinkContext().getClassLoader(), uniqueKeys, rowTypeInfo); transform.setStateKeySelector(selector); transform.setStateKeyType(selector.getProducedType()); return transform; } /** Base translator to create deduplicate operator. */ private abstract static
StreamExecDeduplicate
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/scenario/RelaxedTimeoutConfigurationTest.java
{ "start": 13604, "end": 31635 }
class ____ { private final int normalTimeoutCount; private final int relaxedTimeoutCount; private final int successCount; private final int totalCommands; public BlpopTrafficResult(int normalTimeoutCount, int relaxedTimeoutCount, int successCount, int totalCommands) { this.normalTimeoutCount = normalTimeoutCount; this.relaxedTimeoutCount = relaxedTimeoutCount; this.successCount = successCount; this.totalCommands = totalCommands; } public int getNormalTimeoutCount() { return normalTimeoutCount; } public int getRelaxedTimeoutCount() { return relaxedTimeoutCount; } public int getSuccessCount() { return successCount; } public int getTotalCommands() { return totalCommands; } } private BlpopTrafficResult sendBlpopTraffic(TimeoutTestContext context, String keyPrefix, int commandCount) { log.info("Sending {} BLPOP commands with key prefix: {}", commandCount, keyPrefix); int normalTimeoutCount = 0; int relaxedTimeoutCount = 0; int successCount = 0; for (int i = 0; i < commandCount; i++) { StatefulRedisConnection<String, String> connection = context.capture.getMainConnection(); if (connection == null || !connection.isOpen()) { log.warn("Connection closed during BLPOP traffic, stopping at command #{}", i); break; } long startTime = System.currentTimeMillis(); try { RedisFuture<KeyValue<String, String>> future = connection.async().blpop(BLPOP_TIMEOUT.getSeconds(), keyPrefix + i); future.get(); long duration = System.currentTimeMillis() - startTime; log.info("BLPOP command #{} completed successfully in {}ms", i, duration); successCount++; } catch (Exception e) { long wallClockDuration = System.currentTimeMillis() - startTime; String timeoutDurationStr = extractTimeoutDuration(e); log.info("BLPOP command #{} timed out - Wall clock: {}ms, Actual timeout: {}ms", i, wallClockDuration, timeoutDurationStr); if (!"unknown".equals(timeoutDurationStr)) { int timeoutDuration = Integer.parseInt(timeoutDurationStr); if (timeoutDuration <= NORMAL_COMMAND_TIMEOUT.toMillis()) { log.info("Normal timeout detected: {}ms", timeoutDuration); normalTimeoutCount++; } else if (timeoutDuration > NORMAL_COMMAND_TIMEOUT.toMillis() && timeoutDuration <= EFFECTIVE_TIMEOUT_DURING_MAINTENANCE.toMillis()) { log.info("Relaxed timeout detected: {}ms", timeoutDuration); relaxedTimeoutCount++; } } } } return new BlpopTrafficResult(normalTimeoutCount, relaxedTimeoutCount, successCount, commandCount); } private void checkTimeouts(BlpopTrafficResult result, TimeoutExpectation expectation, String phase) { log.info("=== {} Timeout Check Results ===", phase); log.info("Total commands sent: {}", result.getTotalCommands()); log.info("Successful operations: {}", result.getSuccessCount()); log.info("Normal timeouts detected: {}", result.getNormalTimeoutCount()); log.info("Relaxed timeouts detected: {}", result.getRelaxedTimeoutCount()); if (expectation == TimeoutExpectation.RELAXED) { assertThat(result.getRelaxedTimeoutCount()).as( "During {} phase, should have detected at least one relaxed timeout. " + "No relaxed timeouts detected indicates the timeout relaxation mechanism is not working properly.", phase).isEqualTo(result.getTotalCommands()); assertThat(result.getNormalTimeoutCount()).as( "During {} phase, NO commands should fail with normal timeout. " + "Found {} normal timeouts. " + "Any normal timeouts indicate the timeout relaxation mechanism is not working properly.", phase, result.getNormalTimeoutCount()).isEqualTo(0); } else { assertThat(result.getNormalTimeoutCount()).as("After {} phase, ALL commands should fail with normal timeout. " + "Found {} normal timeouts out of {} total commands. " + "Mixed timeout behavior indicates the timeout un-relaxation mechanism is not working properly.", phase, result.getNormalTimeoutCount(), result.getTotalCommands()).isEqualTo(result.getTotalCommands()); assertThat(result.getRelaxedTimeoutCount()).as( "After {} phase, NO commands should fail with relaxed timeout. " + "Found {} relaxed timeouts out of {} total commands. " + "Any relaxed timeouts indicate the timeout un-relaxation mechanism is not working properly.", phase, result.getRelaxedTimeoutCount(), result.getTotalCommands()).isEqualTo(0); } } private void verifyConnectionAndStack(String context) { log.info("Verifying connection and stack state: {}...", context); try { if (mainConnection != null && mainConnection.isOpen()) { ConnectionTestUtil.verifyConnectionAndStackState(mainConnection, context); } else { log.warn("mainConnection is null or closed - cannot verify stack"); } } catch (Exception e) { log.warn("Failed to verify connection and stack {}: {} - {}", context, e.getClass().getSimpleName(), e.getMessage()); } } public void recordRelaxedTimeout() { timeoutCount.incrementAndGet(); } public void recordNormalTimeoutDuringMaintenance() { normalTimeoutsDuringMaintenance.incrementAndGet(); } public void recordSuccess() { successCount.incrementAndGet(); } public boolean isMaintenanceActive() { return maintenanceActive.get(); } public int getTimeoutCount() { return timeoutCount.get(); } public int getNormalTimeoutsDuringMaintenance() { return normalTimeoutsDuringMaintenance.get(); } public int getSuccessCount() { return successCount.get(); } public boolean waitForMigrationNotifications(Duration timeout) throws InterruptedException { return migrationLatch.await(timeout.toMillis(), TimeUnit.MILLISECONDS); } public boolean waitForFailoverNotifications(Duration timeout) throws InterruptedException { return failoverLatch.await(timeout.toMillis(), TimeUnit.MILLISECONDS); } public List<String> getReceivedNotifications() { return receivedNotifications; } public String getLastNotification() { return lastNotification.get(); } public void recordMovingStart() { movingStartTime.set(System.currentTimeMillis()); log.info("MOVING operation started at {}", movingStartTime.get()); } public void recordMovingEnd() { movingEndTime.set(System.currentTimeMillis()); long duration = movingEndTime.get() - movingStartTime.get(); log.info("MOVING operation completed at {} - Total duration: {}ms", movingEndTime.get(), duration); } public long getMovingDuration() { if (movingStartTime.get() > 0 && movingEndTime.get() > 0) { return movingEndTime.get() - movingStartTime.get(); } return -1; } public void endTestPhase() { testPhaseActive.set(false); log.info("Test phase ended - notifications will be ignored during cleanup"); } private void testUnrelaxedTimeoutsAfterMigrated(TimeoutTestContext context) throws InterruptedException { log.info("Testing unrelaxed timeouts after MIGRATED notification..."); log.info("Waiting for grace period ({}ms) to allow timeout un-relaxation to take effect...", 2 * RELAXED_TIMEOUT_ADDITION.toMillis()); Thread.sleep(2 * RELAXED_TIMEOUT_ADDITION.toMillis()); // Wait for grace period + 100ms buffer log.info("Grace period expired, starting traffic to verify unrelaxed timeouts..."); BlpopTrafficResult result = sendBlpopTraffic(context, "migrated-test-key-", TEST_COMMAND_COUNT); checkTimeouts(result, TimeoutExpectation.UNRELAXED, "MIGRATED"); } public void throwIfAssertionFailed() { AssertionError error = assertionFailure.get(); if (error != null) { throw error; } } } private TimeoutTestContext setupTimeoutTestForMovingUnrelaxed() { return setupTimeoutTestWithType(true, true); } private TimeoutTestContext setupTimeoutTestForUnrelaxed() { return setupTimeoutTestWithType(false, true); } private TimeoutTestContext setupTimeoutTestWithType(boolean isMovingTest, boolean isUnrelaxedTest) { RedisURI uri = RedisURI.builder(RedisURI.create(mStandard.getEndpoints().get(0))) .withAuthentication(mStandard.getUsername(), mStandard.getPassword()).withTimeout(Duration.ofSeconds(5)) .build(); RedisClient client = RedisClient.create(uri); TimeoutOptions timeoutOptions = TimeoutOptions.builder().timeoutCommands().fixedTimeout(NORMAL_COMMAND_TIMEOUT) .relaxedTimeoutsDuringMaintenance(RELAXED_TIMEOUT_ADDITION).build(); ClientOptions options = ClientOptions.builder().autoReconnect(true).protocolVersion(ProtocolVersion.RESP3) .maintNotificationsConfig(MaintNotificationsConfig.enabled(EndpointType.EXTERNAL_IP)) .timeoutOptions(timeoutOptions).build(); client.setOptions(options); StatefulRedisConnection<String, String> connection = client.connect(); TimeoutCapture capture = new TimeoutCapture(isMovingTest, isUnrelaxedTest); capture.setMainConnection(connection); log.info("*** TIMEOUT TEST SETUP: Test method detected as isMovingTest={} ***", isMovingTest); try { connection.sync().ping(); log.info("Initial PING successful - connection established"); } catch (Exception e) { log.warn("Initial PING failed: {}", e.getMessage()); } MaintenancePushNotificationMonitor.setupMonitoring(connection, capture); String bdbId = String.valueOf(mStandard.getBdbId()); TimeoutTestContext context = new TimeoutTestContext(client, connection, capture, bdbId); capture.setTestContext(context); return context; } private void cleanupTimeoutTest(TimeoutTestContext context) { context.connection.close(); context.client.shutdown(); } @Test @DisplayName("Comprehensive MOVING timeout test - Tests complete 4-phase sequence: relaxed during MIGRATING, unrelaxed after MIGRATED, relaxed during MOVING, unrelaxed after MOVING") public void timeoutUnrelaxedOnMovingTest() throws InterruptedException { log.info("test timeoutUnrelaxedOnMovingTest started"); TimeoutTestContext context = setupTimeoutTestForMovingUnrelaxed(); try { log.info("=== MOVING Un-relaxed Timeout Test: Starting maintenance operation ==="); String endpointId = clusterConfig.getFirstEndpointId(); String policy = "single"; log.info("Starting maintenance operation (migrate + rebind) with endpoint-aware node selection..."); log.info("Starting MOVING operation with endpoint-aware node selection and waiting for it to complete..."); Boolean operationResult = faultClient.triggerMovingNotification(context.bdbId, endpointId, policy, clusterConfig) .block(Duration.ofMinutes(3)); assertThat(operationResult).isTrue(); log.info("MOVING operation fully completed: {}", operationResult); // Wait for migration notifications (3 expected: MIGRATING + MIGRATED + MOVING) boolean migrationReceived = context.capture.waitForMigrationNotifications(Duration.ofMinutes(1)); assertThat(migrationReceived).as("Should receive migration notifications").isTrue(); log.info("Verifying we received the expected notifications..."); log.info("Received notifications: {}", context.capture.getReceivedNotifications()); assertThat(context.capture.getReceivedNotifications().stream().anyMatch(n -> n.contains("MIGRATED"))).isTrue(); assertThat(context.capture.getReceivedNotifications().stream().anyMatch(n -> n.contains("MOVING"))).isTrue(); context.capture.recordMovingEnd(); log.info("=== MOVING Un-relaxed Test: Testing normal timeouts after MOVING ==="); log.info("Testing normal timeouts after MOVING notification and reconnection..."); log.info("Connection status before timeout tests: {}", context.connection.isOpen()); TimeoutCapture.BlpopTrafficResult result = context.capture.sendBlpopTraffic(context, "moving-normal-test-key-", TEST_COMMAND_COUNT); context.capture.checkTimeouts(result, TimeoutCapture.TimeoutExpectation.UNRELAXED, "MOVING"); log.info("=== MOVING Un-relaxed Test Results ==="); log.info("MOVING operation duration: {}ms", context.capture.getMovingDuration()); log.info("Notifications received: {}", context.capture.getReceivedNotifications().size()); // Check if any assertions failed in background threads context.capture.throwIfAssertionFailed(); } finally { context.capture.endTestPhase(); cleanupTimeoutTest(context); } log.info("test timeoutUnrelaxedOnMovingTest ended"); } @Test @DisplayName("Comprehensive failover timeout test - Tests relaxed during FAILING_OVER and unrelaxed after FAILED_OVER") public void timeoutUnrelaxedOnFailedoverTest() throws InterruptedException { log.info("test timeoutUnrelaxedOnFailedoverTest started"); TimeoutTestContext context = setupTimeoutTestForUnrelaxed(); String nodeId = clusterConfig.getNodeWithMasterShards(); try { log.info("=== FAILED_OVER Un-relaxed Timeout Test: Starting maintenance operation ==="); log.info("Triggering shard failover for FAILED_OVER notification asynchronously..."); Boolean failoverResult = faultClient.triggerShardFailover(context.bdbId, nodeId, clusterConfig) .block(Duration.ofMinutes(3)); assertThat(failoverResult).isTrue(); log.info("FAILED_OVER operation completed: {}", failoverResult); // Wait for failover notifications (2 expected: FAILING_OVER + FAILED_OVER) boolean failoverReceived = context.capture.waitForFailoverNotifications(Duration.ofMinutes(1)); assertThat(failoverReceived).as("Should receive failover notifications").isTrue(); assertThat(context.capture.getReceivedNotifications().stream().anyMatch(n -> n.contains("FAILED_OVER"))).isTrue(); log.info("=== FAILED_OVER Un-relaxed Test: Testing normal timeouts after FAILED_OVER ==="); log.info("Testing that timeouts are back to normal after FAILED_OVER notification..."); log.info("Waiting for grace period ({}ms) to allow timeout un-relaxation to take effect...", 2 * RELAXED_TIMEOUT_ADDITION.toMillis()); Thread.sleep(2 * RELAXED_TIMEOUT_ADDITION.toMillis()); // Wait for grace period + 100ms buffer log.info("Grace period expired, starting traffic to verify unrelaxed timeouts..."); TimeoutCapture.BlpopTrafficResult result = context.capture.sendBlpopTraffic(context, "normal-test-key-", TEST_COMMAND_COUNT); context.capture.checkTimeouts(result, TimeoutCapture.TimeoutExpectation.UNRELAXED, "failedover completion"); log.info("=== FAILED_OVER Un-relaxed Test Results ==="); log.info("Notifications received: {}", context.capture.getReceivedNotifications().size()); // Check if any assertions failed in background threads context.capture.throwIfAssertionFailed(); } finally { context.capture.endTestPhase(); clusterConfig = RedisEnterpriseConfig.refreshClusterConfig(faultClient, String.valueOf(mStandard.getBdbId())); nodeId = clusterConfig.getNodeWithMasterShards(); log.info("performing cluster cleanup operation for failover testing"); StepVerifier.create(faultClient.triggerShardFailover(context.bdbId, nodeId, clusterConfig)).expectNext(true) .expectComplete().verify(LONG_OPERATION_TIMEOUT); cleanupTimeoutTest(context); } log.info("test timeoutUnrelaxedOnFailedoverTest ended"); } }
BlpopTrafficResult
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ClassNameTest.java
{ "start": 2464, "end": 2684 }
class ____ {} """) .doTest(); } @Test public void negativeInnerClass() { compilationHelper .addSourceLines( "b/B.java", """ package b;
C
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/support/ManagedMap.java
{ "start": 1213, "end": 2653 }
class ____<K, V> extends LinkedHashMap<K, V> implements Mergeable, BeanMetadataElement { private @Nullable Object source; private @Nullable String keyTypeName; private @Nullable String valueTypeName; private boolean mergeEnabled; public ManagedMap() { } public ManagedMap(int initialCapacity) { super(initialCapacity); } /** * Return a new instance containing keys and values extracted from the * given entries. The entries themselves are not stored in the map. * @param entries {@code Map.Entry}s containing the keys and values * from which the map is populated * @param <K> the {@code Map}'s key type * @param <V> the {@code Map}'s value type * @return a {@code Map} containing the specified mappings * @since 5.3.16 */ @SafeVarargs @SuppressWarnings("unchecked") public static <K,V> ManagedMap<K,V> ofEntries(Entry<? extends K, ? extends V>... entries) { ManagedMap<K,V > map = new ManagedMap<>(); for (Entry<? extends K, ? extends V> entry : entries) { map.put(entry.getKey(), entry.getValue()); } return map; } /** * Set the configuration source {@code Object} for this metadata element. * <p>The exact type of the object will depend on the configuration mechanism used. */ public void setSource(@Nullable Object source) { this.source = source; } @Override public @Nullable Object getSource() { return this.source; } /** * Set the default key type name (
ManagedMap
java
google__guava
android/guava-tests/test/com/google/common/collect/OrderingTest.java
{ "start": 38283, "end": 42460 }
enum ____ { REVERSE { @Override <T extends @Nullable Object> Scenario<?> mutate(Scenario<T> scenario) { List<T> newList = new ArrayList<>(scenario.strictlyOrderedList); Collections.reverse(newList); return new Scenario<T>(scenario.ordering.reverse(), newList, scenario.emptyArray); } }, NULLS_FIRST { @Override <T extends @Nullable Object> Scenario<?> mutate(Scenario<T> scenario) { List<T> newList = Lists.newArrayList((T) null); for (T t : scenario.strictlyOrderedList) { if (t != null) { newList.add(t); } } return new Scenario<T>(scenario.ordering.nullsFirst(), newList, scenario.emptyArray); } }, NULLS_LAST { @Override <T extends @Nullable Object> Scenario<?> mutate(Scenario<T> scenario) { List<T> newList = new ArrayList<>(); for (T t : scenario.strictlyOrderedList) { if (t != null) { newList.add(t); } } newList.add(null); return new Scenario<T>(scenario.ordering.nullsLast(), newList, scenario.emptyArray); } }, ON_RESULT_OF { @Override <T extends @Nullable Object> Scenario<?> mutate(Scenario<T> scenario) { Ordering<Integer> ordering = scenario.ordering.onResultOf( new Function<Integer, T>() { @Override public T apply(Integer from) { return scenario.strictlyOrderedList.get(from); } }); List<Integer> list = new ArrayList<>(); for (int i = 0; i < scenario.strictlyOrderedList.size(); i++) { list.add(i); } return new Scenario<>(ordering, list, new Integer[0]); } }, COMPOUND_THIS_WITH_NATURAL { @SuppressWarnings("unchecked") // generic arrays @Override <T extends @Nullable Object> Scenario<?> mutate(Scenario<T> scenario) { List<Composite<T>> composites = new ArrayList<>(); for (T t : scenario.strictlyOrderedList) { composites.add(new Composite<T>(t, 1)); composites.add(new Composite<T>(t, 2)); } Ordering<Composite<T>> ordering = scenario .ordering .onResultOf(Composite.<T>getValueFunction()) .compound(Ordering.natural()); return new Scenario<Composite<T>>( ordering, composites, (Composite<T>[]) new Composite<?>[0]); } }, COMPOUND_NATURAL_WITH_THIS { @SuppressWarnings("unchecked") // generic arrays @Override <T extends @Nullable Object> Scenario<?> mutate(Scenario<T> scenario) { List<Composite<T>> composites = new ArrayList<>(); for (T t : scenario.strictlyOrderedList) { composites.add(new Composite<T>(t, 1)); } for (T t : scenario.strictlyOrderedList) { composites.add(new Composite<T>(t, 2)); } Ordering<Composite<T>> ordering = Ordering.<Composite<T>>natural() .compound(scenario.ordering.onResultOf(Composite.<T>getValueFunction())); return new Scenario<Composite<T>>( ordering, composites, (Composite<T>[]) new Composite<?>[0]); } }, LEXICOGRAPHICAL { @SuppressWarnings("unchecked") // generic arrays @Override <T extends @Nullable Object> Scenario<?> mutate(Scenario<T> scenario) { List<Iterable<T>> words = new ArrayList<>(); words.add(Collections.<T>emptyList()); for (T t : scenario.strictlyOrderedList) { words.add(asList(t)); for (T s : scenario.strictlyOrderedList) { words.add(asList(t, s)); } } return new Scenario<Iterable<T>>( scenario.ordering.lexicographical(), words, (Iterable<T>[]) new Iterable<?>[0]); } }, ; abstract <T extends @Nullable Object> Scenario<?> mutate(Scenario<T> scenario); } /** * A dummy object we create so that we can have something meaningful to have a compound ordering * over. */ private static
OrderingMutation
java
apache__camel
components/camel-slack/src/main/java/org/apache/camel/component/slack/SlackEndpoint.java
{ "start": 1531, "end": 7499 }
class ____ extends ScheduledPollEndpoint { @UriParam(defaultValue = "" + SlackConsumer.DEFAULT_CONSUMER_DELAY, javaType = "java.time.Duration", label = "consumer,scheduler", description = "Milliseconds before the next poll.") private long delay = SlackConsumer.DEFAULT_CONSUMER_DELAY; @UriPath @Metadata(required = true) private String channel; @UriParam(label = "producer") private String webhookUrl; @UriParam(label = "producer", secret = true) @Deprecated private String username; @UriParam(label = "producer") @Deprecated private String iconUrl; @UriParam(label = "producer") @Deprecated private String iconEmoji; @UriParam(secret = true) private String token; @UriParam(label = "consumer", defaultValue = "10") private String maxResults = "10"; @UriParam(label = "consumer", defaultValue = "https://slack.com") private String serverUrl = "https://slack.com"; @UriParam(label = "consumer", defaultValue = "false", javaType = "boolean", description = "Create exchanges in natural order (oldest to newest) or not") private boolean naturalOrder; @UriParam(label = "consumer", enums = "PUBLIC_CHANNEL,PRIVATE_CHANNEL,MPIM,IM", defaultValue = "PUBLIC_CHANNEL", description = "Type of conversation") private ConversationType conversationType = ConversationType.PUBLIC_CHANNEL; /** * Constructor for SlackEndpoint * * @param uri the full component url * @param channelName the channel or username the message is directed at * @param component the component that was created */ public SlackEndpoint(String uri, String channelName, SlackComponent component) { super(uri, component); this.webhookUrl = component.getWebhookUrl(); this.token = component.getToken(); this.channel = channelName; // ScheduledPollConsumer default delay is 500 millis and that is too often for polling slack, // so we override with a new default value. End user can override this value by providing a delay parameter setDelay(SlackConsumer.DEFAULT_CONSUMER_DELAY); } @Override public Producer createProducer() throws Exception { if (ObjectHelper.isEmpty(token) && ObjectHelper.isEmpty(webhookUrl)) { throw new RuntimeCamelException( "Missing required endpoint configuration: token or webhookUrl must be defined for Slack producer"); } return new SlackProducer(this); } @Override public Consumer createConsumer(Processor processor) throws Exception { if (ObjectHelper.isEmpty(token)) { throw new RuntimeCamelException( "Missing required endpoint configuration: token must be defined for Slack consumer"); } if (ObjectHelper.isEmpty(channel)) { throw new RuntimeCamelException( "Missing required endpoint configuration: channel must be defined for Slack consumer"); } SlackConsumer consumer = new SlackConsumer(this, processor); configureConsumer(consumer); return consumer; } /** * The incoming webhook URL */ public void setWebhookUrl(String webhookUrl) { this.webhookUrl = webhookUrl; } public String getWebhookUrl() { return webhookUrl; } public String getChannel() { return channel; } /** * The channel name (syntax #name) or slack user (syntax @userName) to send a message directly to an user. */ public void setChannel(String channel) { this.channel = channel; } public String getUsername() { return username; } /** * This is the username that the bot will have when sending messages to a channel or user. */ public void setUsername(String username) { this.username = username; } public String getIconUrl() { return iconUrl; } /** * The avatar that the component will use when sending message to a channel or user. */ public void setIconUrl(String iconUrl) { this.iconUrl = iconUrl; } public String getIconEmoji() { return iconEmoji; } /** * Use a Slack emoji as an avatar */ public void setIconEmoji(String iconEmoji) { this.iconEmoji = iconEmoji; } public String getToken() { return token; } /** * The token to access Slack. This app needs to have channels:history, groups:history, im:history, mpim:history, * channels:read, groups:read, im:read and mpim:read permissions. The User OAuth Token is the kind of token needed. */ public void setToken(String token) { this.token = token; } public String getMaxResults() { return maxResults; } /** * The Max Result for the poll */ public void setMaxResults(String maxResult) { this.maxResults = maxResult; } public String getServerUrl() { return serverUrl; } /** * The Server URL of the Slack instance */ public void setServerUrl(String serverUrl) { this.serverUrl = serverUrl; } /** * Is consuming message in natural order */ public void setNaturalOrder(boolean naturalOrder) { this.naturalOrder = naturalOrder; } public boolean isNaturalOrder() { return naturalOrder; } /** * The type of the conversation */ public void setConversationType(ConversationType conversationType) { this.conversationType = conversationType; } public ConversationType getConversationType() { return conversationType; } /** * Milliseconds before the next poll. */ @Override public void setDelay(long delay) { super.setDelay(delay); this.delay = delay; } }
SlackEndpoint
java
apache__camel
components/camel-box/camel-box-component/src/generated/java/org/apache/camel/component/box/BoxTasksManagerEndpointConfiguration.java
{ "start": 2492, "end": 5864 }
class ____ extends BoxConfiguration { @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "addFileTask", description="The action the task assignee will be prompted to do")}) private com.box.sdk.BoxTask.Action action; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "addAssignmentToTask", description="The user to assign to task")}) private com.box.sdk.BoxUser assignTo; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "addFileTask", description="The day at which this task is due")}) private java.util.Date dueAt; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "addFileTask", description="The id of file to add task to"), @ApiMethod(methodName = "getFileTasks", description="The id of file")}) private String fileId; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "updateTaskInfo", description="The updated information")}) private com.box.sdk.BoxTask.Info info; @UriParam @ApiParam(optional = true, apiMethods = {@ApiMethod(methodName = "addFileTask", description="An optional message to include with the task")}) private String message; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "deleteTaskAssignment", description="The id of task assignment to delete"), @ApiMethod(methodName = "getTaskAssignmentInfo", description="The id of task assignment")}) private String taskAssignmentId; @UriParam @ApiParam(optional = false, apiMethods = {@ApiMethod(methodName = "addAssignmentToTask", description="The id of task to add assignment for"), @ApiMethod(methodName = "deleteTask", description="The id of task to delete"), @ApiMethod(methodName = "getTaskAssignments", description="The id of task"), @ApiMethod(methodName = "getTaskInfo", description="The id of task"), @ApiMethod(methodName = "updateTaskInfo", description="The id of task")}) private String taskId; public com.box.sdk.BoxTask.Action getAction() { return action; } public void setAction(com.box.sdk.BoxTask.Action action) { this.action = action; } public com.box.sdk.BoxUser getAssignTo() { return assignTo; } public void setAssignTo(com.box.sdk.BoxUser assignTo) { this.assignTo = assignTo; } public java.util.Date getDueAt() { return dueAt; } public void setDueAt(java.util.Date dueAt) { this.dueAt = dueAt; } public String getFileId() { return fileId; } public void setFileId(String fileId) { this.fileId = fileId; } public com.box.sdk.BoxTask.Info getInfo() { return info; } public void setInfo(com.box.sdk.BoxTask.Info info) { this.info = info; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getTaskAssignmentId() { return taskAssignmentId; } public void setTaskAssignmentId(String taskAssignmentId) { this.taskAssignmentId = taskAssignmentId; } public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } }
BoxTasksManagerEndpointConfiguration
java
apache__flink
flink-table/flink-table-common/src/main/java/org/apache/flink/table/catalog/CatalogPartitionSpec.java
{ "start": 1299, "end": 2409 }
class ____ { // An unmodifiable map as <partition key, value> private final Map<String, String> partitionSpec; public CatalogPartitionSpec(Map<String, String> partitionSpec) { checkNotNull(partitionSpec, "partitionSpec cannot be null"); this.partitionSpec = Collections.unmodifiableMap(partitionSpec); } /** * Get the partition spec as key-value map. * * @return a map of partition spec keys and values */ public Map<String, String> getPartitionSpec() { return partitionSpec; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CatalogPartitionSpec that = (CatalogPartitionSpec) o; return partitionSpec.equals(that.partitionSpec); } @Override public int hashCode() { return Objects.hash(partitionSpec); } @Override public String toString() { return "CatalogPartitionSpec{" + partitionSpec + '}'; } }
CatalogPartitionSpec
java
apache__camel
core/camel-core-xml/src/main/java/org/apache/camel/core/xml/PatternBasedPackageScanFilter.java
{ "start": 2811, "end": 3017 }
class ____ match one of the include patterns to * match the filter and return true. * <p> * If the filter contains only exclude filters, then the filter will return true unless the candidate
must
java
google__guava
android/guava/src/com/google/common/base/Defaults.java
{ "start": 859, "end": 1019 }
class ____ default values for all Java types, as defined by the JLS. * * @author Ben Yu * @since 1.0 */ @J2ktIncompatible @GwtIncompatible public final
provides
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/state/internals/PositionSerde.java
{ "start": 1140, "end": 4262 }
class ____ PositionSerde() { } public static Position deserialize(final ByteBuffer buffer) { final byte version = buffer.get(); switch (version) { case (byte) 0: // actual position, v0 final int nTopics = buffer.getInt(); final Map<String, Map<Integer, Long>> position = new HashMap<>(nTopics); for (int i = 0; i < nTopics; i++) { final int topicNameLength = buffer.getInt(); final byte[] topicNameBytes = new byte[topicNameLength]; buffer.get(topicNameBytes); final String topic = new String(topicNameBytes, StandardCharsets.UTF_8); final int numPairs = buffer.getInt(); final Map<Integer, Long> partitionOffsets = new HashMap<>(numPairs); for (int j = 0; j < numPairs; j++) { partitionOffsets.put(buffer.getInt(), buffer.getLong()); } position.put(topic, partitionOffsets); } return Position.fromMap(position); default: throw new IllegalArgumentException( "Unknown version " + version + " when deserializing Position" ); } } public static ByteBuffer serialize(final Position position) { final byte version = (byte) 0; int arraySize = Byte.SIZE; // version final int nTopics = position.getTopics().size(); arraySize += Integer.SIZE; final ArrayList<String> entries = new ArrayList<>(position.getTopics()); final byte[][] topics = new byte[entries.size()][]; for (int i = 0; i < nTopics; i++) { final String topic = entries.get(i); final byte[] topicBytes = topic.getBytes(StandardCharsets.UTF_8); topics[i] = topicBytes; arraySize += Integer.SIZE; // topic name length arraySize += topicBytes.length; // topic name itself final Map<Integer, Long> partitionOffsets = position.getPartitionPositions(topic); arraySize += Integer.SIZE; // Number of PartitionOffset pairs arraySize += (Integer.SIZE + Long.SIZE) * partitionOffsets.size(); // partitionOffsets themselves } final ByteBuffer buffer = ByteBuffer.allocate(arraySize); buffer.put(version); buffer.putInt(nTopics); for (int i = 0; i < nTopics; i++) { buffer.putInt(topics[i].length); buffer.put(topics[i]); final String topic = entries.get(i); final Map<Integer, Long> partitionOffsets = position.getPartitionPositions(topic); buffer.putInt(partitionOffsets.size()); for (final Entry<Integer, Long> partitionOffset : partitionOffsets.entrySet()) { buffer.putInt(partitionOffset.getKey()); buffer.putLong(partitionOffset.getValue()); } } buffer.flip(); return buffer; } }
public
java
apache__camel
components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaCloseEntityManagerOnCompletion.java
{ "start": 1018, "end": 1632 }
class ____ extends SynchronizationAdapter { private final EntityManager entityManager; public JpaCloseEntityManagerOnCompletion(EntityManager entityManager) { this.entityManager = entityManager; } @Override public void onDone(Exchange exchange) { try { if (entityManager.isOpen()) { entityManager.close(); } } catch (Exception e) { // ignore } } @Override public int getOrder() { // we want to run as last as possible return Ordered.LOWEST; } }
JpaCloseEntityManagerOnCompletion
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedMethodTest.java
{ "start": 12180, "end": 12453 }
class ____ { private Test() {} } """) .doTest(); } @Test public void unusedConstructor_finalFieldsLeftDangling_noFix() { refactoringHelper .addInputLines( "Test.java", """
Test
java
apache__camel
core/camel-core-model/src/main/java/org/apache/camel/model/RouteConfigurationContainer.java
{ "start": 1006, "end": 1426 }
interface ____ { /** * Returns the route configurations * * @return the route configurations */ @XmlElementRef List<RouteConfigurationDefinition> getRouteConfigurations(); /** * Sets the route configurations to use * * @param routes the route configurations */ void setRouteConfigurations(List<RouteConfigurationDefinition> routes); }
RouteConfigurationContainer
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/CooperativeStickyAssignor.java
{ "start": 2457, "end": 7441 }
class ____ extends AbstractStickyAssignor { public static final String COOPERATIVE_STICKY_ASSIGNOR_NAME = "cooperative-sticky"; // these schemas are used for preserving useful metadata for the assignment, such as the last stable generation private static final String GENERATION_KEY_NAME = "generation"; private static final Schema COOPERATIVE_STICKY_ASSIGNOR_USER_DATA_V0 = new Schema( new Field(GENERATION_KEY_NAME, Type.INT32)); private int generation = DEFAULT_GENERATION; // consumer group generation @Override public String name() { return COOPERATIVE_STICKY_ASSIGNOR_NAME; } @Override public List<RebalanceProtocol> supportedProtocols() { return Arrays.asList(RebalanceProtocol.COOPERATIVE, RebalanceProtocol.EAGER); } @Override public void onAssignment(Assignment assignment, ConsumerGroupMetadata metadata) { this.generation = metadata.generationId(); } @Override public ByteBuffer subscriptionUserData(Set<String> topics) { Struct struct = new Struct(COOPERATIVE_STICKY_ASSIGNOR_USER_DATA_V0); struct.set(GENERATION_KEY_NAME, generation); ByteBuffer buffer = ByteBuffer.allocate(COOPERATIVE_STICKY_ASSIGNOR_USER_DATA_V0.sizeOf(struct)); COOPERATIVE_STICKY_ASSIGNOR_USER_DATA_V0.write(buffer, struct); buffer.flip(); return buffer; } @Override protected MemberData memberData(Subscription subscription) { // In ConsumerProtocolSubscription v2 or higher, we can take member data from fields directly if (subscription.generationId().isPresent()) { return new MemberData(subscription.ownedPartitions(), subscription.generationId()); } ByteBuffer buffer = subscription.userData(); Optional<Integer> encodedGeneration; if (buffer == null) { encodedGeneration = Optional.empty(); } else { try { Struct struct = COOPERATIVE_STICKY_ASSIGNOR_USER_DATA_V0.read(buffer); encodedGeneration = Optional.of(struct.getInt(GENERATION_KEY_NAME)); } catch (Exception e) { encodedGeneration = Optional.of(DEFAULT_GENERATION); } } return new MemberData(subscription.ownedPartitions(), encodedGeneration, subscription.rackId()); } @Override public Map<String, List<TopicPartition>> assignPartitions(Map<String, List<PartitionInfo>> partitionsPerTopic, Map<String, Subscription> subscriptions) { Map<String, List<TopicPartition>> assignments = super.assignPartitions(partitionsPerTopic, subscriptions); Map<TopicPartition, String> partitionsTransferringOwnership = super.partitionsTransferringOwnership == null ? computePartitionsTransferringOwnership(subscriptions, assignments) : super.partitionsTransferringOwnership; adjustAssignment(assignments, partitionsTransferringOwnership); return assignments; } // Following the cooperative rebalancing protocol requires removing partitions that must first be revoked from the assignment private void adjustAssignment(Map<String, List<TopicPartition>> assignments, Map<TopicPartition, String> partitionsTransferringOwnership) { for (Map.Entry<TopicPartition, String> partitionEntry : partitionsTransferringOwnership.entrySet()) { assignments.get(partitionEntry.getValue()).remove(partitionEntry.getKey()); } } private Map<TopicPartition, String> computePartitionsTransferringOwnership(Map<String, Subscription> subscriptions, Map<String, List<TopicPartition>> assignments) { Map<TopicPartition, String> allAddedPartitions = new HashMap<>(); Set<TopicPartition> allRevokedPartitions = new HashSet<>(); for (final Map.Entry<String, List<TopicPartition>> entry : assignments.entrySet()) { String consumer = entry.getKey(); List<TopicPartition> ownedPartitions = subscriptions.get(consumer).ownedPartitions(); List<TopicPartition> assignedPartitions = entry.getValue(); Set<TopicPartition> ownedPartitionsSet = new HashSet<>(ownedPartitions); for (TopicPartition tp : assignedPartitions) { if (!ownedPartitionsSet.contains(tp)) allAddedPartitions.put(tp, consumer); } Set<TopicPartition> assignedPartitionsSet = new HashSet<>(assignedPartitions); for (TopicPartition tp : ownedPartitions) { if (!assignedPartitionsSet.contains(tp)) allRevokedPartitions.add(tp); } } allAddedPartitions.keySet().retainAll(allRevokedPartitions); return allAddedPartitions; } }
CooperativeStickyAssignor
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/sql/ast/spi/AbstractSqlAstTranslator.java
{ "start": 13147, "end": 36156 }
class ____<T extends JdbcOperation> implements SqlAstTranslator<T>, SqlAppender { /** * When emulating the recursive WITH clause subclauses SEARCH and CYCLE, * we need to build a string path and some databases like MySQL require that * we cast the expression to a char with certain size. * To estimate the size, we need to assume a certain max recursion depth. */ private static final int MAX_RECURSION_DEPTH_ESTIMATE = 1000; /* The following are size estimates for various temporal types */ private static final int DATE_CHAR_SIZE_ESTIMATE = // year 4 + // separator 1 + // month 2 + // separator 1 + // day 2; private static final int TIME_CHAR_SIZE_ESTIMATE = // hour 2 + // separator 1 + // minute 2 + // separator 1 + // second 2; private static final int TIMESTAMP_CHAR_SIZE_ESTIMATE = DATE_CHAR_SIZE_ESTIMATE + // separator 1 + TIME_CHAR_SIZE_ESTIMATE + // separator 1 + // nanos 9; private static final int OFFSET_TIMESTAMP_CHAR_SIZE_ESTIMATE = TIMESTAMP_CHAR_SIZE_ESTIMATE + // separator 1 + // zone offset 6; // pre-req state private final SessionFactoryImplementor sessionFactory; // In-flight state private final StringBuilder sqlBuffer = new StringBuilder(); private final List<JdbcParameterBinder> parameterBinders = new ArrayList<>(); private int[] parameterIdToBinderIndex; private JdbcParameterBindings jdbcParameterBindings; private Map<JdbcParameter, JdbcParameterBinding> appliedParameterBindings = Collections.emptyMap(); private SqlAstNodeRenderingMode parameterRenderingMode = SqlAstNodeRenderingMode.DEFAULT; private final ParameterMarkerStrategy parameterMarkerStrategy; private final Stack<Clause> clauseStack = new StandardStack<>(); private final Stack<QueryPart> queryPartStack = new StandardStack<>(); private final Stack<Statement> statementStack = new StandardStack<>(); /** * Used to identify the QuerySpec to which locking (for update, e.g.) should * be applied. Generally this will be the root QuerySpec, but, well, Oracle... */ private QuerySpec lockingTarget; private LockingClauseStrategy lockingClauseStrategy; private LockOptions lockOptions; private final Dialect dialect; private final Set<String> affectedTableNames = new HashSet<>(); private CteStatement currentCteStatement; private boolean needsSelectAliases; // Column aliases that need to be injected private List<String> columnAliases; private Predicate additionalWherePredicate; // We must reset the queryPartForRowNumbering fields to null if a query part is visited that does not // contribute to the row numbering i.e. if the query part is a sub-query in the where clause. // To determine whether a query part contributes to row numbering, we remember the clause depth // and when visiting a query part, compare the current clause depth against the remembered one. private QueryPart queryPartForRowNumbering; private int queryPartForRowNumberingClauseDepth = -1; private int queryPartForRowNumberingAliasCounter; private int queryGroupAliasCounter; // This field is used to remember the index of the most recently rendered top level with clause element in the sqlBuffer. // See #visitCteContainer for details about the usage. private int topLevelWithClauseIndex; // This field holds the index of where the "recursive" keyword should appear in the sqlBuffer. // See #visitCteContainer for details about the usage. private int withClauseRecursiveIndex = -1; private transient FunctionRenderer castFunction; private transient BasicType<Integer> integerType; private transient BasicType<String> stringType; private transient BasicType<Boolean> booleanType; private Limit limit; private JdbcParameter offsetParameter; private JdbcParameter limitParameter; protected AbstractSqlAstTranslator(SessionFactoryImplementor sessionFactory, Statement statement) { this.sessionFactory = sessionFactory; final JdbcServices jdbcServices = sessionFactory.getJdbcServices(); this.dialect = jdbcServices.getDialect(); this.statementStack.push( statement ); this.parameterMarkerStrategy = jdbcServices.getParameterMarkerStrategy(); if ( statement instanceof SelectStatement selectStatement ) { // ideally we'd only do this if there are LockOptions, // but we do not know that until later (#translate) unfortunately lockingTarget = selectStatement.getQuerySpec(); } } protected void setLockingTarget(QuerySpec querySpec) { lockingTarget = querySpec; } @Override public Statement getSqlAst() { return statementStack.getRoot(); } private static Clause matchWithClause(Clause clause) { if ( clause == Clause.WITH ) { return Clause.WITH; } return null; } public Dialect getDialect() { return dialect; } @Override public SessionFactoryImplementor getSessionFactory() { return sessionFactory; } protected FunctionRenderer castFunction() { if ( castFunction == null ) { castFunction = findSelfRenderingFunction( "cast", 2 ); } return castFunction; } protected WrapperOptions getWrapperOptions() { return sessionFactory.getWrapperOptions(); } public BasicType<Integer> getIntegerType() { if ( integerType == null ) { integerType = sessionFactory.getTypeConfiguration() .getBasicTypeRegistry() .resolve( StandardBasicTypes.INTEGER ); } return integerType; } public BasicType<String> getStringType() { if ( stringType == null ) { stringType = sessionFactory.getTypeConfiguration().getBasicTypeRegistry() .resolve( StandardBasicTypes.STRING ); } return stringType; } public BasicType<Boolean> getBooleanType() { if ( booleanType == null ) { booleanType = sessionFactory.getTypeConfiguration() .getBasicTypeRegistry() .resolve( StandardBasicTypes.BOOLEAN ); } return booleanType; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // for tests, for now public String getSql() { return sqlBuffer.toString(); } // For Blaze-Persistence until its function rendering code doesn't depend on SQL fragments anymore @Internal public StringBuilder getSqlBuffer() { return sqlBuffer; } protected void cleanup() { this.jdbcParameterBindings = null; this.lockOptions = null; this.limit = null; setLockingTarget( null ); setOffsetParameter( null ); setLimitParameter( null ); } public List<JdbcParameterBinder> getParameterBinders() { return parameterBinders; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @SuppressWarnings("unused") protected SqlAppender getSqlAppender() { return this; } @Override public Set<String> getAffectedTableNames() { return affectedTableNames; } @Override public void addAffectedTableName(String tableName) { affectedTableNames.add( tableName ); } protected Statement getStatement() { return statementStack.getRoot(); } public MutationStatement getCurrentDmlStatement() { return statementStack.findCurrentFirst( AbstractSqlAstTranslator::matchMutationStatement ); } private static MutationStatement matchMutationStatement(Statement stmt) { return stmt instanceof MutationStatement mutationStatement ? mutationStatement : null; } protected SqlAstNodeRenderingMode getParameterRenderingMode() { return parameterRenderingMode; } protected void addAdditionalWherePredicate(Predicate predicate) { additionalWherePredicate = Predicate.combinePredicates( additionalWherePredicate, predicate ); } public void prependSql(String fragment) { sqlBuffer.insert( 0, fragment ); } @Override public void appendSql(String fragment) { sqlBuffer.append( fragment ); } @Override public void appendSql(char fragment) { sqlBuffer.append( fragment ); } @Override public void appendSql(int value) { sqlBuffer.append( value ); } @Override public void appendSql(long value) { sqlBuffer.append( value ); } @Override public void appendSql(double value) { sqlBuffer.append( value ); } @Override public void appendSql(float value) { sqlBuffer.append( value ); } @Override public void appendSql(boolean value) { sqlBuffer.append( value ); } @Override public void appendDoubleQuoteEscapedString(String value) { QuotingHelper.appendDoubleQuoteEscapedString( sqlBuffer, value ); } @Override public void appendSingleQuoteEscapedString(String value) { QuotingHelper.appendSingleQuoteEscapedString( sqlBuffer, value ); } @Override public Appendable append(CharSequence csq) { sqlBuffer.append( csq ); return this; } @Override public Appendable append(CharSequence csq, int start, int end) { sqlBuffer.append( csq, start, end ); return this; } @Override public Appendable append(char c) { sqlBuffer.append( c ); return this; } protected JdbcServices getJdbcServices() { return getSessionFactory().getJdbcServices(); } protected void addAppliedParameterBinding(JdbcParameter parameter, JdbcParameterBinding binding) { if ( appliedParameterBindings.isEmpty() ) { appliedParameterBindings = new IdentityHashMap<>(); } if ( binding == null ) { appliedParameterBindings.put( parameter, null ); } else { final JdbcMapping bindType = binding.getBindType(); //noinspection unchecked final Object value = ( (JavaType<Object>) bindType.getJdbcJavaType() ) .getMutabilityPlan() .deepCopy( binding.getBindValue() ); appliedParameterBindings.put( parameter, new JdbcParameterBindingImpl( bindType, value ) ); } } protected Map<JdbcParameter, JdbcParameterBinding> getAppliedParameterBindings() { return appliedParameterBindings; } protected JdbcLockStrategy getJdbcLockStrategy() { return lockOptions == null ? JdbcLockStrategy.FOLLOW_ON : JdbcLockStrategy.NONE; } protected JdbcParameterBindings getJdbcParameterBindings() { return jdbcParameterBindings; } protected LockOptions getLockOptions() { return lockOptions; } protected Limit getLimit() { return limit; } protected boolean hasLimit() { return limit != null && !limit.isEmpty(); } protected boolean hasLimit(QueryPart queryPart) { return queryPart.isRoot() && hasLimit() && limit.getMaxRows() != null || queryPart.getFetchClauseExpression() != null; } protected boolean hasOffset(QueryPart queryPart) { return queryPart.isRoot() && hasLimit() && limit.getFirstRow() != null || queryPart.getOffsetClauseExpression() != null; } protected boolean useOffsetFetchClause(QueryPart queryPart) { return !queryPart.isRoot() || limit == null || limit.isEmpty(); } protected boolean isRowsOnlyFetchClauseType(QueryPart queryPart) { return queryPart.isRoot() && hasLimit() || queryPart.getFetchClauseType() == null || queryPart.getFetchClauseType() == FetchClauseType.ROWS_ONLY; } protected JdbcParameter getOffsetParameter() { return offsetParameter; } protected void setOffsetParameter(JdbcParameter offsetParameter) { this.offsetParameter = offsetParameter; } protected JdbcParameter getLimitParameter() { return limitParameter; } protected void setLimitParameter(JdbcParameter limitParameter) { this.limitParameter = limitParameter; } @Override public <X> X getLiteralValue(Expression expression) { return interpretExpression( expression, jdbcParameterBindings ); } @SuppressWarnings("unchecked") protected <R> R interpretExpression(Expression expression, JdbcParameterBindings jdbcParameterBindings) { if ( expression instanceof Literal literal ) { return (R) literal.getLiteralValue(); } else if ( expression instanceof JdbcParameter jdbcParameter ) { if ( jdbcParameterBindings == null ) { throw new IllegalArgumentException( "Can't interpret expression because no parameter bindings are available" ); } return (R) getParameterBindValue( jdbcParameter ); } else if ( expression instanceof SqmParameterInterpretation parameterInterpretation ) { if ( jdbcParameterBindings == null ) { throw new IllegalArgumentException( "Can't interpret expression because no parameter bindings are available" ); } return (R) getParameterBindValue( (JdbcParameter) parameterInterpretation.getResolvedExpression() ); } else if ( expression instanceof FunctionExpression functionExpression ) { if ( "concat".equals( functionExpression.getFunctionName() ) ) { final List<? extends SqlAstNode> arguments = functionExpression.getArguments(); final StringBuilder sb = new StringBuilder(); for ( SqlAstNode argument : arguments ) { final Object argumentLiteral = interpretExpression( (Expression) argument, jdbcParameterBindings ); if ( argumentLiteral == null ) { return null; } sb.append( argumentLiteral ); } return (R) sb.toString(); } } throw new UnsupportedOperationException( "Can't interpret expression: " + expression ); } protected void renderExpressionAsLiteral(Expression expression, JdbcParameterBindings jdbcParameterBindings) { if ( expression instanceof Literal ) { expression.accept( this ); return; } else if ( expression instanceof JdbcParameter parameter ) { if ( jdbcParameterBindings == null ) { throw new IllegalArgumentException( "Can't interpret expression because no parameter bindings are available" ); } renderAsLiteral( parameter, getParameterBindValue( parameter ) ); return; } else if ( expression instanceof SqmParameterInterpretation parameterInterpretation ) { if ( jdbcParameterBindings == null ) { throw new IllegalArgumentException( "Can't interpret expression because no parameter bindings are available" ); } final JdbcParameter parameter = (JdbcParameter) parameterInterpretation.getResolvedExpression(); renderAsLiteral( parameter, getParameterBindValue( parameter ) ); return; } throw new UnsupportedOperationException( "Can't render expression as literal: " + expression ); } protected Object getParameterBindValue(JdbcParameter parameter) { final JdbcParameterBinding binding; if ( parameter == getOffsetParameter() ) { binding = new JdbcParameterBindingImpl( getIntegerType(), getLimit().getFirstRow() ); } else if ( parameter == getLimitParameter() ) { binding = new JdbcParameterBindingImpl( getIntegerType(), getLimit().getMaxRows() ); } else { binding = jdbcParameterBindings.getBinding( parameter ); } addAppliedParameterBinding( parameter, binding ); return binding.getBindValue(); } protected Expression getLeftHandExpression(Predicate predicate) { if ( predicate instanceof NullnessPredicate nullnessPredicate ) { return nullnessPredicate.getExpression(); } else if ( predicate instanceof ComparisonPredicate comparisonPredicate ) { return comparisonPredicate.getLeftHandExpression(); } else { throw new AssertionFailure( "Unrecognized predicate" ); } } protected boolean inOverOrWithinGroupClause() { return clauseStack.findCurrentFirst( AbstractSqlAstTranslator::matchOverOrWithinGroupClauses ) != null; } private static Boolean matchOverOrWithinGroupClauses(final Clause clause) { return switch (clause) { case OVER, WITHIN_GROUP -> Boolean.TRUE; default -> null; }; } protected Stack<Clause> getClauseStack() { return clauseStack; } protected Stack<Statement> getStatementStack() { return statementStack; } protected Stack<QueryPart> getQueryPartStack() { return queryPartStack; } @Override public QueryPart getCurrentQueryPart() { return queryPartStack.getCurrent(); } @Override public Stack<Clause> getCurrentClauseStack() { return clauseStack; } protected CteStatement getCurrentCteStatement() { return currentCteStatement; } protected CteStatement getCteStatement(final String cteName) { return statementStack.findCurrentFirstWithParameter( cteName, AbstractSqlAstTranslator::matchCteStatement ); } private static CteStatement matchCteStatement(final Statement stmt, final String cteName) { return stmt instanceof CteContainer cteContainer ? cteContainer.getCteStatement( cteName ) : null; } private static CteContainer matchCteContainerByStatement(final Statement stmt, final String cteName) { return stmt instanceof CteContainer cteContainer && cteContainer.getCteStatement( cteName ) != null ? cteContainer : null; } @Override public T translate(JdbcParameterBindings jdbcParameterBindings, QueryOptions queryOptions) { try { this.jdbcParameterBindings = jdbcParameterBindings; final Statement statement = statementStack.pop(); if ( statement instanceof TableMutation<?> tableMutation ) { return translateTableMutation( tableMutation ); } else { this.lockOptions = queryOptions.getLockOptions().makeCopy(); this.limit = queryOptions.getLimit() == null ? null : queryOptions.getLimit().makeCopy(); final JdbcOperation jdbcOperation = getJdbcOperation( statement ); //noinspection unchecked return (T) jdbcOperation; } } finally { cleanup(); } } private JdbcOperation getJdbcOperation(Statement statement) { if ( statement instanceof DeleteStatement deleteStatement ) { return translateDelete( deleteStatement ); } else if ( statement instanceof UpdateStatement updateStatement) { return translateUpdate( updateStatement ); } else if ( statement instanceof InsertSelectStatement insertSelectStatement ) { return translateInsert( insertSelectStatement ); } else if ( statement instanceof SelectStatement selectStatement ) { return translateSelect( selectStatement ); } else { throw new IllegalArgumentException( "Unexpected statement - " + statement ); } } protected JdbcOperationQueryDelete translateDelete(DeleteStatement sqlAst) { visitDeleteStatement( sqlAst ); return new JdbcOperationQueryDelete( getSql(), getParameterBinders(), getAffectedTableNames(), getAppliedParameterBindings() ); } protected JdbcOperationQueryUpdate translateUpdate(UpdateStatement sqlAst) { visitUpdateStatement( sqlAst ); return new JdbcOperationQueryUpdate( getSql(), getParameterBinders(), getAffectedTableNames(), getAppliedParameterBindings() ); } protected JdbcOperationQueryInsert translateInsert(InsertSelectStatement sqlAst) { visitInsertStatement( sqlAst ); return new JdbcOperationQueryInsertImpl( getSql(), getParameterBinders(), getAffectedTableNames(), getUniqueConstraintNameThatMayFail(sqlAst) ); } protected String getUniqueConstraintNameThatMayFail(InsertSelectStatement sqlAst) { final ConflictClause conflictClause = sqlAst.getConflictClause(); if ( conflictClause == null || !conflictClause.getConstraintColumnNames().isEmpty() ) { return null; } else { if ( sqlAst.getSourceSelectStatement() != null && !isFetchFirstRowOnly( sqlAst.getSourceSelectStatement() ) || sqlAst.getValuesList().size() > 1 ) { throw new IllegalQueryOperationException( "Can't emulate conflict clause with constraint name for more than one row to insert" ); } return conflictClause.getConstraintName() == null ? "" : conflictClause.getConstraintName(); } } protected JdbcSelect translateSelect(SelectStatement selectStatement) { logDomainResultGraph( selectStatement.getDomainResultDescriptors() ); logSqlAst( selectStatement ); // we need to make a cope here for later since visitSelectStatement clears it :( final LockOptions lockOptions = this.lockOptions; visitSelectStatement( selectStatement ); final int rowsToSkip; final JdbcOperationQuerySelect jdbcSelect = new JdbcOperationQuerySelect( getSql(), getParameterBinders(), buildJdbcValuesMappingProducer( selectStatement ), getAffectedTableNames(), rowsToSkip = getRowsToSkip( selectStatement, getJdbcParameterBindings() ), getMaxRows( selectStatement, getJdbcParameterBindings(), rowsToSkip ), getAppliedParameterBindings(), getJdbcLockStrategy(), getOffsetParameter(), getLimitParameter() ); if ( lockOptions == null || !lockOptions.getLockMode().isPessimistic() ) { return jdbcSelect; } final LockingSupport lockingSupport = getDialect().getLockingSupport(); final LockingSupport.Metadata lockingSupportMetadata = lockingSupport.getMetadata(); final LockStrategy lockStrategy = determineLockingStrategy( lockingTarget, lockOptions.getFollowOnStrategy() ); return getSessionFactory().getJdbcSelectWithActionsBuilder() .setPrimaryAction( jdbcSelect ) .setLockTimeoutType( lockingSupportMetadata.getLockTimeoutType( lockOptions.getTimeout() ) ) .setLockingSupport( lockingSupport ) .setLockOptions( lockOptions ) .setLockingTarget( lockingTarget ) .setLockingClauseStrategy( lockingClauseStrategy ) .setIsFollowOnLockStrategy( lockStrategy == LockStrategy.FOLLOW_ON ) .build(); } private JdbcValuesMappingProducer buildJdbcValuesMappingProducer(SelectStatement selectStatement) { return getSessionFactory().getJdbcValuesMappingProducerProvider() .buildMappingProducer( selectStatement, getSessionFactory() ); } protected int getRowsToSkip(SelectStatement sqlAstSelect, JdbcParameterBindings jdbcParameterBindings) { if ( hasLimit() ) { if ( offsetParameter != null && needsRowsToSkip() ) { return interpretExpression( offsetParameter, jdbcParameterBindings ); } } else { final Expression offsetClauseExpression = sqlAstSelect.getQueryPart().getOffsetClauseExpression(); if ( offsetClauseExpression != null && needsRowsToSkip() ) { return interpretExpression( offsetClauseExpression, jdbcParameterBindings ); } } return 0; } protected int getMaxRows(SelectStatement sqlAstSelect, JdbcParameterBindings jdbcParameterBindings, int rowsToSkip) { if ( hasLimit() ) { if ( limitParameter != null && needsMaxRows() ) { final Number fetchCount = interpretExpression( limitParameter, jdbcParameterBindings ); return rowsToSkip + fetchCount.intValue(); } } else { final Expression fetchClauseExpression = sqlAstSelect.getQueryPart().getFetchClauseExpression(); if ( fetchClauseExpression != null && needsMaxRows() ) { final Number fetchCount = interpretExpression( fetchClauseExpression, jdbcParameterBindings ); return rowsToSkip + fetchCount.intValue(); } } return Integer.MAX_VALUE; } protected boolean needsRowsToSkip() { return false; } protected boolean needsMaxRows() { return false; } protected void prepareLimitOffsetParameters() { final Limit limit = getLimit(); if ( limit.getFirstRow() != null ) { setOffsetParameter( new OffsetJdbcParameter( sessionFactory.getTypeConfiguration().getBasicTypeForJavaType( Integer.class ) ) ); } if ( limit.getMaxRows() != null ) { setLimitParameter( new LimitJdbcParameter( sessionFactory.getTypeConfiguration().getBasicTypeForJavaType( Integer.class ) ) ); } } private static
AbstractSqlAstTranslator
java
spring-projects__spring-boot
module/spring-boot-thymeleaf/src/test/java/org/springframework/boot/thymeleaf/autoconfigure/ThymeleafServletAutoConfigurationTests.java
{ "start": 16373, "end": 16596 }
class ____ { @Bean FilterRegistrationBean<OrderedCharacterEncodingFilter> filterRegistration() { return new FilterRegistrationBean<>(new OrderedCharacterEncodingFilter()); } } }
FilterRegistrationOtherConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade2/Child.java
{ "start": 209, "end": 815 }
class ____ { private Long id; private String name; private Parent parent; private ChildInfo info; public Child() { } public Child(String name) { this.name = name; } 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; } public Parent getParent() { return parent; } public void setParent(Parent parent) { this.parent = parent; } public ChildInfo getInfo() { return info; } public void setInfo(ChildInfo info) { this.info = info; } }
Child
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/query/QueryRewriteContext.java
{ "start": 2934, "end": 24698 }
class ____ { protected final MapperService mapperService; protected final MappingLookup mappingLookup; protected final Map<String, MappedFieldType> runtimeMappings; protected final IndexSettings indexSettings; private final TransportVersion minTransportVersion; private final String localClusterAlias; protected final Index fullyQualifiedIndex; protected final Predicate<String> indexNameMatcher; protected final NamedWriteableRegistry writeableRegistry; protected final ValuesSourceRegistry valuesSourceRegistry; protected final BooleanSupplier allowExpensiveQueries; protected final ScriptCompiler scriptService; private final XContentParserConfiguration parserConfiguration; protected final Client client; protected final LongSupplier nowInMillis; private final List<BiConsumer<Client, ActionListener<?>>> asyncActions = new ArrayList<>(); private final Map<String, List<TriConsumer<RemoteClusterClient, ThreadContext, ActionListener<?>>>> remoteAsyncActions = new HashMap<>(); protected boolean allowUnmappedFields; protected boolean mapUnmappedFieldAsString; protected Predicate<String> allowedFields; private final ResolvedIndices resolvedIndices; private final PointInTimeBuilder pit; private QueryRewriteInterceptor queryRewriteInterceptor; private final Boolean ccsMinimizeRoundTrips; private final boolean isExplain; private final boolean isProfile; private Long timeRangeFilterFromMillis; private boolean trackTimeRangeFilterFrom = true; public QueryRewriteContext( final XContentParserConfiguration parserConfiguration, final Client client, final LongSupplier nowInMillis, final MapperService mapperService, final MappingLookup mappingLookup, final Map<String, MappedFieldType> runtimeMappings, final IndexSettings indexSettings, final TransportVersion minTransportVersion, final String localClusterAlias, final Index fullyQualifiedIndex, final Predicate<String> indexNameMatcher, final NamedWriteableRegistry namedWriteableRegistry, final ValuesSourceRegistry valuesSourceRegistry, final BooleanSupplier allowExpensiveQueries, final ScriptCompiler scriptService, final ResolvedIndices resolvedIndices, final PointInTimeBuilder pit, final QueryRewriteInterceptor queryRewriteInterceptor, final Boolean ccsMinimizeRoundTrips, final boolean isExplain, final boolean isProfile ) { this.parserConfiguration = parserConfiguration; this.client = client; this.nowInMillis = nowInMillis; this.mapperService = mapperService; this.mappingLookup = Objects.requireNonNull(mappingLookup); this.allowUnmappedFields = indexSettings == null || indexSettings.isDefaultAllowUnmappedFields(); this.runtimeMappings = runtimeMappings; this.indexSettings = indexSettings; this.minTransportVersion = minTransportVersion; this.localClusterAlias = localClusterAlias; this.fullyQualifiedIndex = fullyQualifiedIndex; this.indexNameMatcher = indexNameMatcher; this.writeableRegistry = namedWriteableRegistry; this.valuesSourceRegistry = valuesSourceRegistry; this.allowExpensiveQueries = allowExpensiveQueries; this.scriptService = scriptService; this.resolvedIndices = resolvedIndices; this.pit = pit; this.queryRewriteInterceptor = queryRewriteInterceptor; this.ccsMinimizeRoundTrips = ccsMinimizeRoundTrips; this.isExplain = isExplain; this.isProfile = isProfile; } public QueryRewriteContext(final XContentParserConfiguration parserConfiguration, final Client client, final LongSupplier nowInMillis) { this( parserConfiguration, client, nowInMillis, null, MappingLookup.EMPTY, Collections.emptyMap(), null, null, null, null, null, null, null, null, null, null, null, null, null, false, false ); } public QueryRewriteContext( final XContentParserConfiguration parserConfiguration, final Client client, final LongSupplier nowInMillis, final TransportVersion minTransportVersion, final String localClusterAlias, final ResolvedIndices resolvedIndices, final PointInTimeBuilder pit, final QueryRewriteInterceptor queryRewriteInterceptor, final Boolean ccsMinimizeRoundTrips ) { this( parserConfiguration, client, nowInMillis, minTransportVersion, localClusterAlias, resolvedIndices, pit, queryRewriteInterceptor, ccsMinimizeRoundTrips, false, false ); } public QueryRewriteContext( final XContentParserConfiguration parserConfiguration, final Client client, final LongSupplier nowInMillis, final TransportVersion minTransportVersion, final String localClusterAlias, final ResolvedIndices resolvedIndices, final PointInTimeBuilder pit, final QueryRewriteInterceptor queryRewriteInterceptor, final Boolean ccsMinimizeRoundTrips, final boolean isExplain, final boolean isProfile ) { this( parserConfiguration, client, nowInMillis, null, MappingLookup.EMPTY, Collections.emptyMap(), null, minTransportVersion, localClusterAlias, null, null, null, null, null, null, resolvedIndices, pit, queryRewriteInterceptor, ccsMinimizeRoundTrips, isExplain, isProfile ); } /** * The registry used to build new {@link XContentParser}s. Contains registered named parsers needed to parse the query. * * Used by WrapperQueryBuilder */ public XContentParserConfiguration getParserConfig() { return parserConfiguration; } /** * Returns the time in milliseconds that is shared across all resources involved. Even across shards and nodes. * * Used in date field query rewriting */ public long nowInMillis() { return nowInMillis.getAsLong(); } /** * Returns an instance of {@link SearchExecutionContext} if available or null otherwise */ public SearchExecutionContext convertToSearchExecutionContext() { return null; } /** * Returns an instance of {@link CoordinatorRewriteContext} if available or null otherwise */ public CoordinatorRewriteContext convertToCoordinatorRewriteContext() { return null; } /** * @return an {@link QueryRewriteContext} instance that is aware of the mapping and other index metadata or <code>null</code> otherwise. */ public QueryRewriteContext convertToIndexMetadataContext() { return mapperService != null ? this : null; } /** * Returns an instance of {@link DataRewriteContext} if available or null otherwise */ public DataRewriteContext convertToDataRewriteContext() { return null; } public InnerHitsRewriteContext convertToInnerHitsRewriteContext() { return null; } /** * Returns the {@link MappedFieldType} for the provided field name. * If the field is not mapped, the behaviour depends on the index.query.parse.allow_unmapped_fields setting, which defaults to true. * In case unmapped fields are allowed, null is returned when the field is not mapped. * In case unmapped fields are not allowed, either an exception is thrown or the field is automatically mapped as a text field. * @throws QueryShardException if unmapped fields are not allowed and automatically mapping unmapped fields as text is disabled. * @see QueryRewriteContext#setAllowUnmappedFields(boolean) * @see QueryRewriteContext#setMapUnmappedFieldAsString(boolean) */ public MappedFieldType getFieldType(String name) { return failIfFieldMappingNotFound(name, fieldType(name)); } protected MappedFieldType fieldType(String name) { // If the field is not allowed, behave as if it is not mapped if (allowedFields != null && false == allowedFields.test(name)) { return null; } MappedFieldType fieldType = runtimeMappings.get(name); return fieldType == null ? mappingLookup.getFieldType(name) : fieldType; } public IndexAnalyzers getIndexAnalyzers() { if (mapperService == null) { return IndexAnalyzers.of(Collections.emptyMap()); } return mapperService.getIndexAnalyzers(); } MappedFieldType failIfFieldMappingNotFound(String name, MappedFieldType fieldMapping) { if (fieldMapping != null || allowUnmappedFields) { return fieldMapping; } else if (mapUnmappedFieldAsString) { TextFieldMapper.Builder builder = new TextFieldMapper.Builder(name, getIndexAnalyzers()); return builder.build(MapperBuilderContext.root(false, false)).fieldType(); } else { throw new QueryShardException(this, "No field mapping can be found for the field with name [{}]", name); } } public void setAllowUnmappedFields(boolean allowUnmappedFields) { this.allowUnmappedFields = allowUnmappedFields; } public void setMapUnmappedFieldAsString(boolean mapUnmappedFieldAsString) { this.mapUnmappedFieldAsString = mapUnmappedFieldAsString; } /** * Returns the CCS minimize round-trips setting. Returns null if the value of the setting is unknown. */ public Boolean isCcsMinimizeRoundTrips() { return ccsMinimizeRoundTrips; } public boolean isExplain() { return this.isExplain; } public boolean isProfile() { return this.isProfile; } public NamedWriteableRegistry getWriteableRegistry() { return writeableRegistry; } public ValuesSourceRegistry getValuesSourceRegistry() { return valuesSourceRegistry; } public boolean allowExpensiveQueries() { assert allowExpensiveQueries != null; return allowExpensiveQueries.getAsBoolean(); } /** * Registers an async action that must be executed before the next rewrite round in order to make progress. * This should be used if a rewriteable needs to fetch some external resources in order to be executed ie. a document * from an index. */ public void registerAsyncAction(BiConsumer<Client, ActionListener<?>> asyncAction) { asyncActions.add(asyncAction); } public void registerRemoteAsyncAction( String clusterAlias, TriConsumer<RemoteClusterClient, ThreadContext, ActionListener<?>> asyncAction ) { List<TriConsumer<RemoteClusterClient, ThreadContext, ActionListener<?>>> asyncActions = remoteAsyncActions.computeIfAbsent( clusterAlias, k -> new ArrayList<>() ); asyncActions.add(asyncAction); } /** * Returns <code>true</code> if there are any registered async actions. */ public boolean hasAsyncActions() { return asyncActions.isEmpty() == false || remoteAsyncActions.isEmpty() == false; } /** * Executes all registered async actions and notifies the listener once it's done. The value that is passed to the listener is always * <code>null</code>. The list of registered actions is cleared once this method returns. */ public void executeAsyncActions(ActionListener<Void> listener) { if (asyncActions.isEmpty() && remoteAsyncActions.isEmpty()) { listener.onResponse(null); } else { int actionCount = asyncActions.size(); for (var actionList : remoteAsyncActions.values()) { actionCount += actionList.size(); } CountDown countDown = new CountDown(actionCount); ActionListener<?> internalListener = new ActionListener<>() { @Override public void onResponse(Object o) { if (countDown.countDown()) { listener.onResponse(null); } } @Override public void onFailure(Exception e) { if (countDown.fastForward()) { listener.onFailure(e); } } }; // make a copy to prevent concurrent modification exception List<BiConsumer<Client, ActionListener<?>>> biConsumers = new ArrayList<>(asyncActions); asyncActions.clear(); for (BiConsumer<Client, ActionListener<?>> action : biConsumers) { action.accept(client, internalListener); } var remoteAsyncActionsCopy = new HashMap<>(remoteAsyncActions); remoteAsyncActions.clear(); for (var entry : remoteAsyncActionsCopy.entrySet()) { String clusterAlias = entry.getKey(); List<TriConsumer<RemoteClusterClient, ThreadContext, ActionListener<?>>> remoteTriConsumers = entry.getValue(); RemoteClusterClient remoteClient = client.getRemoteClusterClient( clusterAlias, client.threadPool().executor(SEARCH_COORDINATION), RemoteClusterService.DisconnectedStrategy.RECONNECT_UNLESS_SKIP_UNAVAILABLE ); ThreadContext threadContext = client.threadPool().getThreadContext(); for (var action : remoteTriConsumers) { action.apply(remoteClient, threadContext, internalListener); } } } } /** * Returns the local cluster alias. */ public String getLocalClusterAlias() { return localClusterAlias != null ? localClusterAlias : RemoteClusterAware.LOCAL_CLUSTER_GROUP_KEY; } /** * Returns the minimum {@link TransportVersion} for intra-cluster node-to-node communications. Returns null if it is unknown. */ public TransportVersion getMinTransportVersion() { return minTransportVersion; } /** * Returns the fully qualified index including a remote cluster alias if applicable, and the index uuid */ public Index getFullyQualifiedIndex() { return fullyQualifiedIndex; } /** * Returns the index settings for this context. This might return null if the * context has not index scope. */ public IndexSettings getIndexSettings() { return indexSettings; } /** * Returns the MappingLookup for the queried index. */ public MappingLookup getMappingLookup() { return mappingLookup; } /** * Given an index pattern, checks whether it matches against the current shard. The pattern * may represent a fully qualified index name if the search targets remote shards. */ public boolean indexMatches(String pattern) { assert indexNameMatcher != null; return indexNameMatcher.test(pattern); } /** * Returns the names of all mapped fields that match a given pattern * * All names returned by this method are guaranteed to resolve to a * MappedFieldType if passed to {@link #getFieldType(String)} * * @param pattern the field name pattern */ public Set<String> getMatchingFieldNames(String pattern) { Set<String> matches; if (runtimeMappings.isEmpty()) { matches = mappingLookup.getMatchingFieldNames(pattern); } else { matches = new HashSet<>(mappingLookup.getMatchingFieldNames(pattern)); if ("*".equals(pattern)) { matches.addAll(runtimeMappings.keySet()); } else if (Regex.isSimpleMatchPattern(pattern) == false) { // no wildcard if (runtimeMappings.containsKey(pattern)) { matches.add(pattern); } } else { for (String name : runtimeMappings.keySet()) { if (Regex.simpleMatch(pattern, name)) { matches.add(name); } } } } // If the field is not allowed, behave as if it is not mapped return allowedFields == null ? matches : matches.stream().filter(allowedFields).collect(Collectors.toSet()); } /** * @return An {@link Iterable} with key the field name and value the MappedFieldType */ public Iterable<Map.Entry<String, MappedFieldType>> getAllFields() { Map<String, MappedFieldType> allFromMapping = mappingLookup.getFullNameToFieldType(); Set<Map.Entry<String, MappedFieldType>> allEntrySet = allowedFields == null ? allFromMapping.entrySet() : allFromMapping.entrySet().stream().filter(entry -> allowedFields.test(entry.getKey())).collect(Collectors.toSet()); if (runtimeMappings.isEmpty()) { return allEntrySet; } Set<Map.Entry<String, MappedFieldType>> runtimeEntrySet = allowedFields == null ? runtimeMappings.entrySet() : runtimeMappings.entrySet().stream().filter(entry -> allowedFields.test(entry.getKey())).collect(Collectors.toSet()); // runtime mappings and non-runtime fields don't overlap, so we can simply concatenate the iterables here return () -> Iterators.concat(allEntrySet.iterator(), runtimeEntrySet.iterator()); } public ResolvedIndices getResolvedIndices() { return resolvedIndices; } /** * Returns the {@link PointInTimeBuilder} used by the search request, or null if not specified. */ @Nullable public PointInTimeBuilder getPointInTimeBuilder() { return pit; } /** * Retrieve the first tier preference from the index setting. If the setting is not * present, then return null. */ @Nullable public String getTierPreference() { Settings settings = getIndexSettings().getSettings(); String value = DataTier.TIER_PREFERENCE_SETTING.get(settings); if (Strings.hasText(value) == false) { return null; } // Tier preference can be a comma-delimited list of tiers, ordered by preference // It was decided we should only test the first of these potentially multiple preferences. return value.split(",")[0].trim(); } public QueryRewriteInterceptor getQueryRewriteInterceptor() { return queryRewriteInterceptor; } public void setQueryRewriteInterceptor(QueryRewriteInterceptor queryRewriteInterceptor) { this.queryRewriteInterceptor = queryRewriteInterceptor; } /** * Returns the minimum lower bound across the time ranges filters against the @timestamp field included in the query */ public Long getTimeRangeFilterFromMillis() { return timeRangeFilterFromMillis; } /** * Optionally records the lower bound of a time range filter included in the query. For telemetry purposes. */ public void setTimeRangeFilterFromMillis(String fieldName, long timeRangeFilterFromMillis, DateFieldMapper.Resolution resolution) { if (trackTimeRangeFilterFrom) { if (DataStream.TIMESTAMP_FIELD_NAME.equals(fieldName) || IndexMetadata.EVENT_INGESTED_FIELD_NAME.equals(fieldName)) { // if we got a timestamp with nanoseconds precision, round it down to millis if (resolution == DateFieldMapper.Resolution.NANOSECONDS) { timeRangeFilterFromMillis = timeRangeFilterFromMillis / 1_000_000; } if (this.timeRangeFilterFromMillis == null) { this.timeRangeFilterFromMillis = timeRangeFilterFromMillis; } else { // if there's more range filters on timestamp, we'll take the lowest of the lower bounds this.timeRangeFilterFromMillis = Math.min(timeRangeFilterFromMillis, this.timeRangeFilterFromMillis); } } } } /** * Records the lower bound of a time range filter included in the query. For telemetry purposes. * Similar to {@link #setTimeRangeFilterFromMillis(String, long, DateFieldMapper.Resolution)} but used to copy the value from * another instance of the context, that had its value previously set. */ public void setTimeRangeFilterFromMillis(long timeRangeFilterFromMillis) { this.timeRangeFilterFromMillis = timeRangeFilterFromMillis; } /** * Enables or disables the tracking of the lower bound for time range filters against the @timestamp field, * done via {@link #setTimeRangeFilterFromMillis(String, long, DateFieldMapper.Resolution)}. Tracking is enabled by default, * and explicitly disabled to ensure we don't record the bound for range queries within should and must_not clauses. */ public void setTrackTimeRangeFilterFrom(boolean trackTimeRangeFilterFrom) { this.trackTimeRangeFilterFrom = trackTimeRangeFilterFrom; } }
QueryRewriteContext
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/calc/async/RetryPredicates.java
{ "start": 1422, "end": 1796 }
class ____ implements Predicate<Collection<RowData>>, Serializable { private static final long serialVersionUID = 5065281655787318565L; @Override public boolean test(Collection<RowData> c) { return null == c || c.isEmpty(); } } /** Returns true for any exception. */ public static
EmptyResponseResultStrategy
java
elastic__elasticsearch
test/framework/src/test/java/org/elasticsearch/test/AbstractXContentTestCaseTests.java
{ "start": 1018, "end": 3880 }
class ____ extends ESTestCase { public void testInsertRandomFieldsAndShuffle() throws Exception { XContentBuilder builder = XContentFactory.jsonBuilder(); builder.startObject(); { builder.field("field", 1); } builder.endObject(); BytesReference insertRandomFieldsAndShuffle = RandomizedContext.current() .runWithPrivateRandomness( 1, () -> AbstractXContentTestCase.insertRandomFieldsAndShuffle( BytesReference.bytes(builder), XContentType.JSON, true, new String[] {}, null, this::createParser ) ); try (XContentParser parser = createParser(XContentType.JSON.xContent(), insertRandomFieldsAndShuffle)) { Map<String, Object> mapOrdered = parser.mapOrdered(); assertThat(mapOrdered.size(), equalTo(2)); assertThat(mapOrdered.keySet().iterator().next(), not(equalTo("field"))); } } private record TestToXContent(String field, String value) implements ToXContentFragment { @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.field(field, value); } } public void testYamlXContentRoundtripSanitization() throws Exception { var test = new AbstractXContentTestCase<TestToXContent>() { @Override protected TestToXContent createTestInstance() { // we need to randomly create both a "problematic" and an okay version in order to ensure that the sanitization code // can draw at least one okay version if polled often enough return randomBoolean() ? new TestToXContent("a\u0085b", "def") : new TestToXContent("a b", "def"); } @Override protected TestToXContent doParseInstance(XContentParser parser) throws IOException { assertEquals(XContentParser.Token.START_OBJECT, parser.nextToken()); assertEquals(XContentParser.Token.FIELD_NAME, parser.nextToken()); String name = parser.currentName(); assertEquals(XContentParser.Token.VALUE_STRING, parser.nextToken()); String value = parser.text(); assertEquals(XContentParser.Token.END_OBJECT, parser.nextToken()); return new TestToXContent(name, value); }; @Override protected boolean supportsUnknownFields() { return false; } }; // testFromXContent runs 20 repetitions, enough to hit a YAML xcontent version very likely test.testFromXContent(); } }
AbstractXContentTestCaseTests
java
quarkusio__quarkus
extensions/datasource/deployment-spi/src/main/java/io/quarkus/datasource/deployment/spi/DevServicesDatasourceResultBuildItem.java
{ "start": 1356, "end": 1850 }
class ____ { final String dbType; final Map<String, String> configProperties; public DbResult(String dbType, Map<String, String> configProperties) { this.dbType = dbType; this.configProperties = Collections.unmodifiableMap(configProperties); } public String getDbType() { return dbType; } public Map<String, String> getConfigProperties() { return configProperties; } } }
DbResult
java
quarkusio__quarkus
independent-projects/arc/runtime/src/main/java/io/quarkus/arc/impl/EventProvider.java
{ "start": 368, "end": 1015 }
class ____<T> implements InjectableReferenceProvider<Event<T>> { private final Type eventType; private final Set<Annotation> eventQualifiers; private final InjectionPoint injectionPoint; public EventProvider(Type eventType, Set<Annotation> eventQualifiers, InjectionPoint injectionPoint) { this.eventType = eventType; this.eventQualifiers = eventQualifiers; this.injectionPoint = injectionPoint; } @Override public Event<T> get(CreationalContext<Event<T>> creationalContext) { return ArcContainerImpl.instance().getEvent(eventType, eventQualifiers, injectionPoint); } }
EventProvider
java
hibernate__hibernate-orm
hibernate-jcache/src/test/java/org/hibernate/orm/test/jcache/JCacheClasspathConfigUriTest.java
{ "start": 896, "end": 1183 }
class ____ { @Test public void test(SessionFactoryScope factoryScope) { factoryScope.inTransaction( (session) -> { Product product = new Product(); product.setName( "Acme" ); product.setPriceCents( 100L ); session.persist( product ); } ); } }
JCacheClasspathConfigUriTest
java
quarkusio__quarkus
independent-projects/bootstrap/app-model/src/main/java/io/quarkus/bootstrap/util/BootstrapUtils.java
{ "start": 6338, "end": 9550 }
class ____ not be loaded * @throws IOException in case of an IO failure */ public static ApplicationModel readAppModelWithWorkspaceId(Path file, int workspaceId) throws ClassNotFoundException, IOException { try (ObjectInputStream reader = new ObjectInputStream(Files.newInputStream(file))) { if (reader.readInt() == CP_CACHE_FORMAT_ID) { if (reader.readInt() == workspaceId) { final ApplicationModel appModel = (ApplicationModel) reader.readObject(); log.debugf("Loaded application model %s from %s", appModel, file); for (ResolvedDependency d : appModel.getDependencies(DependencyFlags.DEPLOYMENT_CP)) { for (Path p : d.getResolvedPaths()) { if (!Files.exists(p)) { throw new IOException("Cached artifact does not exist: " + p); } } } return appModel; } else { log.debugf("Application model saved in %s has a different workspace ID", file); } } else { log.debugf("Unsupported application model serialization format in %s", file); } } return null; } /** * Generates a comma-separated list of flag names for an integer representation of the flags. * * @param flags flags as an integer value * @return comma-separated list of the flag names */ public static String toTextFlags(int flags) { var sb = new StringBuilder(); appendFlagIfSet(sb, flags, DependencyFlags.OPTIONAL, "optional"); appendFlagIfSet(sb, flags, DependencyFlags.DIRECT, "direct"); appendFlagIfSet(sb, flags, DependencyFlags.RUNTIME_CP, "runtime-cp"); appendFlagIfSet(sb, flags, DependencyFlags.DEPLOYMENT_CP, "deployment-cp"); appendFlagIfSet(sb, flags, DependencyFlags.RUNTIME_EXTENSION_ARTIFACT, "runtime-extension-artifact"); appendFlagIfSet(sb, flags, DependencyFlags.WORKSPACE_MODULE, "workspace-module"); appendFlagIfSet(sb, flags, DependencyFlags.RELOADABLE, "reloadable"); appendFlagIfSet(sb, flags, DependencyFlags.TOP_LEVEL_RUNTIME_EXTENSION_ARTIFACT, "top-level-runtime-extension-artifact"); appendFlagIfSet(sb, flags, DependencyFlags.CLASSLOADER_PARENT_FIRST, "classloader-parent-first"); appendFlagIfSet(sb, flags, DependencyFlags.CLASSLOADER_RUNNER_PARENT_FIRST, "classloader-runner-parent-first"); appendFlagIfSet(sb, flags, DependencyFlags.CLASSLOADER_LESSER_PRIORITY, "classloader-lesser-priority"); appendFlagIfSet(sb, flags, DependencyFlags.COMPILE_ONLY, "compile-only"); appendFlagIfSet(sb, flags, DependencyFlags.VISITED, "visited"); return sb.toString(); } private static void appendFlagIfSet(StringBuilder sb, int flags, int flagValue, String flagName) { if ((flags & flagValue) == flagValue) { if (!sb.isEmpty()) { sb.append(", "); } sb.append(flagName); } } }
could
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ShouldBeReadable.java
{ "start": 910, "end": 1651 }
class ____ extends BasicErrorMessageFactory { static final String SHOULD_BE_READABLE = "%nExpecting actual:%n %s%nto be readable."; private ShouldBeReadable(File actual) { super(SHOULD_BE_READABLE, actual); } private ShouldBeReadable(Path actual) { super(SHOULD_BE_READABLE, actual); } /** * Creates a new <code>{@link ShouldBeReadable}</code>. * * @param actual the actual value in the failed assertion. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldBeReadable(File actual) { return new ShouldBeReadable(actual); } public static ErrorMessageFactory shouldBeReadable(Path actual) { return new ShouldBeReadable(actual); } }
ShouldBeReadable
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/pattern/NameAbbreviator.java
{ "start": 5632, "end": 5998 }
class ____ extends NameAbbreviator { /** * <p>When the name is reduced in length by cutting parts, there can be two ways to do it.</p> * 1. Remove a given number of parts starting from front - called DROP <br/> * 2. Retain a given number of parts starting from the end - called RETAIN */ private
MaxElementAbbreviator
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/util/Transform.java
{ "start": 910, "end": 959 }
class ____ transforming strings. */ public final
for
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/script/field/ShortDocValuesField.java
{ "start": 780, "end": 3895 }
class ____ extends AbstractScriptFieldFactory<Short> implements Field<Short>, DocValuesScriptFieldFactory, ScriptDocValues.Supplier<Long> { protected final SortedNumericLongValues input; protected final String name; protected short[] values = new short[0]; protected int count; private ScriptDocValues.Longs longs = null; public ShortDocValuesField(SortedNumericLongValues input, String name) { this.input = input; this.name = name; } @Override public void setNextDocId(int docId) throws IOException { if (input.advanceExact(docId)) { resize(input.docValueCount()); for (int i = 0; i < count; i++) { values[i] = (short) input.nextValue(); } } else { resize(0); } } protected void resize(int newSize) { count = newSize; assert count >= 0 : "size must be positive (got " + count + "): likely integer overflow?"; values = ArrayUtil.grow(values, count); } /** * Returns a {@code ScriptDocValues} of the appropriate type for this field. * This is used to support backwards compatibility for accessing field values * through the {@code doc} variable. */ @Override public ScriptDocValues<Long> toScriptDocValues() { if (longs == null) { longs = new ScriptDocValues.Longs(this); } return longs; } @Override public Long getInternal(int index) { return (long) values[index]; } /** * Returns the name of this field. */ @Override public String getName() { return name; } /** * Returns {@code true} if this field has no values, otherwise {@code false}. */ @Override public boolean isEmpty() { return count == 0; } /** * Returns the number of values this field has. */ @Override public int size() { return count; } @Override public Iterator<Short> iterator() { return new Iterator<Short>() { private int index = 0; @Override public boolean hasNext() { return index < count; } @Override public Short next() { if (hasNext() == false) { throw new NoSuchElementException(); } return values[index++]; } }; } public short get(int defaultValue) { return get(0, defaultValue); } /** * Note: Constants in java and painless are ints, so letting the defaultValue be an int allows users to * call this without casting. A short variable will be automatically widened to an int. * If the user does pass a value outside the range, it will be cast down to a short. */ public short get(int index, int defaultValue) { if (isEmpty() || index < 0 || index >= count) { return (short) defaultValue; } return values[index]; } }
ShortDocValuesField
java
spring-projects__spring-framework
spring-tx/src/main/java/org/springframework/transaction/support/ResourceHolder.java
{ "start": 965, "end": 1317 }
interface ____ { /** * Reset the transactional state of this holder. */ void reset(); /** * Notify this holder that it has been unbound from transaction synchronization. */ void unbound(); /** * Determine whether this holder is considered as 'void', * i.e. as a leftover from a previous thread. */ boolean isVoid(); }
ResourceHolder
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/issue_2200/Issue2289.java
{ "start": 610, "end": 661 }
class ____ extends A { public int id; } }
B
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/InstanceOfAssertFactoriesTest.java
{ "start": 62065, "end": 62912 }
class ____ { private final Object actual = AtomicLongFieldUpdater.newUpdater(Container.class, "longField"); @Test void createAssert() { // WHEN AtomicLongFieldUpdaterAssert<Container> result = atomicLongFieldUpdater(Container.class).createAssert(actual); // THEN result.hasValue(0L, new Container()); } @Test void createAssert_with_ValueProvider() { // GIVEN ValueProvider<?> valueProvider = mockThatDelegatesTo(type -> actual); // WHEN AtomicLongFieldUpdaterAssert<Container> result = atomicLongFieldUpdater(Container.class).createAssert(valueProvider); // THEN result.hasValue(0L, new Container()); verify(valueProvider).apply(parameterizedType(AtomicLongFieldUpdater.class, Container.class)); } private static
AtomicLongFieldUpdater_Typed_Factory
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/qualifiers/replaces/IntroductionB.java
{ "start": 861, "end": 959 }
interface ____ { String test(String name); String test(String name, int age); }
IntroductionB
java
netty__netty
transport/src/main/java/io/netty/channel/ServerChannel.java
{ "start": 908, "end": 984 }
interface ____ extends Channel { // This is a tag interface. }
ServerChannel
java
grpc__grpc-java
interop-testing/src/test/java/io/grpc/testing/integration/NettyFlowControlTest.java
{ "start": 7076, "end": 8571 }
class ____ implements StreamObserver<StreamingOutputCallResponse> { final AtomicReference<GrpcHttp2ConnectionHandler> grpcHandlerRef; final CountDownLatch latch = new CountDownLatch(1); final long expectedWindow; int lastWindow; boolean wasCompleted; public TestStreamObserver( AtomicReference<GrpcHttp2ConnectionHandler> grpcHandlerRef, long window) { this.grpcHandlerRef = grpcHandlerRef; expectedWindow = window; } @Override public void onNext(StreamingOutputCallResponse value) { GrpcHttp2ConnectionHandler grpcHandler = grpcHandlerRef.get(); Http2Stream connectionStream = grpcHandler.connection().connectionStream(); int curWindow = grpcHandler.decoder().flowController().initialWindowSize(connectionStream); synchronized (this) { if (curWindow >= expectedWindow) { if (wasCompleted) { return; } wasCompleted = true; lastWindow = curWindow; onCompleted(); } else if (!wasCompleted) { lastWindow = curWindow; } } } @Override public void onError(Throwable t) { latch.countDown(); throw new RuntimeException(t); } @Override public void onCompleted() { latch.countDown(); } public int waitFor(long duration, TimeUnit unit) throws InterruptedException { latch.await(duration, unit); return lastWindow; } } private static
TestStreamObserver
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnusedMethodTest.java
{ "start": 13308, "end": 13594 }
class ____ { private Test(int a) {} private Test(String a) {} public Test of() { return new Test(1); } } """) .addOutputLines( "Test.java", """
Test
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/operators/coordination/RecreateOnResetOperatorCoordinatorTest.java
{ "start": 15759, "end": 16125 }
class ____ implements OperatorEvent { private static final long serialVersionUID = -3289352911927668275L; private final int id; private TestingEvent() { this(-1); } private TestingEvent(int id) { this.id = id; } private int getId() { return id; } } }
TestingEvent
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/ExplainLifecycleRequest.java
{ "start": 1129, "end": 4441 }
class ____ extends LocalClusterStateRequest implements IndicesRequest.Replaceable { private String[] indices = Strings.EMPTY_ARRAY; private IndicesOptions indicesOptions; private boolean onlyErrors = false; private boolean onlyManaged = false; public ExplainLifecycleRequest(TimeValue masterTimeout) { super(masterTimeout); indicesOptions = IndicesOptions.strictExpandOpen(); } /** * NB prior to 9.0 this was a TransportMasterNodeReadAction so for BwC we must remain able to read these requests until * we no longer need to support calling this action remotely. */ @UpdateForV10(owner = UpdateForV10.Owner.DATA_MANAGEMENT) public ExplainLifecycleRequest(StreamInput in) throws IOException { super(in); indices = in.readStringArray(); indicesOptions = IndicesOptions.readIndicesOptions(in); onlyErrors = in.readBoolean(); onlyManaged = in.readBoolean(); } @Override public ExplainLifecycleRequest indices(String... indices) { this.indices = indices; return this; } public ExplainLifecycleRequest indicesOptions(IndicesOptions indicesOptions) { this.indicesOptions = indicesOptions; return this; } @Override public String[] indices() { return indices; } @Override public IndicesOptions indicesOptions() { return indicesOptions; } @Override public boolean includeDataStreams() { return true; } public boolean onlyErrors() { return onlyErrors; } public ExplainLifecycleRequest onlyErrors(boolean onlyErrors) { this.onlyErrors = onlyErrors; return this; } public boolean onlyManaged() { return onlyManaged; } public ExplainLifecycleRequest onlyManaged(boolean onlyManaged) { this.onlyManaged = onlyManaged; return this; } @Override public ActionRequestValidationException validate() { return null; } @Override public Task createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) { return new CancellableTask(id, type, action, "", parentTaskId, headers); } @Override public int hashCode() { return Objects.hash(Arrays.hashCode(indices()), indicesOptions(), onlyErrors, onlyManaged); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (obj.getClass() != getClass()) { return false; } ExplainLifecycleRequest other = (ExplainLifecycleRequest) obj; return Objects.deepEquals(indices(), other.indices()) && Objects.equals(indicesOptions(), other.indicesOptions()) && Objects.equals(onlyErrors(), other.onlyErrors()) && Objects.equals(onlyManaged(), other.onlyManaged()); } @Override public String toString() { return "ExplainLifecycleRequest [indices()=" + Arrays.toString(indices()) + ", indicesOptions()=" + indicesOptions() + ", onlyErrors()=" + onlyErrors() + ", onlyManaged()=" + onlyManaged() + "]"; } }
ExplainLifecycleRequest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/inheritance/discriminator/MultiInheritanceDiscriminatorTest.java
{ "start": 5780, "end": 5823 }
class ____ extends AbstractAcc { } }
DebitAcc
java
google__truth
core/src/main/java/com/google/common/truth/Correspondence.java
{ "start": 3063, "end": 3355 }
class ____ to use one of the static * factory methods. The most general of these is {@link #from}; the other methods are more * convenient in specific cases. The optional diff-formatting functionality can be added using * {@link #formattingDiffsUsing}. (Alternatively, you can subclass this
is
java
redisson__redisson
redisson/src/main/java/org/redisson/PubSubPatternStatusListener.java
{ "start": 841, "end": 1960 }
class ____ implements RedisPubSubListener<Object> { private final PatternStatusListener listener; private final String name; public String getName() { return name; } public PubSubPatternStatusListener(PubSubPatternStatusListener l) { this.listener = l.listener; this.name = l.name; } public PubSubPatternStatusListener(PatternStatusListener listener, String name) { super(); this.listener = listener; this.name = name; } @Override public void onMessage(CharSequence channel, Object message) { } @Override public void onPatternMessage(CharSequence pattern, CharSequence channel, Object message) { } @Override public void onStatus(PubSubType type, CharSequence channel) { if (channel.toString().equals(name)) { if (type == PubSubType.PSUBSCRIBE) { listener.onPSubscribe(channel.toString()); } else if (type == PubSubType.PUNSUBSCRIBE) { listener.onPUnsubscribe(channel.toString()); } } } }
PubSubPatternStatusListener
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/cfg/BaseSettings.java
{ "start": 582, "end": 804 }
class ____ to store simple configuration * settings for both serialization and deserialization. * Since instances are fully immutable, instances can * be freely shared and used without synchronization. */ public final
used
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/view/DefaultRendering.java
{ "start": 1010, "end": 2084 }
class ____ implements Rendering { private static final HttpHeaders EMPTY_HEADERS = HttpHeaders.EMPTY; private final Object view; private final Map<String, Object> model; private final @Nullable HttpStatusCode status; private final HttpHeaders headers; DefaultRendering(Object view, @Nullable Model model, @Nullable HttpStatusCode status, @Nullable HttpHeaders headers) { this.view = view; this.model = (model != null ? model.asMap() : Collections.emptyMap()); this.status = status; this.headers = (headers != null ? headers : EMPTY_HEADERS); } @Override public @Nullable Object view() { return this.view; } @Override public Map<String, Object> modelAttributes() { return this.model; } @Override public @Nullable HttpStatusCode status() { return this.status; } @Override public HttpHeaders headers() { return this.headers; } @Override public String toString() { return "Rendering[view=" + this.view + ", modelAttributes=" + this.model + ", status=" + this.status + ", headers=" + this.headers + "]"; } }
DefaultRendering
java
elastic__elasticsearch
x-pack/plugin/migrate/src/main/java/org/elasticsearch/system_indices/action/GetFeatureUpgradeStatusResponse.java
{ "start": 8539, "end": 12182 }
class ____ implements Writeable, ToXContentObject { private static final Map<String, String> STACK_TRACE_ENABLED_PARAMS = Map.of( ElasticsearchException.REST_EXCEPTION_SKIP_STACK_TRACE, "false" ); private final String indexName; private final IndexVersion version; @Nullable private final Exception exception; // Present if this index failed /** * @param indexName Name of the index * @param version Index version * @param exception The exception that this index's migration failed with, if applicable */ public IndexInfo(String indexName, IndexVersion version, Exception exception) { this.indexName = indexName; this.version = version; this.exception = exception; } /** * @param in A stream input for a serialized index version object * @throws IOException if we can't deserialize the object */ public IndexInfo(StreamInput in) throws IOException { this.indexName = in.readString(); this.version = IndexVersion.readVersion(in); boolean hasException = in.readBoolean(); if (hasException) { this.exception = in.readException(); } else { this.exception = null; } } public String getIndexName() { return this.indexName; } public IndexVersion getVersion() { return this.version; } public Exception getException() { return this.exception; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(this.indexName); IndexVersion.writeVersion(this.version, out); if (exception != null) { out.writeBoolean(true); out.writeException(this.exception); } else { out.writeBoolean(false); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { Params exceptionParams = new DelegatingMapParams(STACK_TRACE_ENABLED_PARAMS, params); builder.startObject(); builder.field("index", this.indexName); builder.field("version", this.version.toReleaseVersion()); if (exception != null) { builder.startObject("failure_cause"); { ElasticsearchException.generateFailureXContent(builder, exceptionParams, exception, true); } builder.endObject(); } builder.endObject(); return builder; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; IndexInfo that = (IndexInfo) o; return indexName.equals(that.indexName) && version.equals(that.version); } @Override public int hashCode() { return Objects.hash(indexName, version); } @Override public String toString() { return "IndexInfo{" + "indexName='" + indexName + '\'' + ", version='" + version + '\'' + ", exception='" + (exception == null ? "null" : exception.getMessage()) + "'" + '}'; } } }
IndexInfo