language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/stream/sql/ChangelogNormalizeOptimizationTest.java
{ "start": 11426, "end": 14679 }
class ____ { private final Set<TableProperties> tablesToCreate; private final Map<String, String> sessionOptions = new HashMap<>(); private final String query; private final String description; private TestSpec(String description, Set<TableProperties> tablesToCreate, String query) { this.tablesToCreate = tablesToCreate; this.query = query; this.description = description; } public static TestSpec selectWithoutMetadata(SourceTable sourceTable, SinkTable sinkTable) { return new TestSpec( String.format( "select_no_metadata_%s_into_%s", sourceTable.getTableName(), sinkTable.getTableName()), new HashSet<>(Arrays.asList(sourceTable, sinkTable)), String.format( "INSERT INTO %s SELECT id, col1, col2 FROM %s", sinkTable.getTableName(), sourceTable.getTableName())); } public static TestSpec select(SourceTable sourceTable, SinkTable sinkTable) { return new TestSpec( String.format( "select_%s_into_%s", sourceTable.getTableName(), sinkTable.getTableName()), new HashSet<>(Arrays.asList(sourceTable, sinkTable)), String.format( "INSERT INTO %s SELECT * FROM %s", sinkTable.getTableName(), sourceTable.getTableName())); } public static TestSpec selectWithFilter(SourceTable sourceTable, SinkTable sinkTable) { return new TestSpec( String.format( "select_with_filter_%s_into_%s", sourceTable.getTableName(), sinkTable.getTableName()), new HashSet<>(Arrays.asList(sourceTable, sinkTable)), String.format( "INSERT INTO %s SELECT * FROM %s WHERE col1 > 2", sinkTable.getTableName(), sourceTable.getTableName())); } public static TestSpec join( SourceTable leftTable, SourceTable rightTable, SinkTable sinkTable) { return new TestSpec( String.format( "join_%s_%s_into_%s", leftTable.getTableName(), rightTable.getTableName(), sinkTable.getTableName()), new HashSet<>(Arrays.asList(leftTable, rightTable, sinkTable)), String.format( "INSERT INTO %s SELECT l.* FROM %s l JOIN %s r ON l.id = r.id", sinkTable.getTableName(), leftTable.getTableName(), rightTable.getTableName())); } public TestSpec withSessionOption(String key, String value) { this.sessionOptions.put(key, value); return this; } @Override public String toString() { return description; } } }
TestSpec
java
quarkusio__quarkus
test-framework/junit5-component/src/test/java/io/quarkus/test/component/lifecycle/PerClassLifecycleTest.java
{ "start": 852, "end": 1552 }
class ____ { @RegisterExtension static final QuarkusComponentTestExtension extension = new QuarkusComponentTestExtension(); @Inject MySingleton mySingleton; @InjectMock Charlie charlie; @Order(1) @Test public void testPing1() { Mockito.when(charlie.ping()).thenReturn("foo"); assertEquals("foo", mySingleton.ping()); assertEquals(1, MySingleton.COUNTER.get()); } @Order(2) @Test public void testPing2() { Mockito.when(charlie.ping()).thenReturn("baz"); assertEquals("baz", mySingleton.ping()); assertEquals(1, MySingleton.COUNTER.get()); } @Singleton public static
PerClassLifecycleTest
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/AtomicLongArrayAssertBaseTest.java
{ "start": 916, "end": 1562 }
class ____ extends BaseTestTemplate<AtomicLongArrayAssert, AtomicLongArray> { protected LongArrays arrays; @Override protected AtomicLongArrayAssert create_assertions() { return new AtomicLongArrayAssert(new AtomicLongArray(emptyArray())); } @Override protected void inject_internal_objects() { super.inject_internal_objects(); arrays = mock(LongArrays.class); assertions.arrays = arrays; } protected LongArrays getArrays(AtomicLongArrayAssert someAssertions) { return someAssertions.arrays; } protected long[] internalArray() { return array(getActual(assertions)); } }
AtomicLongArrayAssertBaseTest
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/util/DumpModelAsYamlTestSupport.java
{ "start": 1012, "end": 1618 }
class ____ extends ContextTestSupport { @Override protected CamelContext createCamelContext() throws Exception { CamelContext ctx = super.createCamelContext(); ctx.getCamelContextExtension().addContextPlugin(NodeIdFactory.class, buildNodeIdFactory()); return ctx; } private static NodeIdFactory buildNodeIdFactory() { return new NodeIdFactory() { @Override public String createId(NamedNode definition) { return definition.getShortName(); // do not use counter } }; } }
DumpModelAsYamlTestSupport
java
spring-projects__spring-boot
module/spring-boot-rsocket/src/main/java/org/springframework/boot/rsocket/autoconfigure/RSocketServerAutoConfiguration.java
{ "start": 7183, "end": 7325 }
class ____ { } @ConditionalOnProperty(name = "spring.rsocket.server.transport", havingValue = "websocket") static
HasMappingPathConfigured
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnBeanTests.java
{ "start": 22654, "end": 22962 }
class ____ { @Bean @ConditionalOnBean(GenericExampleBean.class) GenericExampleBean<String> genericStringWithValueExampleBean() { return new GenericExampleBean<>("genericStringWithValueExampleBean"); } } @Configuration(proxyBeanMethods = false) static
TypeArgumentsConditionWithValueConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/persister/entity/JoinFormulaImplicitJoinTest.java
{ "start": 1211, "end": 2105 }
class ____ { @BeforeEach public void setUp(EntityManagerFactoryScope scope) { scope.inTransaction(entityManager -> { final Person person = new Person(); entityManager.persist(person); for (int i = 0; i < 3; i++) { final PersonVersion personVersion = new PersonVersion(); personVersion.setName("Name" + i); personVersion.setVersion(i); personVersion.setPerson(person); entityManager.persist(personVersion); } }); } protected int entityCount() { return 5; } @Test public void testImplicitJoin(EntityManagerFactoryScope scope) { scope.inTransaction(entityManager -> { entityManager.createQuery( "SELECT person\n" + "FROM Person AS person\n" + " LEFT JOIN FETCH person.latestPersonVersion\n" + "order by person.latestPersonVersion.id desc\n" ); }); } @Entity(name = "Person") public static
JoinFormulaImplicitJoinTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/stateless/fetching/StatelessSessionFetchingTest.java
{ "start": 1397, "end": 6729 }
class ____ { @Test public void testDynamicFetch(SessionFactoryScope scope) { scope.inTransaction( session -> { Date now = new Date(); User me = new User( "me" ); User you = new User( "you" ); Resource yourClock = new Resource( "clock", you ); Task task = new Task( me, "clean", yourClock, now ); // :) session.persist( me ); session.persist( you ); session.persist( yourClock ); session.persist( task ); } ); scope.inStatelessTransaction( session -> { Task taskRef = (Task) session.createQuery( "from Task t join fetch t.resource join fetch t.user" ) .uniqueResult(); assertNotNull( taskRef ); assertTrue( Hibernate.isInitialized( taskRef ) ); assertTrue( Hibernate.isInitialized( taskRef.getUser() ) ); assertTrue( Hibernate.isInitialized( taskRef.getResource() ) ); assertFalse( Hibernate.isInitialized( taskRef.getResource().getOwner() ) ); } ); } @Test public void testDynamicFetchScroll(SessionFactoryScope scope) { scope.inTransaction( session -> { Date now = new Date(); User me = new User( "me" ); User you = new User( "you" ); Resource yourClock = new Resource( "clock", you ); Task task = new Task( me, "clean", yourClock, now ); // :) session.persist( me ); session.persist( you ); session.persist( yourClock ); session.persist( task ); User u3 = new User( "U3" ); User u4 = new User( "U4" ); Resource it = new Resource( "it", u4 ); Task task2 = new Task( u3, "beat", it, now ); // :)) session.persist( u3 ); session.persist( u4 ); session.persist( it ); session.persist( task2 ); } ); scope.inStatelessTransaction( session -> { final Query query = session.createQuery( "from Task t join fetch t.resource join fetch t.user" ); try (ScrollableResults scrollableResults = query.scroll( ScrollMode.FORWARD_ONLY )) { while ( scrollableResults.next() ) { Task taskRef = (Task) scrollableResults.get(); assertTrue( Hibernate.isInitialized( taskRef ) ); assertTrue( Hibernate.isInitialized( taskRef.getUser() ) ); assertTrue( Hibernate.isInitialized( taskRef.getResource() ) ); assertFalse( Hibernate.isInitialized( taskRef.getResource().getOwner() ) ); } } } ); } @Test public void testDynamicFetchScrollSession(SessionFactoryScope scope) { scope.inTransaction( session -> { Date now = new Date(); User me = new User( "me" ); User you = new User( "you" ); Resource yourClock = new Resource( "clock", you ); Task task = new Task( me, "clean", yourClock, now ); // :) session.persist( me ); session.persist( you ); session.persist( yourClock ); session.persist( task ); User u3 = new User( "U3" ); User u4 = new User( "U4" ); Resource it = new Resource( "it", u4 ); Task task2 = new Task( u3, "beat", it, now ); // :)) session.persist( u3 ); session.persist( u4 ); session.persist( it ); session.persist( task2 ); } ); scope.inStatelessTransaction( session -> { final Query query = session.createQuery( "from Task t join fetch t.resource join fetch t.user" ); try (ScrollableResults scrollableResults = query.scroll( ScrollMode.FORWARD_ONLY )) { while ( scrollableResults.next() ) { Task taskRef = (Task) scrollableResults.get(); assertTrue( Hibernate.isInitialized( taskRef ) ); assertTrue( Hibernate.isInitialized( taskRef.getUser() ) ); assertTrue( Hibernate.isInitialized( taskRef.getResource() ) ); assertFalse( Hibernate.isInitialized( taskRef.getResource().getOwner() ) ); } } } ); } @Test public void testDynamicFetchCollectionScroll(SessionFactoryScope scope) { scope.inTransaction( session -> { Producer p1 = new Producer( 1, "Acme" ); Producer p2 = new Producer( 2, "ABC" ); session.persist( p1 ); session.persist( p2 ); Vendor v1 = new Vendor( 1, "v1" ); Vendor v2 = new Vendor( 2, "v2" ); session.persist( v1 ); session.persist( v2 ); final Product product1 = new Product( 1, "123", v1, p1 ); final Product product2 = new Product( 2, "456", v1, p1 ); final Product product3 = new Product( 3, "789", v1, p2 ); session.persist( product1 ); session.persist( product2 ); session.persist( product3 ); } ); scope.inStatelessTransaction( session -> { final Query query = session.createQuery( "select p from Producer p join fetch p.products" ); try (ScrollableResults scrollableResults = query.scroll( ScrollMode.FORWARD_ONLY )) { while ( scrollableResults.next() ) { Producer producer = (Producer) scrollableResults.get(); assertTrue( Hibernate.isInitialized( producer ) ); assertTrue( Hibernate.isInitialized( producer.getProducts() ) ); for ( Product product : producer.getProducts() ) { assertTrue( Hibernate.isInitialized( product ) ); assertFalse( Hibernate.isInitialized( product.getVendor() ) ); } } } } ); } @AfterEach public void cleanup(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } }
StatelessSessionFetchingTest
java
apache__spark
examples/src/main/java/org/apache/spark/examples/sql/streaming/JavaStructuredKafkaWordCount.java
{ "start": 2180, "end": 3479 }
class ____ { public static void main(String[] args) throws Exception { if (args.length < 3) { System.err.println("Usage: JavaStructuredKafkaWordCount <bootstrap-servers> " + "<subscribe-type> <topics>"); System.exit(1); } String bootstrapServers = args[0]; String subscribeType = args[1]; String topics = args[2]; SparkSession spark = SparkSession .builder() .appName("JavaStructuredKafkaWordCount") .getOrCreate(); // Create DataSet representing the stream of input lines from kafka Dataset<String> lines = spark .readStream() .format("kafka") .option("kafka.bootstrap.servers", bootstrapServers) .option(subscribeType, topics) .load() .selectExpr("CAST(value AS STRING)") .as(Encoders.STRING()); // Generate running word count Dataset<Row> wordCounts = lines.flatMap( (FlatMapFunction<String, String>) x -> Arrays.asList(x.split(" ")).iterator(), Encoders.STRING()).groupBy("value").count(); // Start running the query that prints the running counts to the console StreamingQuery query = wordCounts.writeStream() .outputMode("complete") .format("console") .start(); query.awaitTermination(); } }
JavaStructuredKafkaWordCount
java
elastic__elasticsearch
qa/evil-tests/src/test/java/org/elasticsearch/index/engine/EvilInternalEngineTests.java
{ "start": 7391, "end": 8058 }
class ____ extends MergeScheduler { private final MergeScheduler delegate; FilterMergeScheduler(MergeScheduler delegate) { this.delegate = delegate; } @Override public Directory wrapForMerge(MergePolicy.OneMerge merge, Directory in) { return delegate.wrapForMerge(merge, in); } @Override public void merge(MergeSource mergeSource, MergeTrigger trigger) throws IOException { delegate.merge(mergeSource, trigger); } @Override public void close() throws IOException { delegate.close(); } } static
FilterMergeScheduler
java
google__guice
core/test/com/google/inject/errors/MissingConstructorErrorTest.java
{ "start": 1406, "end": 1515 }
class ____ { private PrivateClassWithPrivateConstructor() {} } static
PrivateClassWithPrivateConstructor
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/SequenceFile.java
{ "start": 25985, "end": 27530 }
class ____ implements ValueBytes { private int dataSize; private byte[] data; DataInputBuffer rawData = null; CompressionCodec codec = null; CompressionInputStream decompressedStream = null; private CompressedBytes(CompressionCodec codec) { data = null; dataSize = 0; this.codec = codec; } private void reset(DataInputStream in, int length) throws IOException { if (data == null) { data = new byte[length]; } else if (length > data.length) { data = new byte[Math.max(length, data.length * 2)]; } dataSize = -1; in.readFully(data, 0, length); dataSize = length; } @Override public int getSize() { return dataSize; } @Override public void writeUncompressedBytes(DataOutputStream outStream) throws IOException { if (decompressedStream == null) { rawData = new DataInputBuffer(); decompressedStream = codec.createInputStream(rawData); } else { decompressedStream.resetState(); } rawData.reset(data, 0, dataSize); byte[] buffer = new byte[8192]; int bytesRead = 0; while ((bytesRead = decompressedStream.read(buffer, 0, 8192)) != -1) { outStream.write(buffer, 0, bytesRead); } } @Override public void writeCompressedBytes(DataOutputStream outStream) throws IllegalArgumentException, IOException { outStream.write(data, 0, dataSize); } } // CompressedBytes /** * The
CompressedBytes
java
elastic__elasticsearch
test/fixtures/gcs-fixture/src/main/java/fixture/gcs/MockGcsBlobStore.java
{ "start": 14237, "end": 14606 }
class ____ extends GcsRestException { BlobNotFoundException(String path) { super(RestStatus.NOT_FOUND, "Blob not found: " + path); } BlobNotFoundException(String path, long generation) { super(RestStatus.NOT_FOUND, "Blob not found: " + path + ", generation " + generation); } } static
BlobNotFoundException
java
junit-team__junit5
junit-platform-suite-api/src/main/java/org/junit/platform/suite/api/Suite.java
{ "start": 767, "end": 3425 }
class ____ a test suite on the JUnit Platform. * * <p>Selector and filter annotations are used to control the contents of the * suite. Additionally, configuration can be passed to the suite via the * configuration annotations. * * <p>When the {@link IncludeClassNamePatterns @IncludeClassNamePatterns} * annotation is not present, the default include pattern * {@value org.junit.platform.engine.discovery.ClassNameFilter#STANDARD_INCLUDE_PATTERN} * will be used in order to avoid loading classes unnecessarily (see {@link * org.junit.platform.engine.discovery.ClassNameFilter#STANDARD_INCLUDE_PATTERN * ClassNameFilter#STANDARD_INCLUDE_PATTERN}). * * <p>By default a suite discovers tests using the configuration parameters * explicitly configured by {@link ConfigurationParameter @ConfigurationParameter} * and the configuration parameters from the discovery request that discovered * the suite. Annotating a suite with * {@link DisableParentConfigurationParameters @DisableParentConfigurationParameters} * disables the latter as a source of parameters so that only explicit configuration * parameters are taken into account. * * <p>Note: Depending on the declared selectors, different suites may contain the * same tests, potentially with different configurations. Moreover, tests in a suite * are executed in addition to the tests executed by every other test engine, which * can result in the same tests being executed twice. To prevent that, configure * your build tool to include only the {@code junit-platform-suite} engine, or use * a custom naming pattern. For example, name all suites {@code *Suite} and all * tests {@code *Test}, and configure your build tool to include only the former. * Alternatively, consider using tags to select specific groups of tests. * * @since 1.8 * @see Select * @see SelectClasses * @see SelectClasspathResource * @see SelectDirectories * @see SelectFile * @see SelectModules * @see SelectPackages * @see SelectUris * @see IncludeClassNamePatterns * @see ExcludeClassNamePatterns * @see IncludeEngines * @see ExcludeEngines * @see IncludePackages * @see ExcludePackages * @see IncludeTags * @see ExcludeTags * @see SuiteDisplayName * @see ConfigurationParameter * @see ConfigurationParametersResource * @see DisableParentConfigurationParameters * @see org.junit.platform.launcher.LauncherDiscoveryRequest * @see org.junit.platform.launcher.core.LauncherDiscoveryRequestBuilder * @see org.junit.platform.launcher.Launcher */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) @Inherited @Documented @API(status = STABLE, since = "1.10") @Testable public @
as
java
apache__camel
core/camel-core-reifier/src/main/java/org/apache/camel/reifier/dataformat/RssDataFormatReifier.java
{ "start": 1026, "end": 1355 }
class ____ extends DataFormatReifier<RssDataFormat> { public RssDataFormatReifier(CamelContext camelContext, DataFormatDefinition definition) { super(camelContext, (RssDataFormat) definition); } @Override protected void prepareDataFormatConfig(Map<String, Object> properties) { } }
RssDataFormatReifier
java
google__guava
android/guava/src/com/google/common/base/CaseFormat.java
{ "start": 1161, "end": 2598 }
enum ____ { /** * Hyphenated variable naming convention, e.g., "lower-hyphen". This format is also colloquially * known as "kebab case". */ LOWER_HYPHEN(CharMatcher.is('-'), "-") { @Override String normalizeWord(String word) { return Ascii.toLowerCase(word); } @Override String convert(CaseFormat format, String s) { if (format == LOWER_UNDERSCORE) { return s.replace('-', '_'); } if (format == UPPER_UNDERSCORE) { return Ascii.toUpperCase(s.replace('-', '_')); } return super.convert(format, s); } }, /** C++ variable naming convention, e.g., "lower_underscore". */ LOWER_UNDERSCORE(CharMatcher.is('_'), "_") { @Override String normalizeWord(String word) { return Ascii.toLowerCase(word); } @Override String convert(CaseFormat format, String s) { if (format == LOWER_HYPHEN) { return s.replace('_', '-'); } if (format == UPPER_UNDERSCORE) { return Ascii.toUpperCase(s); } return super.convert(format, s); } }, /** Java variable naming convention, e.g., "lowerCamel". */ LOWER_CAMEL(CharMatcher.inRange('A', 'Z'), "") { @Override String normalizeWord(String word) { return firstCharOnlyToUpper(word); } @Override String normalizeFirstWord(String word) { return Ascii.toLowerCase(word); } }, /** Java and C++
CaseFormat
java
apache__camel
components/camel-seda/src/main/java/org/apache/camel/component/seda/SedaConsumerNotAvailableException.java
{ "start": 935, "end": 1203 }
class ____ extends CamelExchangeException { private static final long serialVersionUID = 683242306650809007L; public SedaConsumerNotAvailableException(String message, Exchange exchange) { super(message, exchange); } }
SedaConsumerNotAvailableException
java
junit-team__junit5
junit-platform-launcher/src/main/java/org/junit/platform/launcher/MethodFilter.java
{ "start": 783, "end": 3749 }
interface ____ extends PostDiscoveryFilter { /** * Create a new <em>include</em> {@link MethodFilter} based on the * supplied patterns. * * <p>The patterns are combined using OR semantics, i.e. if the fully * qualified name of a method matches against at least one of the patterns, * the method will be included in the result set. * * @param patterns regular expressions to match against fully qualified * method names; never {@code null}, empty, or containing {@code null} * @see Class#getName() * @see Method#getName() * @see #includeMethodNamePatterns(List) * @see #excludeMethodNamePatterns(String...) */ static MethodFilter includeMethodNamePatterns(String... patterns) { return new IncludeMethodFilter(patterns); } /** * Create a new <em>include</em> {@link MethodFilter} based on the * supplied patterns. * * <p>The patterns are combined using OR semantics, i.e. if the fully * qualified name of a method matches against at least one of the patterns, * the method will be included in the result set. * * @param patterns regular expressions to match against fully qualified * method names; never {@code null}, empty, or containing {@code null} * @see Class#getName() * @see Method#getName() * @see #includeMethodNamePatterns(String...) * @see #excludeMethodNamePatterns(String...) */ static MethodFilter includeMethodNamePatterns(List<String> patterns) { return includeMethodNamePatterns(patterns.toArray(new String[0])); } /** * Create a new <em>exclude</em> {@link MethodFilter} based on the * supplied patterns. * * <p>The patterns are combined using OR semantics, i.e. if the fully * qualified name of a method matches against at least one of the patterns, * the method will be excluded from the result set. * * @param patterns regular expressions to match against fully qualified * method names; never {@code null}, empty, or containing {@code null} * @see Class#getName() * @see Method#getName() * @see #excludeMethodNamePatterns(List) * @see #includeMethodNamePatterns(String...) */ static MethodFilter excludeMethodNamePatterns(String... patterns) { return new ExcludeMethodFilter(patterns); } /** * Create a new <em>exclude</em> {@link MethodFilter} based on the * supplied patterns. * * <p>The patterns are combined using OR semantics, i.e. if the fully * qualified name of a method matches against at least one of the patterns, * the method will be excluded from the result set. * * @param patterns regular expressions to match against fully qualified * method names; never {@code null}, empty, or containing {@code null} * @see Class#getName() * @see Method#getName() * @see #excludeMethodNamePatterns(String...) * @see #includeMethodNamePatterns(String...) */ static MethodFilter excludeMethodNamePatterns(List<String> patterns) { return excludeMethodNamePatterns(patterns.toArray(new String[0])); } }
MethodFilter
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/CriteriaWithDynamicInstantiationAndOrderByTest.java
{ "start": 8920, "end": 9289 }
class ____ { private Long a; private String b; private R3 r3; public R2(Long a, String b) { this.a = a; this.b = b; } public R2(Long a, String b, R3 r3) { this.a = a; this.b = b; this.r3 = r3; } public Long getA() { return a; } public String getB() { return b; } public R3 getR3() { return r3; } } public static
R2
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/aop/aspectj/autoproxy/AspectJAutoProxyCreatorTests.java
{ "start": 18962, "end": 19151 }
class ____ extends NestedRuntimeException { RetryableException(String msg) { super(msg); } RetryableException(String msg, Throwable cause) { super(msg, cause); } }
RetryableException
java
elastic__elasticsearch
x-pack/plugin/transform/src/main/java/org/elasticsearch/xpack/transform/checkpoint/TransformCheckpointService.java
{ "start": 1767, "end": 6221 }
class ____ { private static final Logger logger = LogManager.getLogger(TransformCheckpointService.class); private final Clock clock; private final TransformConfigManager transformConfigManager; private final TransformAuditor transformAuditor; private final RemoteClusterResolver remoteClusterResolver; public TransformCheckpointService( final Clock clock, final Settings settings, LinkedProjectConfigService linkedProjectConfigService, final TransformConfigManager transformConfigManager, TransformAuditor transformAuditor ) { this.clock = clock; this.transformConfigManager = transformConfigManager; this.transformAuditor = transformAuditor; this.remoteClusterResolver = new RemoteClusterResolver(settings, linkedProjectConfigService); } public CheckpointProvider getCheckpointProvider(final ParentTaskAssigningClient client, final TransformConfig transformConfig) { if (transformConfig.getSyncConfig() instanceof TimeSyncConfig) { return new TimeBasedCheckpointProvider( clock, client, remoteClusterResolver, transformConfigManager, transformAuditor, transformConfig ); } return new DefaultCheckpointProvider( clock, client, remoteClusterResolver, transformConfigManager, transformAuditor, transformConfig ); } /** * Get checkpointing stats for a stopped transform * * @param transformId The transform id * @param lastCheckpointNumber the last checkpoint * @param nextCheckpointPosition position for the next checkpoint * @param nextCheckpointProgress progress for the next checkpoint * @param listener listener to retrieve the result */ public void getCheckpointingInfo( final ParentTaskAssigningClient client, final TimeValue timeout, final String transformId, final long lastCheckpointNumber, final TransformIndexerPosition nextCheckpointPosition, final TransformProgress nextCheckpointProgress, final ActionListener<TransformCheckpointingInfoBuilder> listener ) { // we need to retrieve the config first before we can defer the rest to the corresponding provider transformConfigManager.getTransformConfiguration(transformId, ActionListener.wrap(transformConfig -> { getCheckpointProvider(client, transformConfig).getCheckpointingInfo( lastCheckpointNumber, nextCheckpointPosition, nextCheckpointProgress, timeout, listener ); }, transformError -> { logger.warn("Failed to retrieve configuration for transform [" + transformId + "]", transformError); listener.onFailure(new CheckpointException("Failed to retrieve configuration", transformError)); })); } /** * Derives basic checkpointing stats for a stopped transform. This does not make a call to obtain any additional information. * This will only read checkpointing information from the TransformState. * * @param transformState the current state of the Transform * @return basic checkpointing info, including id, position, and progress of the Next Checkpoint and the id of the Last Checkpoint. */ public static TransformCheckpointingInfo deriveBasicCheckpointingInfo(TransformState transformState) { return new TransformCheckpointingInfo(lastCheckpointStats(transformState), nextCheckpointStats(transformState), 0L, null, null); } private static TransformCheckpointStats lastCheckpointStats(TransformState transformState) { return new TransformCheckpointStats(transformState.getCheckpoint(), null, null, 0L, 0L); } private static TransformCheckpointStats nextCheckpointStats(TransformState transformState) { // getCheckpoint is the last checkpoint. if we're at zero then we'd only call to get the zeroth checkpoint (see getCheckpointInfo) var checkpoint = transformState.getCheckpoint() != 0 ? transformState.getCheckpoint() + 1 : 0; return new TransformCheckpointStats(checkpoint, transformState.getPosition(), transformState.getProgress(), 0L, 0L); } }
TransformCheckpointService
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/UtilsForTests.java
{ "start": 16397, "end": 16914 }
class ____ implements InputFormat<Text, Text> { public InputSplit[] getSplits(JobConf job, int numSplits) throws IOException { InputSplit[] result = new InputSplit[numSplits]; Path outDir = FileOutputFormat.getOutputPath(job); for(int i=0; i < result.length; ++i) { result[i] = new FileSplit(new Path(outDir, "dummy-split-" + i), 0, 1, (String[])null); } return result; } static
RandomInputFormat
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/inference/action/DeleteCCMConfigurationAction.java
{ "start": 1498, "end": 1629 }
class ____'t have any members at the moment so return the same hash code return Objects.hash(NAME); } } }
doesn
java
apache__kafka
clients/src/main/java/org/apache/kafka/clients/consumer/internals/AbstractPartitionAssignor.java
{ "start": 1627, "end": 2877 }
class ____ implements ConsumerPartitionAssignor { private static final Logger log = LoggerFactory.getLogger(AbstractPartitionAssignor.class); private static final Node[] NO_NODES = new Node[] {Node.noNode()}; // Used only in unit tests to verify rack-aware assignment when all racks have all partitions. boolean preferRackAwareLogic; /** * Perform the group assignment given the partition counts and member subscriptions * @param partitionsPerTopic The number of partitions for each subscribed topic. Topics not in metadata will be excluded * from this map. * @param subscriptions Map from the member id to their respective topic subscription * @return Map from each member to the list of partitions assigned to them. */ public abstract Map<String, List<TopicPartition>> assign(Map<String, Integer> partitionsPerTopic, Map<String, Subscription> subscriptions); /** * Default implementation of assignPartitions() that does not include racks. This is only * included to avoid breaking any custom implementation that extends AbstractPartitionAssignor. * Note that this
AbstractPartitionAssignor
java
spring-projects__spring-boot
module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/autoconfigure/RabbitAutoConfigurationTests.java
{ "start": 58710, "end": 59042 }
class ____ { private static final CredentialsRefreshService credentialsRefreshService = mock( CredentialsRefreshService.class); @Bean CredentialsRefreshService credentialsRefreshService() { return credentialsRefreshService; } } @Configuration(proxyBeanMethods = false) static
CredentialsRefreshServiceConfiguration
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/android/testdata/ParcelableCreatorPositiveCases.java
{ "start": 895, "end": 1167 }
class ____ implements Parcelable { public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int flags) { // no op } } // BUG: Diagnostic contains: ParcelableCreator public static
PublicParcelableClassWithoutCreator
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AbfsReadFooterMetrics.java
{ "start": 3513, "end": 3616 }
class ____ responsible for tracking and updating metrics related to reading footers in files. */ public
is
java
elastic__elasticsearch
x-pack/plugin/eql/src/main/java/org/elasticsearch/xpack/eql/expression/OptionalResolvedAttribute.java
{ "start": 732, "end": 2190 }
class ____ extends FieldAttribute { public OptionalResolvedAttribute(FieldAttribute fa) { this(fa.source(), fa.parent(), fa.name(), fa.dataType(), fa.field(), fa.qualifier(), fa.nullable(), fa.id(), fa.synthetic()); } public OptionalResolvedAttribute( Source source, FieldAttribute parent, String name, DataType type, EsField field, String qualifier, Nullability nullability, NameId id, boolean synthetic ) { super(source, parent, name, type, field, qualifier, nullability, id, synthetic); } @Override protected NodeInfo<FieldAttribute> info() { return NodeInfo.create( this, OptionalResolvedAttribute::new, parent(), name(), dataType(), field(), qualifier(), nullable(), id(), synthetic() ); } @Override protected Attribute clone( Source source, String name, DataType type, String qualifier, Nullability nullability, NameId id, boolean synthetic ) { FieldAttribute qualifiedParent = parent() != null ? (FieldAttribute) parent().withQualifier(qualifier) : null; return new OptionalResolvedAttribute(source, qualifiedParent, name, type, field(), qualifier, nullability, id, synthetic); } }
OptionalResolvedAttribute
java
grpc__grpc-java
rls/src/main/java/io/grpc/rls/Throttler.java
{ "start": 759, "end": 1648 }
interface ____ { /** * Checks if a given request should be throttled by the client. This should be called for every * request before allowing it to hit the network. If the returned value is true, the request * should be aborted immediately (as if it had been throttled by the server). * * <p>This updates internal state and should be called exactly once for each request. */ boolean shouldThrottle(); /** * Registers a response received from the backend for a request allowed by shouldThrottle. This * should be called for every response received from the backend (i.e., once for each request for * which ShouldThrottle returned false). This updates the internal statistics used by * shouldThrottle. * * @param throttled specifies whether the request was throttled by the backend. */ void registerBackendResponse(boolean throttled); }
Throttler
java
alibaba__fastjson
src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectP_A.java
{ "start": 72, "end": 725 }
class ____ { private int a; private int b; private int c; private boolean d; private boolean e; private boolean f; public int getA() { return a; } public void setA(int a) { this.a = a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public void setC(int c) { this.c = c; } public boolean isD() { return d; } public void setD(boolean d) { this.d = d; } public boolean isE() { return e; } public void setE(boolean e) { this.e = e; } public boolean isF() { return f; } public void setF(boolean f) { this.f = f; } }
ObjectP_A
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/type/descriptor/java/EnumJavaType.java
{ "start": 6554, "end": 6745 }
enum ____ to its name value */ public String toName(T domainForm) { return domainForm == null ? null : domainForm.name(); } /** * Interpret a string value as the named value of the
type
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/jpa/criteria/basic/Wall.java
{ "start": 471, "end": 1354 }
class ____ { private Long id; private long width; private long height; private String color; private Wall left; private Wall right; @Id @GeneratedValue public Long getId() { return id; } public void setId(Long id) { this.id = id; } public long getWidth() { return width; } public void setWidth(long width) { this.width = width; } public long getHeight() { return height; } public void setHeight(long height) { this.height = height; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } @ManyToOne @JoinColumn(name = "left_id") public Wall getLeft() { return left; } public void setLeft(Wall left) { this.left = left; } @ManyToOne @JoinColumn(name = "right_id") public Wall getRight() { return right; } public void setRight(Wall right) { this.right = right; } }
Wall
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/error/MessageFormatter_format_Test.java
{ "start": 1421, "end": 3248 }
class ____ { private DescriptionFormatter descriptionFormatter; private MessageFormatter messageFormatter; @BeforeEach public void setUp() { descriptionFormatter = spy(new DescriptionFormatter()); messageFormatter = new MessageFormatter(); messageFormatter.descriptionFormatter = descriptionFormatter; } @Test void should_throw_error_if_format_string_is_null() { thenNullPointerException().isThrownBy(() -> messageFormatter.format(null, null, null)); } @Test void should_throw_error_if_args_array_is_null() { Object[] args = null; thenNullPointerException().isThrownBy(() -> messageFormatter.format(null, null, "", args)); } @Test void should_format_message() { // GIVEN Description description = new TextDescription("Test"); // WHEN String s = messageFormatter.format(description, STANDARD_REPRESENTATION, "Hello %s", "World"); // THEN then(s).isEqualTo("[Test] Hello \"World\""); verify(descriptionFormatter).format(description); } @ParameterizedTest @MethodSource("messages") void should_format_message_and_correctly_escape_percentage(String input, String formatted) { // GIVEN Description description = new TextDescription("Test"); // WHEN String finalMessage = messageFormatter.format(description, STANDARD_REPRESENTATION, input); // THEN then(finalMessage).isEqualTo("[Test] " + formatted); } public static Stream<Arguments> messages() { return Stream.of(arguments("%E", "%E"), arguments("%%E", "%%E"), arguments("%%%E", "%%%E"), arguments("%n", "%n".formatted()), arguments("%%%n%E", "%%" + "%n".formatted() + "%E"), arguments("%%n", "%" + "%n".formatted())); } }
MessageFormatter_format_Test
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/inject/ast/UnresolvedTypeKind.java
{ "start": 1245, "end": 1292 }
class ____ reference. */ SUPERCLASS }
type
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/SQLCommentStatementTest.java
{ "start": 225, "end": 626 }
class ____ extends TestCase { public void test_0() throws Exception { String sql = "COMMENT on table t1 IS 'xxx'"; SQLStatementParser parser = new SQLStatementParser(sql); SQLStatement stmt = parser.parseStatementList().get(0); String text = TestUtils.outputSqlServer(stmt); assertEquals("COMMENT ON TABLE t1 IS 'xxx'", text); } }
SQLCommentStatementTest
java
elastic__elasticsearch
x-pack/plugin/slm/src/main/java/org/elasticsearch/xpack/slm/action/ReservedSnapshotAction.java
{ "start": 1535, "end": 5245 }
class ____ implements ReservedClusterStateHandler<List<SnapshotLifecyclePolicy>> { public static final String NAME = "slm"; @Override public String name() { return NAME; } private Collection<PutSnapshotLifecycleAction.Request> prepare(List<SnapshotLifecyclePolicy> policies, ClusterState state) { List<PutSnapshotLifecycleAction.Request> result = new ArrayList<>(); List<Exception> exceptions = new ArrayList<>(); for (var policy : policies) { PutSnapshotLifecycleAction.Request request = new PutSnapshotLifecycleAction.Request( RESERVED_CLUSTER_STATE_HANDLER_IGNORED_TIMEOUT, RESERVED_CLUSTER_STATE_HANDLER_IGNORED_TIMEOUT, policy.getId(), policy ); try { validate(request); SnapshotLifecycleService.validateRepositoryExists(request.getLifecycle().getRepository(), state); SnapshotLifecycleService.validateMinimumInterval(request.getLifecycle(), state); result.add(request); } catch (Exception e) { exceptions.add(e); } } if (exceptions.isEmpty() == false) { var illegalArgumentException = new IllegalArgumentException("Error on validating SLM requests"); exceptions.forEach(illegalArgumentException::addSuppressed); throw illegalArgumentException; } return result; } @Override public TransformState transform(List<SnapshotLifecyclePolicy> source, TransformState prevState) throws Exception { var requests = prepare(source, prevState.state()); ClusterState state = prevState.state(); for (var request : requests) { TransportPutSnapshotLifecycleAction.UpdateSnapshotPolicyTask task = new TransportPutSnapshotLifecycleAction.UpdateSnapshotPolicyTask(request); state = task.execute(state); } Set<String> entities = requests.stream().map(r -> r.getLifecycle().getId()).collect(Collectors.toSet()); Set<String> toDelete = new HashSet<>(prevState.keys()); toDelete.removeAll(entities); for (var policyToDelete : toDelete) { var task = new TransportDeleteSnapshotLifecycleAction.DeleteSnapshotPolicyTask( new DeleteSnapshotLifecycleAction.Request( RESERVED_CLUSTER_STATE_HANDLER_IGNORED_TIMEOUT, RESERVED_CLUSTER_STATE_HANDLER_IGNORED_TIMEOUT, policyToDelete ), ActionListener.noop() ); state = task.execute(state); } return new TransformState(state, entities); } @Override public ClusterState remove(TransformState prevState) throws Exception { return transform(List.of(), prevState).state(); } @Override public List<SnapshotLifecyclePolicy> fromXContent(XContentParser parser) throws IOException { List<SnapshotLifecyclePolicy> result = new ArrayList<>(); Map<String, ?> source = parser.map(); for (String name : source.keySet()) { @SuppressWarnings("unchecked") Map<String, ?> content = (Map<String, ?>) source.get(name); try (XContentParser policyParser = mapToXContentParser(XContentParserConfiguration.EMPTY, content)) { result.add(SnapshotLifecyclePolicy.parse(policyParser, name)); } } return result; } @Override public Collection<String> optionalDependencies() { return List.of("snapshot_repositories"); } }
ReservedSnapshotAction
java
apache__camel
components/camel-leveldb/src/test/java/org/apache/camel/component/leveldb/LevelDBAggregateRecoverWithSedaTest.java
{ "start": 1436, "end": 4541 }
class ____ extends LevelDBTestSupport { private static Map<SerializerType, AtomicInteger> counters = new ConcurrentHashMap(); private static AtomicInteger getCounter(SerializerType serializerType) { AtomicInteger counter = counters.get(serializerType); if (counter == null) { counter = new AtomicInteger(); counters.put(serializerType, counter); } return counter; } @Override public void doPreSetup() throws Exception { deleteDirectory("target/data"); } @Test public void testLevelDBAggregateRecoverWithSeda() throws Exception { // should fail the first 2 times and then recover getMockEndpoint("mock:aggregated").expectedMessageCount(3); getMockEndpoint("mock:result").expectedBodiesReceived("ABCDE"); // should be marked as redelivered getMockEndpoint("mock:result").message(0).header(Exchange.REDELIVERED).isEqualTo(Boolean.TRUE); // on the 2nd redelivery attempt we success getMockEndpoint("mock:result").message(0).header(Exchange.REDELIVERY_COUNTER).isEqualTo(2); template.sendBodyAndHeader("direct:start", "A", "id", 123); template.sendBodyAndHeader("direct:start", "B", "id", 123); template.sendBodyAndHeader("direct:start", "C", "id", 123); template.sendBodyAndHeader("direct:start", "D", "id", 123); template.sendBodyAndHeader("direct:start", "E", "id", 123); MockEndpoint.assertIsSatisfied(context, 30, TimeUnit.SECONDS); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // enable recovery LevelDBAggregationRepository repo = getRepo(); repo.setUseRecovery(true); // check faster repo.setRecoveryInterval(500, TimeUnit.MILLISECONDS); from("direct:start") .aggregate(header("id"), new StringAggregationStrategy()) .completionSize(5).aggregationRepository(repo) .to("mock:aggregated") .to("seda:foo") .end(); // should be able to recover when we send over SEDA as its a OnCompletion // which confirms the exchange when its complete. from("seda:foo") .delay(1000) // simulate errors the first two times .process(new Processor() { public void process(Exchange exchange) { int count = getCounter(getSerializerType()).incrementAndGet(); if (count <= 2) { throw new IllegalArgumentException("Damn"); } } }) .to("mock:result"); } }; } }
LevelDBAggregateRecoverWithSedaTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/test/java/org/apache/hadoop/hdfs/server/federation/router/TestConnectionManager.java
{ "start": 2137, "end": 16871 }
class ____ { private Configuration conf; private ConnectionManager connManager; private static final String[] TEST_GROUP = new String[]{"TEST_GROUP"}; private static final UserGroupInformation TEST_USER1 = UserGroupInformation.createUserForTesting("user1", TEST_GROUP); private static final UserGroupInformation TEST_USER2 = UserGroupInformation.createUserForTesting("user2", TEST_GROUP); private static final UserGroupInformation TEST_USER3 = UserGroupInformation.createUserForTesting("user3", TEST_GROUP); private static final String TEST_NN_ADDRESS = "nn1:8080"; private static final String UNRESOLVED_TEST_NN_ADDRESS = "unknownhost:8080"; @BeforeEach public void setup() throws Exception { conf = new Configuration(); connManager = new ConnectionManager(conf); NetUtils.addStaticResolution("nn1", "localhost"); NetUtils.createSocketAddrForHost("nn1", 8080); connManager.start(); } @AfterEach public void shutdown() { if (connManager != null) { connManager.close(); } } @Test public void testCleanup() throws Exception { Map<ConnectionPoolId, ConnectionPool> poolMap = connManager.getPools(); ConnectionPool pool1 = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER1, 0, 10, 0.5f, ClientProtocol.class, null); addConnectionsToPool(pool1, 9, 4); poolMap.put( new ConnectionPoolId(TEST_USER1, TEST_NN_ADDRESS, ClientProtocol.class), pool1); ConnectionPool pool2 = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER2, 0, 10, 0.5f, ClientProtocol.class, null); addConnectionsToPool(pool2, 10, 10); poolMap.put( new ConnectionPoolId(TEST_USER2, TEST_NN_ADDRESS, ClientProtocol.class), pool2); checkPoolConnections(TEST_USER1, 9, 4); checkPoolConnections(TEST_USER2, 10, 10); // Clean up first pool, one connection should be removed, and second pool // should remain the same. connManager.cleanup(pool1); checkPoolConnections(TEST_USER1, 8, 4); checkPoolConnections(TEST_USER2, 10, 10); // Clean up the first pool again, it should have no effect since it reached // the MIN_ACTIVE_RATIO. connManager.cleanup(pool1); checkPoolConnections(TEST_USER1, 8, 4); checkPoolConnections(TEST_USER2, 10, 10); // Make sure the number of connections doesn't go below minSize ConnectionPool pool3 = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER3, 2, 10, 0.5f, ClientProtocol.class, null); addConnectionsToPool(pool3, 8, 0); poolMap.put( new ConnectionPoolId(TEST_USER3, TEST_NN_ADDRESS, ClientProtocol.class), pool3); checkPoolConnections(TEST_USER3, 10, 0); for (int i = 0; i < 10; i++) { connManager.cleanup(pool3); } checkPoolConnections(TEST_USER3, 2, 0); // With active connections added to pool, make sure it honors the // MIN_ACTIVE_RATIO again addConnectionsToPool(pool3, 8, 2); checkPoolConnections(TEST_USER3, 10, 2); for (int i = 0; i < 10; i++) { connManager.cleanup(pool3); } checkPoolConnections(TEST_USER3, 4, 2); } @Test public void testGetConnectionWithConcurrency() throws Exception { Map<ConnectionPoolId, ConnectionPool> poolMap = connManager.getPools(); Configuration copyConf = new Configuration(conf); copyConf.setInt(RBFConfigKeys.DFS_ROUTER_MAX_CONCURRENCY_PER_CONNECTION_KEY, 20); ConnectionPool pool = new ConnectionPool( copyConf, TEST_NN_ADDRESS, TEST_USER1, 1, 10, 0.5f, ClientProtocol.class, null); poolMap.put( new ConnectionPoolId(TEST_USER1, TEST_NN_ADDRESS, ClientProtocol.class), pool); assertEquals(1, pool.getNumConnections()); // one connection can process the maximum number of requests concurrently. for (int i = 0; i < 20; i++) { ConnectionContext cc = pool.getConnection(); assertTrue(cc.isUsable()); cc.getClient(); } assertEquals(1, pool.getNumConnections()); // Ask for more and this returns an unusable connection ConnectionContext cc1 = pool.getConnection(); assertTrue(cc1.isActive()); assertFalse(cc1.isUsable()); // add a new connection into pool pool.addConnection(pool.newConnection()); // will return the new connection ConnectionContext cc2 = pool.getConnection(); assertTrue(cc2.isUsable()); cc2.getClient(); assertEquals(2, pool.getNumConnections()); checkPoolConnections(TEST_USER1, 2, 2); } @Test public void testConnectionCreatorWithException() throws Exception { // Create a bad connection pool pointing to unresolvable namenode address. ConnectionPool badPool = new ConnectionPool( conf, UNRESOLVED_TEST_NN_ADDRESS, TEST_USER1, 0, 10, 0.5f, ClientProtocol.class, null); BlockingQueue<ConnectionPool> queue = new ArrayBlockingQueue<>(1); queue.add(badPool); ConnectionManager.ConnectionCreator connectionCreator = new ConnectionManager.ConnectionCreator(queue); connectionCreator.setDaemon(true); connectionCreator.start(); // Wait to make sure async thread is scheduled and picks GenericTestUtils.waitFor(queue::isEmpty, 50, 5000); // At this point connection creation task should be definitely picked up. assertTrue(queue.isEmpty()); // At this point connection thread should still be alive. assertTrue(connectionCreator.isAlive()); // Stop the thread as test is successful at this point connectionCreator.interrupt(); } @Test public void testGetConnectionWithException() throws Exception { String exceptionCause = "java.net.UnknownHostException: unknownhost"; assertThrows(IllegalArgumentException.class, () -> { // Create a bad connection pool pointing to unresolvable namenode address. ConnectionPool badPool = new ConnectionPool( conf, UNRESOLVED_TEST_NN_ADDRESS, TEST_USER1, 1, 10, 0.5f, ClientProtocol.class, null); }, exceptionCause); } @Test public void testGetConnection() throws Exception { Map<ConnectionPoolId, ConnectionPool> poolMap = connManager.getPools(); final int totalConns = 10; int activeConns = 5; ConnectionPool pool = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER1, 0, 10, 0.5f, ClientProtocol.class, null); addConnectionsToPool(pool, totalConns, activeConns); poolMap.put( new ConnectionPoolId(TEST_USER1, TEST_NN_ADDRESS, ClientProtocol.class), pool); // All remaining connections should be usable final int remainingSlots = totalConns - activeConns; for (int i = 0; i < remainingSlots; i++) { ConnectionContext cc = pool.getConnection(); assertTrue(cc.isUsable()); cc.getClient(); activeConns++; } checkPoolConnections(TEST_USER1, totalConns, activeConns); // Ask for more and this returns an active connection ConnectionContext cc = pool.getConnection(); assertTrue(cc.isActive()); } @Test public void testValidClientIndex() throws Exception { ConnectionPool pool = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER1, 2, 2, 0.5f, ClientProtocol.class, null); for(int i = -3; i <= 3; i++) { pool.getClientIndex().set(i); ConnectionContext conn = pool.getConnection(); assertNotNull(conn); assertTrue(conn.isUsable()); } } @Test public void getGetConnectionNamenodeProtocol() throws Exception { Map<ConnectionPoolId, ConnectionPool> poolMap = connManager.getPools(); final int totalConns = 10; int activeConns = 5; ConnectionPool pool = new ConnectionPool(conf, TEST_NN_ADDRESS, TEST_USER1, 0, 10, 0.5f, NamenodeProtocol.class, null); addConnectionsToPool(pool, totalConns, activeConns); poolMap.put( new ConnectionPoolId( TEST_USER1, TEST_NN_ADDRESS, NamenodeProtocol.class), pool); // All remaining connections should be usable final int remainingSlots = totalConns - activeConns; for (int i = 0; i < remainingSlots; i++) { ConnectionContext cc = pool.getConnection(); assertTrue(cc.isUsable()); cc.getClient(); activeConns++; } checkPoolConnections(TEST_USER1, totalConns, activeConns); // Ask for more and this returns an active connection ConnectionContext cc = pool.getConnection(); assertTrue(cc.isActive()); } private void addConnectionsToPool(ConnectionPool pool, int numTotalConn, int numActiveConn) throws IOException { for (int i = 0; i < numTotalConn; i++) { ConnectionContext cc = pool.newConnection(); pool.addConnection(cc); if (i < numActiveConn) { cc.getClient(); } } } private void checkPoolConnections(UserGroupInformation ugi, int numOfConns, int numOfActiveConns) { boolean connPoolFoundForUser = false; for (Map.Entry<ConnectionPoolId, ConnectionPool> e : connManager.getPools().entrySet()) { if (e.getKey().getUgi() == ugi) { assertEquals(numOfConns, e.getValue().getNumConnections()); assertEquals(numOfActiveConns, e.getValue().getNumActiveConnections()); // idle + active = total connections assertEquals(numOfConns - numOfActiveConns, e.getValue().getNumIdleConnections()); connPoolFoundForUser = true; } } if (!connPoolFoundForUser) { fail("Connection pool not found for user " + ugi.getUserName()); } } @Test public void testAdvanceClientStateId() throws IOException { // Start one ConnectionManager Configuration tmpConf = new Configuration(); ConnectionManager tmpConnManager = new ConnectionManager(tmpConf); tmpConnManager.start(); Map<ConnectionPoolId, ConnectionPool> poolMap = tmpConnManager.getPools(); // Mock one Server.Call with FederatedNamespaceState that ns0 = 1L. Server.Call mockCall1 = new Server.Call(1, 1, null, null, RPC.RpcKind.RPC_BUILTIN, new byte[] {1, 2, 3}); Map<String, Long> nsStateId = new HashMap<>(); nsStateId.put("ns0", 1L); RouterFederatedStateProto.Builder stateBuilder = RouterFederatedStateProto.newBuilder(); nsStateId.forEach(stateBuilder::putNamespaceStateIds); mockCall1.setFederatedNamespaceState(stateBuilder.build().toByteString()); Server.getCurCall().set(mockCall1); // Create one new connection pool tmpConnManager.getConnection(TEST_USER1, TEST_NN_ADDRESS, NamenodeProtocol.class, "ns0"); assertEquals(1, poolMap.size()); ConnectionPoolId connectionPoolId = new ConnectionPoolId(TEST_USER1, TEST_NN_ADDRESS, NamenodeProtocol.class); ConnectionPool pool = poolMap.get(connectionPoolId); assertEquals(1L, pool.getPoolAlignmentContext().getPoolLocalStateId()); // Mock one Server.Call with FederatedNamespaceState that ns0 = 2L. Server.Call mockCall2 = new Server.Call(2, 1, null, null, RPC.RpcKind.RPC_BUILTIN, new byte[] {1, 2, 3}); nsStateId.clear(); nsStateId.put("ns0", 2L); stateBuilder = RouterFederatedStateProto.newBuilder(); nsStateId.forEach(stateBuilder::putNamespaceStateIds); mockCall2.setFederatedNamespaceState(stateBuilder.build().toByteString()); Server.getCurCall().set(mockCall2); // Get one existed connection for ns0 tmpConnManager.getConnection(TEST_USER1, TEST_NN_ADDRESS, NamenodeProtocol.class, "ns0"); assertEquals(1, poolMap.size()); pool = poolMap.get(connectionPoolId); assertEquals(2L, pool.getPoolAlignmentContext().getPoolLocalStateId()); } @Test public void testConfigureConnectionActiveRatio() throws IOException { // test 1 conn below the threshold and these conns are closed testConnectionCleanup(0.8f, 10, 7, 9); // test 2 conn below the threshold and these conns are closed testConnectionCleanup(0.8f, 10, 6, 8); } @Test public void testConnectionCreatorWithSamePool() throws IOException { Configuration tmpConf = new Configuration(); // Set DFS_ROUTER_MAX_CONCURRENCY_PER_CONNECTION_KEY to 0 // for ensuring a pool will be offered in the creatorQueue tmpConf.setInt( RBFConfigKeys.DFS_ROUTER_MAX_CONCURRENCY_PER_CONNECTION_KEY, 0); ConnectionManager tmpConnManager = new ConnectionManager(tmpConf); tmpConnManager.start(); // Close ConnectionCreator thread to make sure that new connection will not initialize. tmpConnManager.closeConnectionCreator(); // Create same connection pool for simulating concurrency scenario for (int i = 0; i < 3; i++) { tmpConnManager.getConnection(TEST_USER1, TEST_NN_ADDRESS, NamenodeProtocol.class, "ns0"); } assertEquals(1, tmpConnManager.getNumCreatingConnections()); tmpConnManager.getConnection(TEST_USER2, TEST_NN_ADDRESS, NamenodeProtocol.class, "ns0"); assertEquals(2, tmpConnManager.getNumCreatingConnections()); } private void testConnectionCleanup(float ratio, int totalConns, int activeConns, int leftConns) throws IOException { Configuration tmpConf = new Configuration(); // Set dfs.federation.router.connection.min-active-ratio tmpConf.setFloat( RBFConfigKeys.DFS_ROUTER_NAMENODE_CONNECTION_MIN_ACTIVE_RATIO, ratio); ConnectionManager tmpConnManager = new ConnectionManager(tmpConf); tmpConnManager.start(); // Create one new connection pool tmpConnManager.getConnection(TEST_USER1, TEST_NN_ADDRESS, NamenodeProtocol.class, "ns0"); Map<ConnectionPoolId, ConnectionPool> poolMap = tmpConnManager.getPools(); ConnectionPoolId connectionPoolId = new ConnectionPoolId(TEST_USER1, TEST_NN_ADDRESS, NamenodeProtocol.class); ConnectionPool pool = poolMap.get(connectionPoolId); // Test min active ratio is as set value assertEquals(ratio, pool.getMinActiveRatio(), 0.001f); pool.getConnection().getClient(); // Test there is one active connection in pool assertEquals(1, pool.getNumActiveConnections()); // Add other active-1 connections / totalConns-1 connections to pool addConnectionsToPool(pool, totalConns - 1, activeConns - 1); // There are activeConn connections. // We can cleanup the pool tmpConnManager.cleanup(pool); assertEquals(leftConns, pool.getNumConnections()); tmpConnManager.close(); } @Test public void testUnsupportedProtoExceptionMsg() throws Exception { LambdaTestUtils.intercept(IllegalStateException.class, "Unsupported protocol for connection to NameNode: " + TestConnectionManager.class.getName(), () -> ConnectionPool.newConnection(conf, TEST_NN_ADDRESS, TEST_USER1, TestConnectionManager.class, false, 0, null)); } }
TestConnectionManager
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/services/ITestReadBufferManagerV2.java
{ "start": 1893, "end": 6192 }
class ____ extends AbstractAbfsIntegrationTest { private static final int LESS_NUM_FILES = 2; private static final int MORE_NUM_FILES = 5; private static final int SMALL_FILE_SIZE = 6 * ONE_MB; private static final int LARGE_FILE_SIZE = 50 * ONE_MB; private static final int BLOCK_SIZE = 4 * ONE_MB; public ITestReadBufferManagerV2() throws Exception { } @Test public void testReadDifferentFilesInParallel() throws Exception { try (AzureBlobFileSystem fs = getConfiguredFileSystem()) { int fileSize = LARGE_FILE_SIZE; int numFiles = MORE_NUM_FILES; byte[] fileContent = getRandomBytesArray(fileSize); Path[] testPaths = new Path[numFiles]; int[] idx = {0}; for (int i = 0; i < numFiles; i++) { final String fileName = methodName.getMethodName() + i; testPaths[i] = createFileWithContent(fs, fileName, fileContent); } ExecutorService executorService = Executors.newFixedThreadPool(numFiles); Map<String, Long> metricMap = getInstrumentationMap(fs); long requestsMadeBeforeTest = metricMap .get(CONNECTIONS_MADE.getStatName()); try { for (int i = 0; i < numFiles; i++) { executorService.submit((Callable<Void>) () -> { try (FSDataInputStream iStream = fs.open(testPaths[idx[0]++])) { byte[] buffer = new byte[fileSize]; int bytesRead = iStream.read(buffer, 0, fileSize); assertThat(bytesRead).isEqualTo(fileSize); assertThat(buffer).isEqualTo(fileContent); } return null; }); } } finally { executorService.shutdown(); // wait for all tasks to finish executorService.awaitTermination(1, TimeUnit.MINUTES); } metricMap = getInstrumentationMap(fs); long requestsMadeAfterTest = metricMap .get(CONNECTIONS_MADE.getStatName()); int expectedRequests = numFiles // Get Path Status for each file + ((int) Math.ceil((double) fileSize / BLOCK_SIZE)) * numFiles; // Read requests for each file assertEquals(expectedRequests, requestsMadeAfterTest - requestsMadeBeforeTest); } } @Test public void testReadSameFileInParallel() throws Exception { try (AzureBlobFileSystem fs = getConfiguredFileSystem()) { int fileSize = SMALL_FILE_SIZE; int numFiles = LESS_NUM_FILES; byte[] fileContent = getRandomBytesArray(fileSize); final String fileName = methodName.getMethodName(); Path testPath = createFileWithContent(fs, fileName, fileContent); ExecutorService executorService = Executors.newFixedThreadPool(numFiles); Map<String, Long> metricMap = getInstrumentationMap(fs); long requestsMadeBeforeTest = metricMap .get(CONNECTIONS_MADE.getStatName()); try { for (int i = 0; i < numFiles; i++) { executorService.submit((Callable<Void>) () -> { try (FSDataInputStream iStream = fs.open(testPath)) { byte[] buffer = new byte[fileSize]; int bytesRead = iStream.read(buffer, 0, fileSize); assertThat(bytesRead).isEqualTo(fileSize); assertThat(buffer).isEqualTo(fileContent); } return null; }); } } finally { executorService.shutdown(); // wait for all tasks to finish executorService.awaitTermination(1, TimeUnit.MINUTES); } metricMap = getInstrumentationMap(fs); long requestsMadeAfterTest = metricMap .get(CONNECTIONS_MADE.getStatName()); int expectedRequests = numFiles // Get Path Status for each file + ((int) Math.ceil( (double) fileSize / BLOCK_SIZE)); // Read requests for each file assertEquals(expectedRequests, requestsMadeAfterTest - requestsMadeBeforeTest); } } private AzureBlobFileSystem getConfiguredFileSystem() throws Exception { Configuration config = new Configuration(getRawConfiguration()); config.set(FS_AZURE_ENABLE_READAHEAD_V2, TRUE); config.set(FS_AZURE_ENABLE_READAHEAD_V2_DYNAMIC_SCALING, TRUE); AzureBlobFileSystem fs = (AzureBlobFileSystem) FileSystem.newInstance(config); return fs; } }
ITestReadBufferManagerV2
java
netty__netty
codec-base/src/test/java/io/netty/handler/codec/DatagramPacketDecoderTest.java
{ "start": 2670, "end": 3153 }
class ____ extends MessageToMessageDecoder<ByteBuf> { private final boolean sharable; TestMessageToMessageDecoder(boolean sharable) { this.sharable = sharable; } @Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { // NOOP } @Override public boolean isSharable() { return sharable; } } }
TestMessageToMessageDecoder
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/SequenceFileOutputFormat.java
{ "start": 1603, "end": 4668 }
class ____ <K,V> extends FileOutputFormat<K, V> { public RecordWriter<K, V> getRecordWriter( FileSystem ignored, JobConf job, String name, Progressable progress) throws IOException { // get the path of the temporary output file Path file = FileOutputFormat.getTaskOutputPath(job, name); FileSystem fs = file.getFileSystem(job); CompressionCodec codec = null; CompressionType compressionType = CompressionType.NONE; if (getCompressOutput(job)) { // find the kind of compression to do compressionType = getOutputCompressionType(job); // find the right codec Class<? extends CompressionCodec> codecClass = getOutputCompressorClass(job, DefaultCodec.class); codec = ReflectionUtils.newInstance(codecClass, job); } final SequenceFile.Writer out = SequenceFile.createWriter(fs, job, file, job.getOutputKeyClass(), job.getOutputValueClass(), compressionType, codec, progress); return new RecordWriter<K, V>() { public void write(K key, V value) throws IOException { out.append(key, value); } public void close(Reporter reporter) throws IOException { out.close();} }; } /** Open the output generated by this format. */ public static SequenceFile.Reader[] getReaders(Configuration conf, Path dir) throws IOException { FileSystem fs = dir.getFileSystem(conf); Path[] names = FileUtil.stat2Paths(fs.listStatus(dir)); // sort names, so that hash partitioning works Arrays.sort(names); SequenceFile.Reader[] parts = new SequenceFile.Reader[names.length]; for (int i = 0; i < names.length; i++) { parts[i] = new SequenceFile.Reader(fs, names[i], conf); } return parts; } /** * Get the {@link CompressionType} for the output {@link SequenceFile}. * @param conf the {@link JobConf} * @return the {@link CompressionType} for the output {@link SequenceFile}, * defaulting to {@link CompressionType#RECORD} */ public static CompressionType getOutputCompressionType(JobConf conf) { String val = conf.get(org.apache.hadoop.mapreduce.lib.output. FileOutputFormat.COMPRESS_TYPE, CompressionType.RECORD.toString()); return CompressionType.valueOf(val); } /** * Set the {@link CompressionType} for the output {@link SequenceFile}. * @param conf the {@link JobConf} to modify * @param style the {@link CompressionType} for the output * {@link SequenceFile} */ public static void setOutputCompressionType(JobConf conf, CompressionType style) { setCompressOutput(conf, true); conf.set(org.apache.hadoop.mapreduce.lib.output. FileOutputFormat.COMPRESS_TYPE, style.toString()); } }
SequenceFileOutputFormat
java
spring-projects__spring-boot
build-plugin/spring-boot-gradle-plugin/src/main/java/org/springframework/boot/gradle/plugin/KotlinPluginAction.java
{ "start": 1251, "end": 2526 }
class ____ implements PluginApplicationAction { @Override public void execute(Project project) { configureKotlinVersionProperty(project); enableJavaParametersOption(project); repairDamageToAotCompileConfigurations(project); } private void configureKotlinVersionProperty(Project project) { ExtraPropertiesExtension extraProperties = project.getExtensions().getExtraProperties(); if (!extraProperties.has("kotlin.version")) { String kotlinVersion = getKotlinVersion(project); extraProperties.set("kotlin.version", kotlinVersion); } } private String getKotlinVersion(Project project) { return KotlinPluginWrapperKt.getKotlinPluginVersion(project); } private void enableJavaParametersOption(Project project) { project.getTasks() .withType(KotlinCompile.class) .configureEach((compile) -> compile.getCompilerOptions().getJavaParameters().set(true)); } private void repairDamageToAotCompileConfigurations(Project project) { SpringBootAotPlugin aotPlugin = project.getPlugins().findPlugin(SpringBootAotPlugin.class); if (aotPlugin != null) { aotPlugin.repairKotlinPluginDamage(project); } } @Override public Class<? extends Plugin<? extends Project>> getPluginClass() { return KotlinPluginWrapper.class; } }
KotlinPluginAction
java
apache__camel
components/camel-kafka/src/test/java/org/apache/camel/component/kafka/integration/KafkaConsumerLastRecordHeaderIT.java
{ "start": 1566, "end": 4522 }
class ____ extends BaseKafkaTestSupport { private static final Logger LOG = LoggerFactory.getLogger(KafkaConsumerLastRecordHeaderIT.class); private static final String TOPIC = "last-record"; private org.apache.kafka.clients.producer.KafkaProducer<String, String> producer; @BeforeEach public void before() { Properties props = getDefaultProperties(); producer = new org.apache.kafka.clients.producer.KafkaProducer<>(props); } @AfterEach public void after() { if (producer != null) { producer.close(); } // clean all test topics kafkaAdminClient.deleteTopics(Collections.singletonList(TOPIC)); } /** * When consuming data with autoCommitEnable=false Then the LAST_RECORD_BEFORE_COMMIT header must be always defined * And it should be true only for the last one of batch of polled records */ @Test public void shouldStartFromBeginningWithEmptyOffsetRepository() throws InterruptedException { MockEndpoint result = contextExtension.getMockEndpoint(KafkaTestUtil.MOCK_RESULT); result.expectedMessageCount(5); result.expectedBodiesReceived("message-0", "message-1", "message-2", "message-3", "message-4"); for (int i = 0; i < 5; i++) { producer.send(new ProducerRecord<>(TOPIC, "1", "message-" + i)); } result.assertIsSatisfied(5000); List<Exchange> exchanges = result.getExchanges(); LOG.debug("There are {} exchanges in the result", exchanges.size()); for (int i = 0; i < exchanges.size(); i++) { final Boolean lastRecordCommit = exchanges.get(i).getIn().getHeader(KafkaConstants.LAST_RECORD_BEFORE_COMMIT, Boolean.class); final Boolean lastPollRecord = exchanges.get(i).getIn().getHeader(KafkaConstants.LAST_POLL_RECORD, Boolean.class); LOG.debug("Processing LAST_RECORD_BEFORE_COMMIT header for {}: {} ", i, lastRecordCommit); LOG.debug("Processing LAST_POLL_RECORD header for {}: {} ", i, lastPollRecord); assertNotNull(lastRecordCommit, "Header not set for #" + i); assertEquals(lastRecordCommit, i == exchanges.size() - 1 || lastPollRecord.booleanValue(), "Header invalid for #" + i); assertNotNull(lastPollRecord, "Last record header not set for #" + i); if (i == exchanges.size() - 1) { assertEquals(lastPollRecord, i == exchanges.size() - 1, "Last record header invalid for #" + i); } } } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("kafka:" + TOPIC + "?groupId=A&autoOffsetReset=earliest&autoCommitEnable=false") .to("mock:result"); } }; } }
KafkaConsumerLastRecordHeaderIT
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableStartWithTest.java
{ "start": 824, "end": 3825 }
class ____ { @Test public void justCompletableComplete() { Flowable.just(1).startWith(Completable.complete()) .test() .assertResult(1); } @Test public void emptyCompletableComplete() { Flowable.empty().startWith(Completable.complete()) .test() .assertResult(); } @Test public void runCompletableError() { Runnable run = mock(Runnable.class); Flowable.fromRunnable(run).startWith(Completable.error(new TestException())) .test() .assertFailure(TestException.class); verify(run, never()).run(); } @Test public void justSingleJust() { Flowable.just(1).startWith(Single.just(2)) .test() .assertResult(2, 1); } @Test public void emptySingleJust() { Runnable run = mock(Runnable.class); Flowable.fromRunnable(run) .startWith(Single.just(2)) .test() .assertResult(2); verify(run).run(); } @Test public void runSingleError() { Runnable run = mock(Runnable.class); Flowable.fromRunnable(run).startWith(Single.error(new TestException())) .test() .assertFailure(TestException.class); verify(run, never()).run(); } @Test public void justMaybeJust() { Flowable.just(1).startWith(Maybe.just(2)) .test() .assertResult(2, 1); } @Test public void emptyMaybeJust() { Runnable run = mock(Runnable.class); Flowable.fromRunnable(run) .startWith(Maybe.just(2)) .test() .assertResult(2); verify(run).run(); } @Test public void runMaybeError() { Runnable run = mock(Runnable.class); Flowable.fromRunnable(run).startWith(Maybe.error(new TestException())) .test() .assertFailure(TestException.class); verify(run, never()).run(); } @Test public void justFlowableJust() { Flowable.just(1).startWith(Flowable.just(2, 3, 4, 5)) .test() .assertResult(2, 3, 4, 5, 1); } @Test public void emptyFlowableJust() { Runnable run = mock(Runnable.class); Flowable.fromRunnable(run) .startWith(Flowable.just(2, 3, 4, 5)) .test() .assertResult(2, 3, 4, 5); verify(run).run(); } @Test public void emptyFlowableEmpty() { Runnable run = mock(Runnable.class); Runnable run2 = mock(Runnable.class); Flowable.fromRunnable(run) .startWith(Flowable.fromRunnable(run2)) .test() .assertResult(); verify(run).run(); verify(run2).run(); } @Test public void runFlowableError() { Runnable run = mock(Runnable.class); Flowable.fromRunnable(run).startWith(Flowable.error(new TestException())) .test() .assertFailure(TestException.class); verify(run, never()).run(); } }
FlowableStartWithTest
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfigurationTests.java
{ "start": 29423, "end": 29689 }
class ____ { @Bean CorsConfigurationSource corsConfigurationSource() { return new CustomCorsConfigurationSource(); } @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { return http.build(); } } static
NonUrlBasedCorsConfig
java
google__guava
android/guava/src/com/google/common/util/concurrent/ListenerCallQueue.java
{ "start": 1418, "end": 2630 }
class ____ designed to make it easy to achieve the following properties * * <ul> * <li>Multiple events for the same listener are never dispatched concurrently. * <li>Events for the different listeners are dispatched concurrently. * <li>All events for a given listener dispatch on the provided executor. * <li>It is easy for the user to ensure that listeners are never invoked while holding locks. * </ul> * * The last point is subtle. Often the observable object will be managing its own internal state * using a lock, however it is dangerous to dispatch listeners while holding a lock because they * might run on the {@code directExecutor()} or be otherwise re-entrant (call back into your * object). So it is important to not call {@link #dispatch} while holding any locks. This is why * {@link #enqueue} and {@link #dispatch} are 2 different methods. It is expected that the decision * to run a particular event is made during the state change, but the decision to actually invoke * the listeners can be delayed slightly so that locks can be dropped. Also, because {@link * #dispatch} is expected to be called concurrently, it is idempotent. */ @J2ktIncompatible @GwtIncompatible final
is
java
square__retrofit
retrofit-mock/src/main/java/retrofit2/mock/BehaviorDelegate.java
{ "start": 1940, "end": 5353 }
interface ____ creation guarded by parameter safety. public <R> T returning(Call<R> call) { final Call<R> behaviorCall = new BehaviorCall<>(behavior, executor, call); return (T) Proxy.newProxyInstance( service.getClassLoader(), new Class[] {service}, (proxy, method, args) -> { ServiceMethodAdapterInfo adapterInfo = parseServiceMethodAdapterInfo(method); Annotation[] methodAnnotations = method.getAnnotations(); CallAdapter<R, T> callAdapter = (CallAdapter<R, T>) retrofit.callAdapter(adapterInfo.responseType, methodAnnotations); T adapted = callAdapter.adapt(behaviorCall); if (!adapterInfo.isSuspend) { return adapted; } Call<Object> adaptedCall = (Call<Object>) adapted; Continuation<Object> continuation = (Continuation<Object>) args[args.length - 1]; try { return adapterInfo.wantsResponse ? KotlinExtensions.awaitResponse(adaptedCall, continuation) : KotlinExtensions.await(adaptedCall, continuation); } catch (Exception e) { return KotlinExtensions.suspendAndThrow(e, continuation); } }); } /** * Computes the adapter type of the method for lookup via {@link Retrofit#callAdapter} as well as * information on whether the method is a {@code suspend fun}. * * <p>In the case of a Kotlin {@code suspend fun}, the last parameter type is a {@code * Continuation} whose parameter carries the actual response type. In this case, we return {@code * Call<T>} where {@code T} is the body type. */ private static ServiceMethodAdapterInfo parseServiceMethodAdapterInfo(Method method) { Type[] genericParameterTypes = method.getGenericParameterTypes(); if (genericParameterTypes.length != 0) { Type lastParameterType = genericParameterTypes[genericParameterTypes.length - 1]; if (lastParameterType instanceof ParameterizedType) { ParameterizedType parameterizedLastParameterType = (ParameterizedType) lastParameterType; try { if (parameterizedLastParameterType.getRawType() == Continuation.class) { Type resultType = parameterizedLastParameterType.getActualTypeArguments()[0]; if (resultType instanceof WildcardType) { resultType = ((WildcardType) resultType).getLowerBounds()[0]; } if (resultType instanceof ParameterizedType) { ParameterizedType parameterizedResultType = (ParameterizedType) resultType; if (parameterizedResultType.getRawType() == Response.class) { Type bodyType = parameterizedResultType.getActualTypeArguments()[0]; Type callType = new CallParameterizedTypeImpl(bodyType); return new ServiceMethodAdapterInfo(true, true, callType); } } Type callType = new CallParameterizedTypeImpl(resultType); return new ServiceMethodAdapterInfo(true, false, callType); } } catch (NoClassDefFoundError ignored) { // Not using coroutines. } } } return new ServiceMethodAdapterInfo(false, false, method.getGenericReturnType()); } static final
proxy
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 18684, "end": 19038 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return dialect.getIdentityColumnSupport().supportsIdentityColumns() && dialect.getGlobalTemporaryTableStrategy() != null && dialect.getGlobalTemporaryTableStrategy().supportsTemporaryTablePrimaryKey(); } } public static
SupportsGlobalTemporaryTableIdentity
java
junit-team__junit5
junit-platform-engine/src/main/java/org/junit/platform/engine/support/hierarchical/WorkerThreadPoolHierarchicalTestExecutorService.java
{ "start": 27011, "end": 28565 }
class ____ implements AutoCloseable { private final BiFunction<Boolean, BooleanSupplier, WorkerLeaseManager.ReacquisitionToken> releaseAction; private WorkerLeaseManager.@Nullable ReacquisitionToken reacquisitionToken; WorkerLease(BiFunction<Boolean, BooleanSupplier, WorkerLeaseManager.ReacquisitionToken> releaseAction) { this.releaseAction = releaseAction; } @Override public void close() { release(true); } public void release(BooleanSupplier doneCondition) { release(true, doneCondition); } void release(boolean compensate) { release(compensate, () -> false); } void release(boolean compensate, BooleanSupplier doneCondition) { if (reacquisitionToken == null) { reacquisitionToken = releaseAction.apply(compensate, doneCondition); } } void reacquire() throws InterruptedException { Preconditions.notNull(reacquisitionToken, "Cannot reacquire an unreleased WorkerLease"); reacquisitionToken.reacquire(); reacquisitionToken = null; } } private record LeaseAwareRejectedExecutionHandler(WorkerLeaseManager workerLeaseManager) implements RejectedExecutionHandler { @Override public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { if (!(r instanceof RunLeaseAwareWorker worker)) { return; } worker.workerLease.release(false); if (executor.isShutdown() || workerLeaseManager.isAtLeastOneLeaseTaken()) { return; } throw new RejectedExecutionException("Task with " + workerLeaseManager + " rejected from " + executor); } } }
WorkerLease
java
hibernate__hibernate-orm
hibernate-envers/src/test/java/org/hibernate/orm/test/envers/entities/components/relations/OneToManyComponent.java
{ "start": 504, "end": 1758 }
class ____ { @OneToMany @JoinTable(joinColumns = @JoinColumn(name = "OneToMany_id")) private Set<StrTestEntity> entities = new HashSet<StrTestEntity>(); private String data; public OneToManyComponent(String data) { this.data = data; } public OneToManyComponent() { } public String getData() { return data; } public void setData(String data) { this.data = data; } public Set<StrTestEntity> getEntities() { return entities; } public void setEntities(Set<StrTestEntity> entities) { this.entities = entities; } @Override public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } OneToManyComponent that = (OneToManyComponent) o; if ( data != null ? !data.equals( that.data ) : that.data != null ) { return false; } if ( entities != null ? !entities.equals( that.entities ) : that.entities != null ) { return false; } return true; } @Override public int hashCode() { int result = entities != null ? entities.hashCode() : 0; result = 31 * result + (data != null ? data.hashCode() : 0); return result; } public String toString() { return "OneToManyComponent(data = " + data + ")"; } }
OneToManyComponent
java
google__error-prone
check_api/src/main/java/com/google/errorprone/DescriptionListener.java
{ "start": 1102, "end": 1216 }
interface ____ { DescriptionListener getDescriptionListener(Log log, JCCompilationUnit compilation); } }
Factory
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/error/ShouldNotHaveSameClass.java
{ "start": 826, "end": 1415 }
class ____ extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldNotHaveSameClass}</code>. * @param actual the actual value in the failed assertion. * @param other the type {@code actual} is expected to be. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldNotHaveSameClass(Object actual, Object other) { return new ShouldNotHaveSameClass(actual, other); } private ShouldNotHaveSameClass(Object actual, Object other) { super("%nExpecting actual:%n %s%nnot to have the same
ShouldNotHaveSameClass
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/scheduling/config/ScheduledTaskHolder.java
{ "start": 711, "end": 934 }
interface ____ exposing locally scheduled tasks. * * @author Juergen Hoeller * @since 5.0.2 * @see ScheduledTaskRegistrar * @see org.springframework.scheduling.annotation.ScheduledAnnotationBeanPostProcessor */ public
for
java
apache__rocketmq
remoting/src/main/java/org/apache/rocketmq/remoting/protocol/RocketMQSerializable.java
{ "start": 1141, "end": 8716 }
class ____ { private static final Charset CHARSET_UTF8 = StandardCharsets.UTF_8; public static void writeStr(ByteBuf buf, boolean useShortLength, String str) { int lenIndex = buf.writerIndex(); if (useShortLength) { buf.writeShort(0); } else { buf.writeInt(0); } int len = buf.writeCharSequence(str, StandardCharsets.UTF_8); if (useShortLength) { buf.setShort(lenIndex, len); } else { buf.setInt(lenIndex, len); } } private static String readStr(ByteBuf buf, boolean useShortLength, int limit) throws RemotingCommandException { int len = useShortLength ? buf.readShort() : buf.readInt(); if (len == 0) { return null; } if (len > limit) { throw new RemotingCommandException("string length exceed limit:" + limit); } CharSequence cs = buf.readCharSequence(len, StandardCharsets.UTF_8); return cs == null ? null : cs.toString(); } public static int rocketMQProtocolEncode(RemotingCommand cmd, ByteBuf out) { int beginIndex = out.writerIndex(); // int code(~32767) out.writeShort(cmd.getCode()); // LanguageCode language out.writeByte(cmd.getLanguage().getCode()); // int version(~32767) out.writeShort(cmd.getVersion()); // int opaque out.writeInt(cmd.getOpaque()); // int flag out.writeInt(cmd.getFlag()); // String remark String remark = cmd.getRemark(); if (remark != null && !remark.isEmpty()) { writeStr(out, false, remark); } else { out.writeInt(0); } int mapLenIndex = out.writerIndex(); out.writeInt(0); if (cmd.readCustomHeader() instanceof FastCodesHeader) { ((FastCodesHeader) cmd.readCustomHeader()).encode(out); } HashMap<String, String> map = cmd.getExtFields(); if (map != null && !map.isEmpty()) { map.forEach((k, v) -> { if (k != null && v != null) { writeStr(out, true, k); writeStr(out, false, v); } }); } out.setInt(mapLenIndex, out.writerIndex() - mapLenIndex - 4); return out.writerIndex() - beginIndex; } public static byte[] rocketMQProtocolEncode(RemotingCommand cmd) { // String remark byte[] remarkBytes = null; int remarkLen = 0; if (cmd.getRemark() != null && cmd.getRemark().length() > 0) { remarkBytes = cmd.getRemark().getBytes(CHARSET_UTF8); remarkLen = remarkBytes.length; } // HashMap<String, String> extFields byte[] extFieldsBytes = null; int extLen = 0; if (cmd.getExtFields() != null && !cmd.getExtFields().isEmpty()) { extFieldsBytes = mapSerialize(cmd.getExtFields()); extLen = extFieldsBytes.length; } int totalLen = calTotalLen(remarkLen, extLen); ByteBuffer headerBuffer = ByteBuffer.allocate(totalLen); // int code(~32767) headerBuffer.putShort((short) cmd.getCode()); // LanguageCode language headerBuffer.put(cmd.getLanguage().getCode()); // int version(~32767) headerBuffer.putShort((short) cmd.getVersion()); // int opaque headerBuffer.putInt(cmd.getOpaque()); // int flag headerBuffer.putInt(cmd.getFlag()); // String remark if (remarkBytes != null) { headerBuffer.putInt(remarkBytes.length); headerBuffer.put(remarkBytes); } else { headerBuffer.putInt(0); } // HashMap<String, String> extFields; if (extFieldsBytes != null) { headerBuffer.putInt(extFieldsBytes.length); headerBuffer.put(extFieldsBytes); } else { headerBuffer.putInt(0); } return headerBuffer.array(); } public static byte[] mapSerialize(HashMap<String, String> map) { // keySize+key+valSize+val if (null == map || map.isEmpty()) return null; int totalLength = 0; int kvLength; Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); if (entry.getKey() != null && entry.getValue() != null) { kvLength = // keySize + Key 2 + entry.getKey().getBytes(CHARSET_UTF8).length // valSize + val + 4 + entry.getValue().getBytes(CHARSET_UTF8).length; totalLength += kvLength; } } ByteBuffer content = ByteBuffer.allocate(totalLength); byte[] key; byte[] val; it = map.entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, String> entry = it.next(); if (entry.getKey() != null && entry.getValue() != null) { key = entry.getKey().getBytes(CHARSET_UTF8); val = entry.getValue().getBytes(CHARSET_UTF8); content.putShort((short) key.length); content.put(key); content.putInt(val.length); content.put(val); } } return content.array(); } private static int calTotalLen(int remark, int ext) { // int code(~32767) int length = 2 // LanguageCode language + 1 // int version(~32767) + 2 // int opaque + 4 // int flag + 4 // String remark + 4 + remark // HashMap<String, String> extFields + 4 + ext; return length; } public static RemotingCommand rocketMQProtocolDecode(final ByteBuf headerBuffer, int headerLen) throws RemotingCommandException { RemotingCommand cmd = new RemotingCommand(); // int code(~32767) cmd.setCode(headerBuffer.readShort()); // LanguageCode language cmd.setLanguage(LanguageCode.valueOf(headerBuffer.readByte())); // int version(~32767) cmd.setVersion(headerBuffer.readShort()); // int opaque cmd.setOpaque(headerBuffer.readInt()); // int flag cmd.setFlag(headerBuffer.readInt()); // String remark cmd.setRemark(readStr(headerBuffer, false, headerLen)); // HashMap<String, String> extFields int extFieldsLength = headerBuffer.readInt(); if (extFieldsLength > 0) { if (extFieldsLength > headerLen) { throw new RemotingCommandException("RocketMQ protocol decoding failed, extFields length: " + extFieldsLength + ", but header length: " + headerLen); } cmd.setExtFields(mapDeserialize(headerBuffer, extFieldsLength)); } return cmd; } public static HashMap<String, String> mapDeserialize(ByteBuf byteBuffer, int len) throws RemotingCommandException { HashMap<String, String> map = new HashMap<>(128); int endIndex = byteBuffer.readerIndex() + len; while (byteBuffer.readerIndex() < endIndex) { String k = readStr(byteBuffer, true, len); String v = readStr(byteBuffer, false, len); map.put(k, v); } return map; } }
RocketMQSerializable
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/action/fieldcaps/RequestDispatcherTests.java
{ "start": 38213, "end": 42925 }
class ____ { private final RequestDispatcher dispatcher; private final RoutingTable routingTable; private final boolean withFilter; private final AtomicInteger currentRound = new AtomicInteger(); final List<NodeRequest> sentNodeRequests = new CopyOnWriteArrayList<>(); RequestTracker(RequestDispatcher dispatcher, RoutingTable routingTable, boolean withFilter) { this.dispatcher = dispatcher; this.routingTable = routingTable; this.withFilter = withFilter; } void verifyAfterComplete() { final int lastRound = dispatcher.executionRound(); // No requests are sent in the last round for (NodeRequest request : sentNodeRequests) { assertThat(request.round, lessThan(lastRound)); } for (int i = 0; i < lastRound; i++) { int round = i; List<NodeRequest> nodeRequests = sentNodeRequests.stream().filter(r -> r.round == round).toList(); if (withFilter == false) { // Without filter, each index is requested once in each round. Map<String, Integer> requestsPerIndex = new HashMap<>(); nodeRequests.forEach(r -> r.indices().forEach(index -> requestsPerIndex.merge(index, 1, Integer::sum))); for (var e : requestsPerIndex.entrySet()) { assertThat("index " + e.getKey() + " has requested more than once", e.getValue(), equalTo(1)); } } // With or without filter, each new node receives at most one request each round final Map<DiscoveryNode, List<NodeRequest>> requestsPerNode = sentNodeRequests.stream() .filter(r -> r.round == round) .collect(Collectors.groupingBy(r -> r.node)); for (Map.Entry<DiscoveryNode, List<NodeRequest>> e : requestsPerNode.entrySet()) { assertThat( "node " + e.getKey().getName() + " receives more than 1 requests in round " + currentRound, e.getValue(), hasSize(1) ); } // No shardId is requested more than once in a round Set<ShardId> requestedShards = new HashSet<>(); for (NodeRequest nodeRequest : nodeRequests) { for (ShardId shardId : nodeRequest.request.shardIds()) { assertTrue(requestedShards.add(shardId)); } } } // Request only shards that assigned to target nodes for (NodeRequest nodeRequest : sentNodeRequests) { for (String index : nodeRequest.indices()) { final Set<ShardId> requestedShardIds = nodeRequest.requestedShardIds(index); final Set<ShardId> assignedShardIds = assignedShardsOnNode(routingTable.index(index), nodeRequest.node.getId()); assertThat(requestedShardIds, everyItem(in(assignedShardIds))); } } // No shard is requested twice each node Map<String, Set<ShardId>> requestedShardIdsPerNode = new HashMap<>(); for (NodeRequest nodeRequest : sentNodeRequests) { final Set<ShardId> shardIds = requestedShardIdsPerNode.computeIfAbsent(nodeRequest.node.getId(), k -> new HashSet<>()); for (ShardId shardId : nodeRequest.request.shardIds()) { assertTrue(shardIds.add(shardId)); } } } void verifyAndTrackRequest(Transport.Connection connection, String action, TransportRequest request) { final int requestRound = dispatcher.executionRound(); final DiscoveryNode node = connection.getNode(); if (action.equals(TransportFieldCapabilitiesAction.ACTION_NODE_NAME)) { assertThat(request, instanceOf(FieldCapabilitiesNodeRequest.class)); FieldCapabilitiesNodeRequest nodeRequest = (FieldCapabilitiesNodeRequest) request; sentNodeRequests.add(new NodeRequest(requestRound, node, nodeRequest)); } } List<NodeRequest> nodeRequests(String index, int round) { return sentNodeRequests.stream().filter(r -> r.round == round && r.indices().contains(index)).toList(); } List<NodeRequest> nodeRequests(String index) { return sentNodeRequests.stream().filter(r -> r.indices().contains(index)).toList(); } } private static
RequestTracker
java
apache__camel
components/camel-salesforce/camel-salesforce-maven-plugin/src/test/resources/generated/QueryRecordsComplexCalculatedFormula.java
{ "start": 375, "end": 481 }
class ____ extends AbstractQueryRecordsBase<ComplexCalculatedFormula> { }
QueryRecordsComplexCalculatedFormula
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/contracts/exceptions/InvalidConfigurationValueException.java
{ "start": 1107, "end": 1691 }
class ____ extends AzureBlobFileSystemException { public InvalidConfigurationValueException(String configKey, Exception innerException) { super("Invalid configuration value detected for " + configKey, innerException); } public InvalidConfigurationValueException(String configKey) { super("Invalid configuration value detected for " + configKey); } public InvalidConfigurationValueException(String configKey, String message) { super(String.format("Invalid configuration value detected for \"%s\". %s ", configKey, message)); } }
InvalidConfigurationValueException
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/uuid_test/UUIDTypeHandler.java
{ "start": 944, "end": 1889 }
class ____ extends BaseTypeHandler<UUID> { @Override public void setNonNullParameter(PreparedStatement ps, int i, UUID parameter, JdbcType jdbcType) throws SQLException { ps.setString(i, parameter.toString()); } @Override public UUID getNullableResult(ResultSet rs, String columnName) throws SQLException { String value = rs.getString(columnName); if (value != null) { return UUID.fromString(value); } return null; } @Override public UUID getNullableResult(ResultSet rs, int columnIndex) throws SQLException { String value = rs.getString(columnIndex); if (value != null) { return UUID.fromString(value); } return null; } @Override public UUID getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { String value = cs.getString(columnIndex); if (value != null) { return UUID.fromString(value); } return null; } }
UUIDTypeHandler
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/jmx/export/naming/MetadataNamingStrategyTests.java
{ "start": 1158, "end": 3398 }
class ____ { private static final TestBean TEST_BEAN = new TestBean(); private final MetadataNamingStrategy strategy; MetadataNamingStrategyTests() { this.strategy = new MetadataNamingStrategy(); this.strategy.setDefaultDomain("com.example"); this.strategy.setAttributeSource(new AnnotationJmxAttributeSource()); } @Test void getObjectNameWhenBeanNameIsSimple() throws MalformedObjectNameException { ObjectName name = this.strategy.getObjectName(TEST_BEAN, "myBean"); assertThat(name.getDomain()).isEqualTo("com.example"); assertThat(name).satisfies(hasDefaultProperties(TEST_BEAN, "myBean")); } @Test void getObjectNameWhenBeanNameIsValidObjectName() throws MalformedObjectNameException { ObjectName name = this.strategy.getObjectName(TEST_BEAN, "com.another:name=myBean"); assertThat(name.getDomain()).isEqualTo("com.another"); assertThat(name.getKeyPropertyList()).containsOnly(entry("name", "myBean")); } @Test void getObjectNameWhenBeanNameContainsComma() throws MalformedObjectNameException { ObjectName name = this.strategy.getObjectName(TEST_BEAN, "myBean,"); assertThat(name).satisfies(hasDefaultProperties(TEST_BEAN, "\"myBean,\"")); } @Test void getObjectNameWhenBeanNameContainsEquals() throws MalformedObjectNameException { ObjectName name = this.strategy.getObjectName(TEST_BEAN, "my=Bean"); assertThat(name).satisfies(hasDefaultProperties(TEST_BEAN, "\"my=Bean\"")); } @Test void getObjectNameWhenBeanNameContainsColon() throws MalformedObjectNameException { ObjectName name = this.strategy.getObjectName(TEST_BEAN, "my:Bean"); assertThat(name).satisfies(hasDefaultProperties(TEST_BEAN, "\"my:Bean\"")); } @Test void getObjectNameWhenBeanNameContainsQuote() throws MalformedObjectNameException { ObjectName name = this.strategy.getObjectName(TEST_BEAN, "\"myBean\""); assertThat(name).satisfies(hasDefaultProperties(TEST_BEAN, "\"\\\"myBean\\\"\"")); } private Consumer<ObjectName> hasDefaultProperties(Object instance, String expectedName) { return objectName -> assertThat(objectName.getKeyPropertyList()).containsOnly( entry("type", ClassUtils.getShortName(instance.getClass())), entry("name", expectedName)); } static
MetadataNamingStrategyTests
java
spring-projects__spring-boot
module/spring-boot-graphql/src/test/java/org/springframework/boot/graphql/autoconfigure/rsocket/RSocketGraphQlClientAutoConfigurationTests.java
{ "start": 2655, "end": 2812 }
class ____ { @Bean RSocketGraphQlClient.Builder<?> myRSocketGraphQlClientBuilder() { return builderInstance; } } }
CustomRSocketGraphQlClientBuilder
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/objectarray/ObjectArrayAssert_extracting_Test.java
{ "start": 14175, "end": 14227 }
class ____ implements DefaultName { } public
Person
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/job/persistence/TimingStatsReporter.java
{ "start": 509, "end": 652 }
class ____ the logic of persisting {@link TimingStats} if they changed significantly since the last time * they were persisted. * * This
handles
java
eclipse-vertx__vert.x
vertx-core/src/main/java/io/vertx/core/spi/context/storage/ConcurrentAccessMode.java
{ "start": 161, "end": 1205 }
class ____ implements AccessMode { public static final ConcurrentAccessMode INSTANCE = new ConcurrentAccessMode(); private static final VarHandle LOCALS_UPDATER = MethodHandles.arrayElementVarHandle(Object[].class); private ConcurrentAccessMode() { } @Override public Object get(Object[] locals, int idx) { return LOCALS_UPDATER.getVolatile(locals, idx); } @Override public void put(Object[] locals, int idx, Object value) { LOCALS_UPDATER.setRelease(locals, idx, value); } @Override public Object getOrCreate(Object[] locals, int idx, Supplier<Object> initialValueSupplier) { Object res; while (true) { res = LOCALS_UPDATER.getVolatile(locals, idx); if (res != null) { break; } Object initial = initialValueSupplier.get(); if (initial == null) { throw new IllegalStateException(); } if (LOCALS_UPDATER.compareAndSet(locals, idx, null, initial)) { res = initial; break; } } return res; } }
ConcurrentAccessMode
java
greenrobot__greendao
DaoCore/src/main/java/org/greenrobot/greendao/query/CountQuery.java
{ "start": 913, "end": 3134 }
class ____<T2> extends AbstractQueryData<T2, CountQuery<T2>> { private QueryData(AbstractDao<T2, ?> dao, String sql, String[] initialValues) { super(dao, sql, initialValues); } @Override protected CountQuery<T2> createQuery() { return new CountQuery<T2>(this, dao, sql, initialValues.clone()); } } static <T2> CountQuery<T2> create(AbstractDao<T2, ?> dao, String sql, Object[] initialValues) { QueryData<T2> queryData = new QueryData<T2>(dao, sql, toStringArray(initialValues)); return queryData.forCurrentThread(); } private final QueryData<T> queryData; private CountQuery(QueryData<T> queryData, AbstractDao<T, ?> dao, String sql, String[] initialValues) { super(dao, sql, initialValues); this.queryData = queryData; } public CountQuery<T> forCurrentThread() { return queryData.forCurrentThread(this); } /** Returns the count (number of results matching the query). Uses SELECT COUNT (*) sematics. */ public long count() { checkThread(); Cursor cursor = dao.getDatabase().rawQuery(sql, parameters); try { if (!cursor.moveToNext()) { throw new DaoException("No result for count"); } else if (!cursor.isLast()) { throw new DaoException("Unexpected row count: " + cursor.getCount()); } else if (cursor.getColumnCount() != 1) { throw new DaoException("Unexpected column count: " + cursor.getColumnCount()); } return cursor.getLong(0); } finally { cursor.close(); } } // copy setParameter methods to allow easy chaining @Override public CountQuery<T> setParameter(int index, Object parameter) { return (CountQuery<T>) super.setParameter(index, parameter); } @Override public CountQuery<T> setParameter(int index, Date parameter) { return (CountQuery<T>) super.setParameter(index, parameter); } @Override public CountQuery<T> setParameter(int index, Boolean parameter) { return (CountQuery<T>) super.setParameter(index, parameter); } }
QueryData
java
spring-projects__spring-security
access/src/test/java/org/springframework/security/access/TargetObject.java
{ "start": 1298, "end": 2031 }
class ____ * was on the <code>SecurityContext</code> at the time of method invocation, and a * boolean indicating if the <code>Authentication</code> object is authenticated or * not */ @Override public String makeLowerCase(String input) { Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth == null) { return input.toLowerCase() + " Authentication empty"; } else { return input.toLowerCase() + " " + auth.getClass().getName() + " " + auth.isAuthenticated(); } } /** * Returns the uppercase string, followed by security environment information. * @param input the message to make uppercase * @return the uppercase message, a space, the <code>Authentication</code>
that
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated/org/elasticsearch/compute/aggregation/AllLastIntByTimestampAggregatorFunction.java
{ "start": 1109, "end": 5724 }
class ____ implements AggregatorFunction { private static final List<IntermediateStateDesc> INTERMEDIATE_STATE_DESC = List.of( new IntermediateStateDesc("timestamps", ElementType.LONG), new IntermediateStateDesc("values", ElementType.INT), new IntermediateStateDesc("seen", ElementType.BOOLEAN), new IntermediateStateDesc("hasValue", ElementType.BOOLEAN) ); private final DriverContext driverContext; private final AllLongIntState state; private final List<Integer> channels; public AllLastIntByTimestampAggregatorFunction(DriverContext driverContext, List<Integer> channels, AllLongIntState state) { this.driverContext = driverContext; this.channels = channels; this.state = state; } public static AllLastIntByTimestampAggregatorFunction create(DriverContext driverContext, List<Integer> channels) { return new AllLastIntByTimestampAggregatorFunction(driverContext, channels, AllLastIntByTimestampAggregator.initSingle(driverContext)); } public static List<IntermediateStateDesc> intermediateStateDesc() { return INTERMEDIATE_STATE_DESC; } @Override public int intermediateBlockCount() { return INTERMEDIATE_STATE_DESC.size(); } @Override public void addRawInput(Page page, BooleanVector mask) { if (mask.allFalse()) { // Entire page masked away } else if (mask.allTrue()) { addRawInputNotMasked(page); } else { addRawInputMasked(page, mask); } } private void addRawInputMasked(Page page, BooleanVector mask) { IntBlock valueBlock = page.getBlock(channels.get(0)); LongBlock timestampBlock = page.getBlock(channels.get(1)); addRawBlock(valueBlock, timestampBlock, mask); } private void addRawInputNotMasked(Page page) { IntBlock valueBlock = page.getBlock(channels.get(0)); LongBlock timestampBlock = page.getBlock(channels.get(1)); addRawBlock(valueBlock, timestampBlock); } private void addRawBlock(IntBlock valueBlock, LongBlock timestampBlock) { for (int p = 0; p < valueBlock.getPositionCount(); p++) { AllLastIntByTimestampAggregator.combine(state, p, valueBlock, timestampBlock); } } private void addRawBlock(IntBlock valueBlock, LongBlock timestampBlock, BooleanVector mask) { for (int p = 0; p < valueBlock.getPositionCount(); p++) { if (mask.getBoolean(p) == false) { continue; } AllLastIntByTimestampAggregator.combine(state, p, valueBlock, timestampBlock); } } @Override public void addIntermediateInput(Page page) { assert channels.size() == intermediateBlockCount(); assert page.getBlockCount() >= channels.get(0) + intermediateStateDesc().size(); Block timestampsUncast = page.getBlock(channels.get(0)); if (timestampsUncast.areAllValuesNull()) { return; } LongVector timestamps = ((LongBlock) timestampsUncast).asVector(); assert timestamps.getPositionCount() == 1; Block valuesUncast = page.getBlock(channels.get(1)); if (valuesUncast.areAllValuesNull()) { return; } IntVector values = ((IntBlock) valuesUncast).asVector(); assert values.getPositionCount() == 1; Block seenUncast = page.getBlock(channels.get(2)); if (seenUncast.areAllValuesNull()) { return; } BooleanVector seen = ((BooleanBlock) seenUncast).asVector(); assert seen.getPositionCount() == 1; Block hasValueUncast = page.getBlock(channels.get(3)); if (hasValueUncast.areAllValuesNull()) { return; } BooleanVector hasValue = ((BooleanBlock) hasValueUncast).asVector(); assert hasValue.getPositionCount() == 1; AllLastIntByTimestampAggregator.combineIntermediate(state, timestamps.getLong(0), values.getInt(0), seen.getBoolean(0), hasValue.getBoolean(0)); } @Override public void evaluateIntermediate(Block[] blocks, int offset, DriverContext driverContext) { state.toIntermediate(blocks, offset, driverContext); } @Override public void evaluateFinal(Block[] blocks, int offset, DriverContext driverContext) { if (state.seen() == false) { blocks[offset] = driverContext.blockFactory().newConstantNullBlock(1); return; } blocks[offset] = AllLastIntByTimestampAggregator.evaluateFinal(state, driverContext); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()).append("["); sb.append("channels=").append(channels); sb.append("]"); return sb.toString(); } @Override public void close() { state.close(); } }
AllLastIntByTimestampAggregatorFunction
java
apache__hadoop
hadoop-tools/hadoop-azure/src/test/java/org/apache/hadoop/fs/azurebfs/services/TestTextFileBasedIdentityHandler.java
{ "start": 1382, "end": 7240 }
class ____ { @TempDir public static Path tempDir; private static File userMappingFile = null; private static File groupMappingFile = null; private static final String NEW_LINE = "\n"; private static String testUserDataLine1 = "a2b27aec-77bd-46dd-8c8c-39611a333331:user1:11000:21000:spi-user1:abcf86e9-5a5b-49e2-a253-f5c9e2afd4ec" + NEW_LINE; private static String testUserDataLine2 = "#i2j27aec-77bd-46dd-8c8c-39611a333331:user2:41000:21000:spi-user2:mnof86e9-5a5b-49e2-a253-f5c9e2afd4ec" + NEW_LINE; private static String testUserDataLine3 = "c2d27aec-77bd-46dd-8c8c-39611a333331:user2:21000:21000:spi-user2:deff86e9-5a5b-49e2-a253-f5c9e2afd4ec" + NEW_LINE; private static String testUserDataLine4 = "e2f27aec-77bd-46dd-8c8c-39611a333331c" + NEW_LINE; private static String testUserDataLine5 = "g2h27aec-77bd-46dd-8c8c-39611a333331:user4:41000:21000:spi-user4:jklf86e9-5a5b-49e2-a253-f5c9e2afd4ec" + NEW_LINE; private static String testUserDataLine6 = " " + NEW_LINE; private static String testUserDataLine7 = "i2j27aec-77bd-46dd-8c8c-39611a333331:user5:41000:21000:spi-user5:mknf86e9-5a5b-49e2-a253-f5c9e2afd4ec" + NEW_LINE; private static String testGroupDataLine1 = "1d23024d-957c-4456-aac1-a57f9e2de914:group1:21000:sgp-group1" + NEW_LINE; private static String testGroupDataLine2 = "3d43024d-957c-4456-aac1-a57f9e2de914:group2:21000:sgp-group2" + NEW_LINE; private static String testGroupDataLine3 = "5d63024d-957c-4456-aac1-a57f9e2de914" + NEW_LINE; private static String testGroupDataLine4 = " " + NEW_LINE; private static String testGroupDataLine5 = "7d83024d-957c-4456-aac1-a57f9e2de914:group4:21000:sgp-group4" + NEW_LINE; @BeforeAll public static void init() throws IOException { userMappingFile = tempDir.resolve("user-mapping.conf").toFile(); groupMappingFile = tempDir.resolve("group-mapping.conf").toFile(); //Stage data for user mapping FileUtils.writeStringToFile(userMappingFile, testUserDataLine1, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(userMappingFile, testUserDataLine2, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(userMappingFile, testUserDataLine3, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(userMappingFile, testUserDataLine4, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(userMappingFile, testUserDataLine5, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(userMappingFile, testUserDataLine6, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(userMappingFile, testUserDataLine7, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(userMappingFile, NEW_LINE, StandardCharsets.UTF_8, true); //Stage data for group mapping FileUtils.writeStringToFile(groupMappingFile, testGroupDataLine1, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(groupMappingFile, testGroupDataLine2, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(groupMappingFile, testGroupDataLine3, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(groupMappingFile, testGroupDataLine4, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(groupMappingFile, testGroupDataLine5, StandardCharsets.UTF_8, true); FileUtils.writeStringToFile(groupMappingFile, NEW_LINE, StandardCharsets.UTF_8, true); } private void assertUserLookup(TextFileBasedIdentityHandler handler, String userInTest, String expectedUser) throws IOException { String actualUser = handler.lookupForLocalUserIdentity(userInTest); assertEquals(expectedUser, actualUser, "Wrong user identity for "); } @Test public void testLookupForUser() throws IOException { TextFileBasedIdentityHandler handler = new TextFileBasedIdentityHandler(userMappingFile.getPath(), groupMappingFile.getPath()); //Success scenario => user in test -> user2. assertUserLookup(handler, testUserDataLine3.split(":")[0], testUserDataLine3.split(":")[1]); //No username found in the mapping file. assertUserLookup(handler, "bogusIdentity", ""); //Edge case when username is empty string. assertUserLookup(handler, "", ""); } @Test public void testLookupForUserFileNotFound() throws Exception { TextFileBasedIdentityHandler handler = new TextFileBasedIdentityHandler(userMappingFile.getPath() + ".test", groupMappingFile.getPath()); intercept(NoSuchFileException.class, "NoSuchFileException", () -> handler.lookupForLocalUserIdentity(testUserDataLine3.split(":")[0])); } private void assertGroupLookup(TextFileBasedIdentityHandler handler, String groupInTest, String expectedGroup) throws IOException { String actualGroup = handler.lookupForLocalGroupIdentity(groupInTest); assertEquals(expectedGroup, actualGroup, "Wrong group identity for "); } @Test public void testLookupForGroup() throws IOException { TextFileBasedIdentityHandler handler = new TextFileBasedIdentityHandler(userMappingFile.getPath(), groupMappingFile.getPath()); //Success scenario. assertGroupLookup(handler, testGroupDataLine2.split(":")[0], testGroupDataLine2.split(":")[1]); //No group name found in the mapping file. assertGroupLookup(handler, "bogusIdentity", ""); //Edge case when group name is empty string. assertGroupLookup(handler, "", ""); } @Test public void testLookupForGroupFileNotFound() throws Exception { TextFileBasedIdentityHandler handler = new TextFileBasedIdentityHandler(userMappingFile.getPath(), groupMappingFile.getPath() + ".test"); intercept(NoSuchFileException.class, "NoSuchFileException", () -> handler.lookupForLocalGroupIdentity(testGroupDataLine2.split(":")[0])); } }
TestTextFileBasedIdentityHandler
java
google__gson
gson/src/main/java/com/google/gson/JsonSerializer.java
{ "start": 1135, "end": 1726 }
class ____&lt;T&gt; { * private final Class&lt;T&gt; clazz; * private final long value; * * public Id(Class&lt;T&gt; clazz, long value) { * this.clazz = clazz; * this.value = value; * } * * public long getValue() { * return value; * } * } * </pre> * * <p>The default serialization of {@code Id(com.foo.MyObject.class, 20L)} will be <code> * {"clazz":"com.foo.MyObject","value":20}</code>. Suppose, you just want the output to be the value * instead, which is {@code 20} in this case. You can achieve that by writing a custom serializer: * * <pre> *
Id
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/metrics/TimerGauge.java
{ "start": 7326, "end": 7415 }
interface ____ { void markStart(); void markEnd(); } }
StartStopListener
java
alibaba__fastjson
src/test/java/com/alibaba/json/test/jackson/JacksonUnwrappedTest.java
{ "start": 635, "end": 701 }
class ____ { public int x; public int y; } }
Point
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/slm/action/GetSLMStatusAction.java
{ "start": 1007, "end": 1852 }
class ____ extends ActionResponse implements ToXContentObject { private final OperationMode mode; public Response(StreamInput in) throws IOException { this.mode = in.readEnum(OperationMode.class); } public Response(OperationMode mode) { this.mode = mode; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeEnum(this.mode); } public OperationMode getOperationMode() { return this.mode; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("operation_mode", this.mode); builder.endObject(); return builder; } } }
Response
java
eclipse-vertx__vert.x
vertx-core/src/main/generated/io/vertx/core/http/HttpClientOptionsConverter.java
{ "start": 338, "end": 8322 }
class ____ { static void fromJson(Iterable<java.util.Map.Entry<String, Object>> json, HttpClientOptions obj) { for (java.util.Map.Entry<String, Object> member : json) { switch (member.getKey()) { case "http2MultiplexingLimit": if (member.getValue() instanceof Number) { obj.setHttp2MultiplexingLimit(((Number)member.getValue()).intValue()); } break; case "http2ConnectionWindowSize": if (member.getValue() instanceof Number) { obj.setHttp2ConnectionWindowSize(((Number)member.getValue()).intValue()); } break; case "http2KeepAliveTimeout": if (member.getValue() instanceof Number) { obj.setHttp2KeepAliveTimeout(((Number)member.getValue()).intValue()); } break; case "http2UpgradeMaxContentLength": if (member.getValue() instanceof Number) { obj.setHttp2UpgradeMaxContentLength(((Number)member.getValue()).intValue()); } break; case "http2MultiplexImplementation": if (member.getValue() instanceof Boolean) { obj.setHttp2MultiplexImplementation((Boolean)member.getValue()); } break; case "keepAlive": if (member.getValue() instanceof Boolean) { obj.setKeepAlive((Boolean)member.getValue()); } break; case "keepAliveTimeout": if (member.getValue() instanceof Number) { obj.setKeepAliveTimeout(((Number)member.getValue()).intValue()); } break; case "pipelining": if (member.getValue() instanceof Boolean) { obj.setPipelining((Boolean)member.getValue()); } break; case "pipeliningLimit": if (member.getValue() instanceof Number) { obj.setPipeliningLimit(((Number)member.getValue()).intValue()); } break; case "verifyHost": if (member.getValue() instanceof Boolean) { obj.setVerifyHost((Boolean)member.getValue()); } break; case "decompressionSupported": if (member.getValue() instanceof Boolean) { obj.setDecompressionSupported((Boolean)member.getValue()); } break; case "defaultHost": if (member.getValue() instanceof String) { obj.setDefaultHost((String)member.getValue()); } break; case "defaultPort": if (member.getValue() instanceof Number) { obj.setDefaultPort(((Number)member.getValue()).intValue()); } break; case "protocolVersion": if (member.getValue() instanceof String) { obj.setProtocolVersion(io.vertx.core.http.HttpVersion.valueOf((String)member.getValue())); } break; case "maxChunkSize": if (member.getValue() instanceof Number) { obj.setMaxChunkSize(((Number)member.getValue()).intValue()); } break; case "maxInitialLineLength": if (member.getValue() instanceof Number) { obj.setMaxInitialLineLength(((Number)member.getValue()).intValue()); } break; case "maxHeaderSize": if (member.getValue() instanceof Number) { obj.setMaxHeaderSize(((Number)member.getValue()).intValue()); } break; case "initialSettings": if (member.getValue() instanceof JsonObject) { obj.setInitialSettings(new io.vertx.core.http.Http2Settings((io.vertx.core.json.JsonObject)member.getValue())); } break; case "alpnVersions": if (member.getValue() instanceof JsonArray) { java.util.ArrayList<io.vertx.core.http.HttpVersion> list = new java.util.ArrayList<>(); ((Iterable<Object>)member.getValue()).forEach( item -> { if (item instanceof String) list.add(io.vertx.core.http.HttpVersion.valueOf((String)item)); }); obj.setAlpnVersions(list); } break; case "http2ClearTextUpgrade": if (member.getValue() instanceof Boolean) { obj.setHttp2ClearTextUpgrade((Boolean)member.getValue()); } break; case "http2ClearTextUpgradeWithPreflightRequest": if (member.getValue() instanceof Boolean) { obj.setHttp2ClearTextUpgradeWithPreflightRequest((Boolean)member.getValue()); } break; case "maxRedirects": if (member.getValue() instanceof Number) { obj.setMaxRedirects(((Number)member.getValue()).intValue()); } break; case "forceSni": if (member.getValue() instanceof Boolean) { obj.setForceSni((Boolean)member.getValue()); } break; case "decoderInitialBufferSize": if (member.getValue() instanceof Number) { obj.setDecoderInitialBufferSize(((Number)member.getValue()).intValue()); } break; case "tracingPolicy": if (member.getValue() instanceof String) { obj.setTracingPolicy(io.vertx.core.tracing.TracingPolicy.valueOf((String)member.getValue())); } break; case "shared": if (member.getValue() instanceof Boolean) { obj.setShared((Boolean)member.getValue()); } break; case "name": if (member.getValue() instanceof String) { obj.setName((String)member.getValue()); } break; } } } static void toJson(HttpClientOptions obj, JsonObject json) { toJson(obj, json.getMap()); } static void toJson(HttpClientOptions obj, java.util.Map<String, Object> json) { json.put("http2MultiplexingLimit", obj.getHttp2MultiplexingLimit()); json.put("http2ConnectionWindowSize", obj.getHttp2ConnectionWindowSize()); json.put("http2KeepAliveTimeout", obj.getHttp2KeepAliveTimeout()); json.put("http2UpgradeMaxContentLength", obj.getHttp2UpgradeMaxContentLength()); json.put("http2MultiplexImplementation", obj.getHttp2MultiplexImplementation()); json.put("keepAlive", obj.isKeepAlive()); json.put("keepAliveTimeout", obj.getKeepAliveTimeout()); json.put("pipelining", obj.isPipelining()); json.put("pipeliningLimit", obj.getPipeliningLimit()); json.put("verifyHost", obj.isVerifyHost()); json.put("decompressionSupported", obj.isDecompressionSupported()); if (obj.getDefaultHost() != null) { json.put("defaultHost", obj.getDefaultHost()); } json.put("defaultPort", obj.getDefaultPort()); if (obj.getProtocolVersion() != null) { json.put("protocolVersion", obj.getProtocolVersion().name()); } json.put("maxChunkSize", obj.getMaxChunkSize()); json.put("maxInitialLineLength", obj.getMaxInitialLineLength()); json.put("maxHeaderSize", obj.getMaxHeaderSize()); if (obj.getInitialSettings() != null) { json.put("initialSettings", obj.getInitialSettings().toJson()); } if (obj.getAlpnVersions() != null) { JsonArray array = new JsonArray(); obj.getAlpnVersions().forEach(item -> array.add(item.name())); json.put("alpnVersions", array); } json.put("http2ClearTextUpgrade", obj.isHttp2ClearTextUpgrade()); json.put("http2ClearTextUpgradeWithPreflightRequest", obj.isHttp2ClearTextUpgradeWithPreflightRequest()); json.put("maxRedirects", obj.getMaxRedirects()); json.put("forceSni", obj.isForceSni()); json.put("decoderInitialBufferSize", obj.getDecoderInitialBufferSize()); if (obj.getTracingPolicy() != null) { json.put("tracingPolicy", obj.getTracingPolicy().name()); } json.put("shared", obj.isShared()); if (obj.getName() != null) { json.put("name", obj.getName()); } } }
HttpClientOptionsConverter
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/ContextConfigurationTestClassScopedExtensionContextNestedTests.java
{ "start": 5561, "end": 5657 }
class ____ { @Bean String foo() { return FOO; } } @Configuration static
TopLevelConfig
java
apache__flink
flink-core/src/test/java/org/apache/flink/api/common/resources/ResourceTest.java
{ "start": 1196, "end": 7912 }
class ____ { @Test void testConstructorValid() { final Resource v1 = new TestResource(0.1); assertTestResourceValueEquals(0.1, v1); final Resource v2 = new TestResource(BigDecimal.valueOf(0.1)); assertTestResourceValueEquals(0.1, v2); } @Test void testConstructorInvalidValue() { assertThatThrownBy(() -> new TestResource(-0.1)) .isInstanceOf(IllegalArgumentException.class); } @Test void testEquals() { final Resource v1 = new TestResource(0.1); final Resource v2 = new TestResource(0.1); final Resource v3 = new TestResource(0.2); assertThat(v2).isEqualTo(v1); assertThat(v3).isNotEqualTo(v1); } @Test void testEqualsIgnoringScale() { final Resource v1 = new TestResource(new BigDecimal("0.1")); final Resource v2 = new TestResource(new BigDecimal("0.10")); assertThat(v2).isEqualTo(v1); } @Test void testHashCodeIgnoringScale() { final Resource v1 = new TestResource(new BigDecimal("0.1")); final Resource v2 = new TestResource(new BigDecimal("0.10")); assertThat(v2).hasSameHashCodeAs(v1); } @Test void testMerge() { final Resource v1 = new TestResource(0.1); final Resource v2 = new TestResource(0.2); assertTestResourceValueEquals(0.3, v1.merge(v2)); } @Test void testMergeErrorOnDifferentTypes() { final Resource v1 = new TestResource(0.1); final Resource v2 = new CPUResource(0.1); // v1.merge(v2); assertThatThrownBy(() -> v1.merge(v2)).isInstanceOf(IllegalArgumentException.class); } @Test void testSubtract() { final Resource v1 = new TestResource(0.2); final Resource v2 = new TestResource(0.1); assertTestResourceValueEquals(0.1, v1.subtract(v2)); } @Test void testSubtractLargerValue() { final Resource v1 = new TestResource(0.1); final Resource v2 = new TestResource(0.2); assertThatThrownBy(() -> v1.subtract(v2)).isInstanceOf(IllegalArgumentException.class); } @Test void testSubtractErrorOnDifferentTypes() { final Resource v1 = new TestResource(0.1); final Resource v2 = new CPUResource(0.1); assertThatThrownBy(() -> v1.subtract(v2)).isInstanceOf(IllegalArgumentException.class); } @Test void testDivide() { final Resource resource = new TestResource(0.04); final BigDecimal by = BigDecimal.valueOf(0.1); assertTestResourceValueEquals(0.4, resource.divide(by)); } @Test void testDivideNegative() { final Resource resource = new TestResource(1.2); final BigDecimal by = BigDecimal.valueOf(-0.5); assertThatThrownBy(() -> resource.divide(by)).isInstanceOf(IllegalArgumentException.class); } @Test void testDivideInteger() { final Resource resource = new TestResource(0.12); final int by = 4; assertTestResourceValueEquals(0.03, resource.divide(by)); } @Test void testDivideNegativeInteger() { final Resource resource = new TestResource(1.2); final int by = -5; assertThatThrownBy(() -> resource.divide(by)).isInstanceOf(IllegalArgumentException.class); } @Test void testMultiply() { final Resource resource = new TestResource(0.3); final BigDecimal by = BigDecimal.valueOf(0.2); assertTestResourceValueEquals(0.06, resource.multiply(by)); } @Test void testMutiplyNegative() { final Resource resource = new TestResource(0.3); final BigDecimal by = BigDecimal.valueOf(-0.2); assertThatThrownBy(() -> resource.multiply(by)) .isInstanceOf(IllegalArgumentException.class); } @Test void testMultiplyInteger() { final Resource resource = new TestResource(0.3); final int by = 2; assertTestResourceValueEquals(0.6, resource.multiply(by)); } @Test void testMutiplyNegativeInteger() { final Resource resource = new TestResource(0.3); final int by = -2; assertThatThrownBy(() -> resource.multiply(by)) .isInstanceOf(IllegalArgumentException.class); } @Test void testIsZero() { final Resource resource1 = new TestResource(0.0); final Resource resource2 = new TestResource(1.0); assertThat(resource1.isZero()).isTrue(); assertThat(resource2.isZero()).isFalse(); } @Test void testCompareTo() { final Resource resource1 = new TestResource(0.0); final Resource resource2 = new TestResource(0.0); final Resource resource3 = new TestResource(1.0); assertThatComparable(resource1).isEqualByComparingTo(resource1); assertThatComparable(resource2).isEqualByComparingTo(resource1); assertThatComparable(resource1).isLessThan(resource3); assertThatComparable(resource3).isGreaterThan(resource1); } @Test void testCompareToFailNull() { // new TestResource(0.0).compareTo(null); assertThatThrownBy(() -> new TestResource(0.0).compareTo(null)) .isInstanceOf(IllegalArgumentException.class); } @Test void testCompareToFailDifferentType() { // initialized as different anonymous classes final Resource resource1 = new TestResource(0.0) {}; final Resource resource2 = new TestResource(0.0) {}; assertThatThrownBy(() -> resource1.compareTo(resource2)) .isInstanceOf(IllegalArgumentException.class); } @Test void testCompareToFailDifferentName() { // initialized as different anonymous classes final Resource resource1 = new TestResource("name1", 0.0); final Resource resource2 = new TestResource("name2", 0.0); assertThatThrownBy(() -> resource1.compareTo(resource2)) .isInstanceOf(IllegalArgumentException.class); } /** This test assume that the scale limitation is 8. */ @Test void testValueScaleLimited() { final Resource v1 = new TestResource(0.100000001); assertTestResourceValueEquals(0.1, v1); final Resource v2 = new TestResource(1.0).divide(3); assertTestResourceValueEquals(0.33333333, v2); } @Test void testStripTrailingZeros() { final Resource v = new TestResource(0.25).multiply(2); assertThat(v.getValue().toString()).isEqualTo("0.5"); } private static void assertTestResourceValueEquals(final double value, final Resource resource) { assertThat(resource).isEqualTo(new TestResource(value)); } }
ResourceTest
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/api/MediaTypeTests.java
{ "start": 1211, "end": 1484 }
class ____ { @Test void equals() { var mediaType1 = MediaType.TEXT_PLAIN; var mediaType2 = MediaType.parse(mediaType1.toString()); var mediaType3 = MediaType.APPLICATION_JSON; assertEqualsAndHashCode(mediaType1, mediaType2, mediaType3); } @Nested
MediaTypeTests
java
elastic__elasticsearch
x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/aggregate/TopSerializationTests.java
{ "start": 563, "end": 1901 }
class ____ extends AbstractExpressionSerializationTests<Top> { @Override protected Top createTestInstance() { Source source = randomSource(); Expression field = randomChild(); Expression limit = randomChild(); Expression order = randomChild(); Expression outputField = randomBoolean() ? null : randomChild(); return new Top(source, field, limit, order, outputField); } @Override protected Top mutateInstance(Top instance) throws IOException { Source source = instance.source(); Expression field = instance.field(); Expression limit = instance.limitField(); Expression order = instance.orderField(); Expression outputField = instance.outputField(); switch (between(0, 3)) { case 0 -> field = randomValueOtherThan(field, AbstractExpressionSerializationTests::randomChild); case 1 -> limit = randomValueOtherThan(limit, AbstractExpressionSerializationTests::randomChild); case 2 -> order = randomValueOtherThan(order, AbstractExpressionSerializationTests::randomChild); case 3 -> outputField = randomValueOtherThan(outputField, () -> randomBoolean() ? null : randomChild()); } return new Top(source, field, limit, order, outputField); } }
TopSerializationTests
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/operators/sort/SorterInputGateway.java
{ "start": 1187, "end": 5052 }
class ____<E> { /** Logging. */ private static final Logger LOG = LoggerFactory.getLogger(SorterInputGateway.class); private final LargeRecordHandler<E> largeRecords; /** The object into which the thread reads the data from the input. */ private final StageRunner.StageMessageDispatcher<E> dispatcher; private long bytesUntilSpilling; private CircularElement<E> currentBuffer; /** * Creates a new gateway for pushing records into the sorter. * * @param dispatcher The queues used to pass buffers between the threads. */ SorterInputGateway( StageRunner.StageMessageDispatcher<E> dispatcher, @Nullable LargeRecordHandler<E> largeRecordsHandler, long startSpillingBytes) { // members this.bytesUntilSpilling = startSpillingBytes; this.largeRecords = largeRecordsHandler; this.dispatcher = checkNotNull(dispatcher); if (bytesUntilSpilling < 1) { this.dispatcher.send(SortStage.SORT, CircularElement.spillingMarker()); } } /** Writes the given record for sorting. */ public void writeRecord(E record) throws IOException, InterruptedException { if (currentBuffer == null) { this.currentBuffer = this.dispatcher.take(SortStage.READ); if (!currentBuffer.getBuffer().isEmpty()) { throw new IOException("New buffer is not empty."); } } InMemorySorter<E> sorter = currentBuffer.getBuffer(); long occupancyPreWrite = sorter.getOccupancy(); if (!sorter.write(record)) { long recordSize = sorter.getCapacity() - occupancyPreWrite; signalSpillingIfNecessary(recordSize); boolean isLarge = occupancyPreWrite == 0; if (isLarge) { // did not fit in a fresh buffer, must be large... writeLarge(record, sorter); this.currentBuffer.getBuffer().reset(); } else { this.dispatcher.send(SortStage.SORT, currentBuffer); this.currentBuffer = null; writeRecord(record); } } else { long recordSize = sorter.getOccupancy() - occupancyPreWrite; signalSpillingIfNecessary(recordSize); } } /** Signals the end of input. Will flush all buffers and notify later stages. */ public void finishReading() { if (currentBuffer != null && !currentBuffer.getBuffer().isEmpty()) { this.dispatcher.send(SortStage.SORT, currentBuffer); } // add the sentinel to notify the receivers that the work is done // send the EOF marker final CircularElement<E> EOF_MARKER = CircularElement.endMarker(); this.dispatcher.send(SortStage.SORT, EOF_MARKER); LOG.debug("Reading thread done."); } private void writeLarge(E record, InMemorySorter<E> sorter) throws IOException { if (this.largeRecords != null) { LOG.debug( "Large record did not fit into a fresh sort buffer. Putting into large record store."); this.largeRecords.addRecord(record); } else { throw new IOException( "The record exceeds the maximum size of a sort buffer (current maximum: " + sorter.getCapacity() + " bytes)."); } } private void signalSpillingIfNecessary(long writtenSize) { if (bytesUntilSpilling <= 0) { return; } bytesUntilSpilling -= writtenSize; if (bytesUntilSpilling < 1) { // add the spilling marker this.dispatcher.send(SortStage.SORT, CircularElement.spillingMarker()); bytesUntilSpilling = 0; } } }
SorterInputGateway
java
apache__commons-lang
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
{ "start": 3878, "end": 24320 }
class ____ { private static final Supplier<RandomUtils> SECURE_SUPPLIER = RandomUtils::secure; private static RandomStringUtils INSECURE = new RandomStringUtils(RandomUtils::insecure); private static RandomStringUtils SECURE = new RandomStringUtils(SECURE_SUPPLIER); private static RandomStringUtils SECURE_STRONG = new RandomStringUtils(RandomUtils::secureStrong); private static final char[] ALPHANUMERICAL_CHARS = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; private static final int ASCII_0 = '0'; private static final int ASCII_9 = '9'; private static final int ASCII_A = 'A'; private static final int ASCII_z = 'z'; private static final int CACHE_PADDING_BITS = 3; private static final int BITS_TO_BYTES_DIVISOR = 5; private static final int BASE_CACHE_SIZE_PADDING = 10; /** * Gets the singleton instance based on {@link ThreadLocalRandom#current()}; <b>which is not cryptographically * secure</b>; use {@link #secure()} to use an algorithms/providers specified in the * {@code securerandom.strongAlgorithms} {@link Security} property. * <p> * The method {@link ThreadLocalRandom#current()} is called on-demand. * </p> * * @return the singleton instance based on {@link ThreadLocalRandom#current()}. * @see ThreadLocalRandom#current() * @see #secure() * @since 3.16.0 */ public static RandomStringUtils insecure() { return INSECURE; } /** * Creates a random string whose length is the number of characters specified. * * <p> * Characters will be chosen from the set of all characters. * </p> * * @param count the length of random string to create. * @return the random string. * @throws IllegalArgumentException if {@code count} &lt; 0. * @deprecated Use {@link #next(int)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String random(final int count) { return secure().next(count); } /** * Creates a random string whose length is the number of characters specified. * * <p> * Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. * </p> * * @param count the length of random string to create. * @param letters if {@code true}, generated string may include alphabetic characters. * @param numbers if {@code true}, generated string may include numeric characters. * @return the random string. * @throws IllegalArgumentException if {@code count} &lt; 0. * @deprecated Use {@link #next(int, boolean, boolean)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String random(final int count, final boolean letters, final boolean numbers) { return secure().next(count, letters, numbers); } /** * Creates a random string whose length is the number of characters specified. * * <p> * Characters will be chosen from the set of characters specified. * </p> * * @param count the length of random string to create. * @param chars the character array containing the set of characters to use, may be null. * @return the random string. * @throws IllegalArgumentException if {@code count} &lt; 0. * @deprecated Use {@link #next(int, char...)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String random(final int count, final char... chars) { return secure().next(count, chars); } /** * Creates a random string whose length is the number of characters specified. * * <p> * Characters will be chosen from the set of alpha-numeric characters as indicated by the arguments. * </p> * * @param count the length of random string to create. * @param start the position in set of chars to start at. * @param end the position in set of chars to end before. * @param letters if {@code true}, generated string may include alphabetic characters. * @param numbers if {@code true}, generated string may include numeric characters. * @return the random string. * @throws IllegalArgumentException if {@code count} &lt; 0. * @deprecated Use {@link #next(int, int, int, boolean, boolean)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers) { return secure().next(count, start, end, letters, numbers); } /** * Creates a random string based on a variety of options, using default source of randomness. * * <p> * This method has exactly the same semantics as {@link #random(int,int,int,boolean,boolean,char[],Random)}, but * instead of using an externally supplied source of randomness, it uses the internal static {@link Random} * instance. * </p> * * @param count the length of random string to create. * @param start the position in set of chars to start at. * @param end the position in set of chars to end before. * @param letters if {@code true}, generated string may include alphabetic characters. * @param numbers if {@code true}, generated string may include numeric characters. * @param chars the set of chars to choose randoms from. If {@code null}, then it will use the set of all chars. * @return the random string. * @throws ArrayIndexOutOfBoundsException if there are not {@code (end - start) + 1} characters in the set array. * @throws IllegalArgumentException if {@code count} &lt; 0. * @deprecated Use {@link #next(int, int, int, boolean, boolean, char...)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String random(final int count, final int start, final int end, final boolean letters, final boolean numbers, final char... chars) { return secure().next(count, start, end, letters, numbers, chars); } /** * Creates a random string based on a variety of options, using supplied source of randomness. * * <p> * If start and end are both {@code 0}, start and end are set to {@code ' '} and {@code 'z'}, the ASCII printable * characters, will be used, unless letters and numbers are both {@code false}, in which case, start and end are set * to {@code 0} and {@link Character#MAX_CODE_POINT}. * * <p> * If set is not {@code null}, characters between start and end are chosen. * </p> * * <p> * This method accepts a user-supplied {@link Random} instance to use as a source of randomness. By seeding a single * {@link Random} instance with a fixed seed and using it for each call, the same random sequence of strings can be * generated repeatedly and predictably. * </p> * * @param count the length of random string to create. * @param start the position in set of chars to start at (inclusive). * @param end the position in set of chars to end before (exclusive). * @param letters if {@code true}, generated string may include alphabetic characters. * @param numbers if {@code true}, generated string may include numeric characters. * @param chars the set of chars to choose randoms from, must not be empty. If {@code null}, then it will use the * set of all chars. * @param random a source of randomness. * @return the random string. * @throws ArrayIndexOutOfBoundsException if there are not {@code (end - start) + 1} characters in the set array. * @throws IllegalArgumentException if {@code count} &lt; 0 or the provided chars array is empty. * @since 2.0 */ public static String random(int count, int start, int end, final boolean letters, final boolean numbers, final char[] chars, final Random random) { if (count == 0) { return StringUtils.EMPTY; } if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if (chars != null && chars.length == 0) { throw new IllegalArgumentException("The chars array must not be empty"); } if (start == 0 && end == 0) { if (chars != null) { end = chars.length; } else if (!letters && !numbers) { end = Character.MAX_CODE_POINT; } else { end = 'z' + 1; start = ' '; } } else if (end <= start) { throw new IllegalArgumentException( "Parameter end (" + end + ") must be greater than start (" + start + ")"); } else if (start < 0 || end < 0) { throw new IllegalArgumentException("Character positions MUST be >= 0"); } if (end > Character.MAX_CODE_POINT) { // Technically, it should be `Character.MAX_CODE_POINT+1` as `end` is excluded // But the character `Character.MAX_CODE_POINT` is private use, so it would anyway be excluded end = Character.MAX_CODE_POINT; } // Optimizations and tests when chars == null and using ASCII characters (end <= 0x7f) if (chars == null && end <= 0x7f) { // Optimize generation of full alphanumerical characters // Normally, we would need to pick a 7-bit integer, since gap = 'z' - '0' + 1 = 75 > 64 // In turn, this would make us reject the sampling with probability 1 - 62 / 2^7 > 1 / 2 // Instead we can pick directly from the right set of 62 characters, which requires // picking a 6-bit integer and only rejecting with probability 2 / 64 = 1 / 32 if (letters && numbers && start <= ASCII_0 && end >= ASCII_z + 1) { return random(count, 0, 0, false, false, ALPHANUMERICAL_CHARS, random); } if (numbers && end <= ASCII_0 || letters && end <= ASCII_A) { throw new IllegalArgumentException( "Parameter end (" + end + ") must be greater then (" + ASCII_0 + ") for generating digits " + "or greater then (" + ASCII_A + ") for generating letters."); } // Optimize start and end when filtering by letters and/or numbers: // The range provided may be too large since we filter anyway afterward. // Note the use of Math.min/max (as opposed to setting start to '0' for example), // since it is possible the range start/end excludes some of the letters/numbers, // e.g., it is possible that start already is '1' when numbers = true, and start // needs to stay equal to '1' in that case. // Note that because of the above test, we will always have start < end // even after this optimization. if (letters && numbers) { start = Math.max(ASCII_0, start); end = Math.min(ASCII_z + 1, end); } else if (numbers) { // just numbers, no letters start = Math.max(ASCII_0, start); end = Math.min(ASCII_9 + 1, end); } else if (letters) { // just letters, no numbers start = Math.max(ASCII_A, start); end = Math.min(ASCII_z + 1, end); } } final StringBuilder builder = new StringBuilder(count); final int gap = end - start; final int gapBits = Integer.SIZE - Integer.numberOfLeadingZeros(gap); // The size of the cache we use is an heuristic: // about twice the number of bytes required if no rejection // Ideally the cache size depends on multiple factor, including the cost of generating x bytes // of randomness as well as the probability of rejection. It is however not easy to know // those values programmatically for the general case. // Calculate cache size: // 1. Multiply count by bits needed per character (gapBits) // 2. Add padding bits (3) to handle partial bytes // 3. Divide by 5 to convert to bytes (normally this would be by 8, dividing by 5 allows for about 60% extra space) // 4. Add base padding (10) to handle small counts efficiently // 5. Ensure we don't exceed Integer.MAX_VALUE / 5 + 10 to provide a good balance between overflow prevention and // making the cache extremely large final long desiredCacheSize = ((long) count * gapBits + CACHE_PADDING_BITS) / BITS_TO_BYTES_DIVISOR + BASE_CACHE_SIZE_PADDING; final int cacheSize = (int) Math.min(desiredCacheSize, Integer.MAX_VALUE / BITS_TO_BYTES_DIVISOR + BASE_CACHE_SIZE_PADDING); final CachedRandomBits arb = new CachedRandomBits(cacheSize, random); while (count-- != 0) { // Generate a random value between start (included) and end (excluded) final int randomValue = arb.nextBits(gapBits) + start; // Rejection sampling if value too large if (randomValue >= end) { count++; continue; } final int codePoint; if (chars == null) { codePoint = randomValue; switch (Character.getType(codePoint)) { case Character.UNASSIGNED: case Character.PRIVATE_USE: case Character.SURROGATE: count++; continue; } } else { codePoint = chars[randomValue]; } final int numberOfChars = Character.charCount(codePoint); if (count == 0 && numberOfChars > 1) { count++; continue; } if (letters && Character.isLetter(codePoint) || numbers && Character.isDigit(codePoint) || !letters && !numbers) { builder.appendCodePoint(codePoint); if (numberOfChars == 2) { count--; } } else { count++; } } return builder.toString(); } /** * Creates a random string whose length is the number of characters specified. * * <p> * Characters will be chosen from the set of characters specified by the string, must not be empty. If null, the set * of all characters is used. * </p> * * @param count the length of random string to create. * @param chars the String containing the set of characters to use, may be null, but must not be empty. * @return the random string. * @throws IllegalArgumentException if {@code count} &lt; 0 or the string is empty. * @deprecated Use {@link #next(int, String)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String random(final int count, final String chars) { return secure().next(count, chars); } /** * Creates a random string whose length is the number of characters specified. * * <p> * Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z). * </p> * * @param count the length of random string to create. * @return the random string. * @throws IllegalArgumentException if {@code count} &lt; 0. * @deprecated Use {@link #nextAlphabetic(int)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String randomAlphabetic(final int count) { return secure().nextAlphabetic(count); } /** * Creates a random string whose length is between the inclusive minimum and the exclusive maximum. * * <p> * Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z). * </p> * * @param minLengthInclusive the inclusive minimum length of the string to generate. * @param maxLengthExclusive the exclusive maximum length of the string to generate. * @return the random string. * @since 3.5 * @deprecated Use {@link #nextAlphabetic(int, int)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String randomAlphabetic(final int minLengthInclusive, final int maxLengthExclusive) { return secure().nextAlphabetic(minLengthInclusive, maxLengthExclusive); } /** * Creates a random string whose length is the number of characters specified. * * <p> * Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z) and the digits 0-9. * </p> * * @param count the length of random string to create. * @return the random string. * @throws IllegalArgumentException if {@code count} &lt; 0. * @deprecated Use {@link #nextAlphanumeric(int)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String randomAlphanumeric(final int count) { return secure().nextAlphanumeric(count); } /** * Creates a random string whose length is between the inclusive minimum and the exclusive maximum. * * <p> * Characters will be chosen from the set of Latin alphabetic characters (a-z, A-Z) and the digits 0-9. * </p> * * @param minLengthInclusive the inclusive minimum length of the string to generate. * @param maxLengthExclusive the exclusive maximum length of the string to generate. * @return the random string. * @since 3.5 * @deprecated Use {@link #nextAlphanumeric(int, int)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String randomAlphanumeric(final int minLengthInclusive, final int maxLengthExclusive) { return secure().nextAlphanumeric(minLengthInclusive, maxLengthExclusive); } /** * Creates a random string whose length is the number of characters specified. * * <p> * Characters will be chosen from the set of characters whose ASCII value is between {@code 32} and {@code 126} * (inclusive). * </p> * * @param count the length of random string to create. * @return the random string. * @throws IllegalArgumentException if {@code count} &lt; 0. * @deprecated Use {@link #nextAscii(int)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String randomAscii(final int count) { return secure().nextAscii(count); } /** * Creates a random string whose length is between the inclusive minimum and the exclusive maximum. * * <p> * Characters will be chosen from the set of characters whose ASCII value is between {@code 32} and {@code 126} * (inclusive). * </p> * * @param minLengthInclusive the inclusive minimum length of the string to generate. * @param maxLengthExclusive the exclusive maximum length of the string to generate. * @return the random string. * @since 3.5 * @deprecated Use {@link #nextAscii(int, int)} from {@link #secure()}, {@link #secureStrong()}, or {@link #insecure()}. */ @Deprecated public static String randomAscii(final int minLengthInclusive, final int maxLengthExclusive) { return secure().nextAscii(minLengthInclusive, maxLengthExclusive); } /** * Creates a random string whose length is the number of characters specified. * * <p> * Characters will be chosen from the set of characters which match the POSIX [:graph:] regular expression character * class. This
RandomStringUtils
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/CustomHeadersDecorator.java
{ "start": 1286, "end": 3925 }
class ____< R extends RequestBody, P extends ResponseBody, M extends MessageParameters> implements MessageHeaders<R, P, M> { private final MessageHeaders<R, P, M> decorated; private Collection<HttpHeader> customHeaders; /** * Creates a new {@code CustomHeadersDecorator} for a given {@link MessageHeaders} object. * * @param decorated The MessageHeaders to decorate. */ public CustomHeadersDecorator(MessageHeaders<R, P, M> decorated) { this.decorated = decorated; } @Override public HttpMethodWrapper getHttpMethod() { return decorated.getHttpMethod(); } @Override public String getTargetRestEndpointURL() { return decorated.getTargetRestEndpointURL(); } @Override public Collection<? extends RestAPIVersion<?>> getSupportedAPIVersions() { return decorated.getSupportedAPIVersions(); } @Override public Class<P> getResponseClass() { return decorated.getResponseClass(); } @Override public HttpResponseStatus getResponseStatusCode() { return decorated.getResponseStatusCode(); } @Override public String getDescription() { return decorated.getDescription(); } @Override public Class<R> getRequestClass() { return decorated.getRequestClass(); } @Override public M getUnresolvedMessageParameters() { return decorated.getUnresolvedMessageParameters(); } /** * Returns the custom headers added to the message. * * @return The custom headers as a collection of {@link HttpHeader}. */ @Override public Collection<HttpHeader> getCustomHeaders() { return customHeaders; } @Override public Collection<Class<?>> getResponseTypeParameters() { return decorated.getResponseTypeParameters(); } /** * Sets the custom headers for the message. * * @param customHeaders A collection of custom headers. */ public void setCustomHeaders(Collection<HttpHeader> customHeaders) { this.customHeaders = customHeaders; } /** * Adds a custom header to the message. Initializes the custom headers collection if it hasn't * been initialized yet. * * @param httpHeader The header to add. */ public void addCustomHeader(HttpHeader httpHeader) { if (customHeaders == null) { customHeaders = new ArrayList<>(); } customHeaders.add(httpHeader); } public MessageHeaders<R, P, M> getDecorated() { return decorated; } }
CustomHeadersDecorator
java
apache__camel
components/camel-consul/src/test/java/org/apache/camel/component/consul/cloud/ConsulServiceRegistrationTestBase.java
{ "start": 1529, "end": 4225 }
class ____ extends ConsulTestSupport { protected static final String SERVICE_ID = UUID.randomUUID().toString(); protected static final String SERVICE_NAME = "my-service"; protected static final String SERVICE_HOST = "localhost"; protected static final int SERVICE_PORT = AvailablePortFinder.getNextAvailable(); protected Map<String, String> getMetadata() { return Collections.emptyMap(); } @Override protected CamelContext createCamelContext() throws Exception { final CamelContext context = super.createCamelContext(); ConsulServiceRegistry registry = new ConsulServiceRegistry(); registry.setId(context.getUuidGenerator().generateUuid()); registry.setCamelContext(context()); registry.setUrl(service.getConsulUrl()); registry.setServiceHost(SERVICE_HOST); registry.setOverrideServiceHost(true); context.addService(registry, true, false); return context; } @Test public void testRegistrationFromRoute() throws Exception { final CatalogClient catalog = getConsul().catalogClient(); final HealthClient health = getConsul().healthClient(); // the service should not be registered as the route is not running assertTrue(catalog.getService(SERVICE_NAME).getResponse().isEmpty()); // let start the route context().getRouteController().startRoute(SERVICE_ID); // check that service has been registered List<CatalogService> services = catalog.getService(SERVICE_NAME).getResponse(); assertEquals(1, services.size()); assertEquals(SERVICE_PORT, services.get(0).getServicePort()); assertEquals("localhost", services.get(0).getServiceAddress()); assertTrue(services.get(0).getServiceTags().contains(ServiceDefinition.SERVICE_META_PROTOCOL + "=http")); assertTrue(services.get(0).getServiceTags().contains(ServiceDefinition.SERVICE_META_PATH + "=/service/endpoint")); getMetadata().forEach((k, v) -> { assertTrue(services.get(0).getServiceTags().contains(k + "=" + v)); }); List<ServiceHealth> checks = health.getHealthyServiceInstances(SERVICE_NAME).getResponse(); assertEquals(1, checks.size()); assertEquals(SERVICE_PORT, checks.get(0).getService().getPort()); assertEquals("localhost", checks.get(0).getService().getAddress()); // let stop the route context().getRouteController().stopRoute(SERVICE_ID); // the service should be removed once the route is stopped assertTrue(catalog.getService(SERVICE_NAME).getResponse().isEmpty()); } }
ConsulServiceRegistrationTestBase
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/TestComparators.java
{ "start": 7550, "end": 8863 }
class ____ implements Reducer<IntWritable, IntWritable, IntWritable, Text> { public void configure(JobConf job) { } // keep track of the last key we've seen private int lastKey = Integer.MAX_VALUE; public void reduce(IntWritable key, Iterator<IntWritable> values, OutputCollector<IntWritable, Text> out, Reporter reporter) throws IOException { // check key order int currentKey = key.get(); if (currentKey > lastKey) { fail("Keys not in sorted descending order"); } lastKey = currentKey; // check order of values IntWritable previous = new IntWritable(Integer.MAX_VALUE); int valueCount = 0; while (values.hasNext()) { IntWritable current = values.next(); // Check that the values are sorted if (current.compareTo(previous) > 0) fail("Values generated by Mapper not in order"); previous = current; ++valueCount; } if (valueCount != 5) { fail("Values not grouped by primary key"); } out.collect(key, new Text("success")); } public void close() { } } /** * A decreasing Comparator for IntWritable */ public static
DescendingGroupReducer
java
apache__dubbo
dubbo-test/dubbo-test-modules/src/test/java/org/apache/dubbo/dependency/FileTest.java
{ "start": 28841, "end": 29763 }
interface ____ be added to dubbo-all(dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml in shade plugin) to being transformed. Found spis: " + expectedSpis); List<String> unexpectedSpis = new LinkedList<>(transformsInDubboAll); unexpectedSpis.removeAll(spis); Assertions.assertTrue( unexpectedSpis.isEmpty(), "Class without `@SPI` declaration should not be added to dubbo-all(dubbo-distribution" + File.separator + "dubbo-all" + File.separator + "pom.xml in shade plugin) to being transformed. Found spis: " + unexpectedSpis); expectedSpis = new LinkedList<>(spis); expectedSpis.removeAll(transformsInDubboAllShaded); Assertions.assertTrue( expectedSpis.isEmpty(), "Newly created SPI
must
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/cluster/routing/allocation/mapper/DataTierFieldMapper.java
{ "start": 932, "end": 1208 }
class ____ extends MetadataFieldMapper { public static final String NAME = "_tier"; public static final String CONTENT_TYPE = "_tier"; public static final TypeParser PARSER = new FixedTypeParser(c -> new DataTierFieldMapper()); static final
DataTierFieldMapper
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/jndi/JndiObjectFactoryBean.java
{ "start": 11870, "end": 12941 }
interface ____ the JndiObjectTargetSource. ProxyFactory proxyFactory = new ProxyFactory(); if (jof.proxyInterfaces != null) { proxyFactory.setInterfaces(jof.proxyInterfaces); } else { Class<?> targetClass = targetSource.getTargetClass(); if (targetClass == null) { throw new IllegalStateException( "Cannot deactivate 'lookupOnStartup' without specifying a 'proxyInterface' or 'expectedType'"); } Class<?>[] ifcs = ClassUtils.getAllInterfacesForClass(targetClass, jof.beanClassLoader); for (Class<?> ifc : ifcs) { if (Modifier.isPublic(ifc.getModifiers())) { proxyFactory.addInterface(ifc); } } } if (jof.exposeAccessContext) { proxyFactory.addAdvice(new JndiContextExposingInterceptor(jof.getJndiTemplate())); } proxyFactory.setTargetSource(targetSource); return proxyFactory.getProxy(jof.beanClassLoader); } } /** * Interceptor that exposes the JNDI context for all method invocations, * according to JndiObjectFactoryBean's "exposeAccessContext" flag. */ private static
and
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/stateless/StatelessDoWorkTest.java
{ "start": 4222, "end": 4679 }
class ____ { @Id @Column(name = "ID") private Integer id; @Column(name = "NAME") private String name; public TestEntity() { } public TestEntity(Integer id, String name) { this.id = id; this.name = name; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } }
TestEntity
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/context/properties/ConfigurationPropertiesBeanTests.java
{ "start": 2193, "end": 17700 }
class ____ { @Test void getAllReturnsAll() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( NonAnnotatedComponent.class, AnnotatedComponent.class, AnnotatedBeanConfiguration.class, ValueObjectConfiguration.class)) { Map<String, ConfigurationPropertiesBean> all = ConfigurationPropertiesBean.getAll(context); assertThat(all).containsOnlyKeys("annotatedComponent", "annotatedBean", ValueObject.class.getName()); ConfigurationPropertiesBean component = all.get("annotatedComponent"); assertThat(component).isNotNull(); assertThat(component.getName()).isEqualTo("annotatedComponent"); assertThat(component.getInstance()).isInstanceOf(AnnotatedComponent.class); assertThat(component.getAnnotation()).isNotNull(); assertThat(component.getType()).isEqualTo(AnnotatedComponent.class); assertThat(component.asBindTarget().getBindMethod()).isEqualTo(BindMethod.JAVA_BEAN); ConfigurationPropertiesBean bean = all.get("annotatedBean"); assertThat(bean).isNotNull(); assertThat(bean.getName()).isEqualTo("annotatedBean"); assertThat(bean.getInstance()).isInstanceOf(AnnotatedBean.class); assertThat(bean.getType()).isEqualTo(AnnotatedBean.class); assertThat(bean.getAnnotation()).isNotNull(); assertThat(bean.asBindTarget().getBindMethod()).isEqualTo(BindMethod.JAVA_BEAN); ConfigurationPropertiesBean valueObject = all.get(ValueObject.class.getName()); assertThat(valueObject).isNotNull(); assertThat(valueObject.getName()).isEqualTo(ValueObject.class.getName()); assertThat(valueObject.getInstance()).isInstanceOf(ValueObject.class); assertThat(valueObject.getType()).isEqualTo(ValueObject.class); assertThat(valueObject.getAnnotation()).isNotNull(); assertThat(valueObject.asBindTarget().getBindMethod()).isEqualTo(BindMethod.VALUE_OBJECT); } } @Test void getAllDoesNotFindABeanDeclaredInAStaticBeanMethodOnAConfigurationAndConfigurationPropertiesAnnotatedClass() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( StaticBeanMethodConfiguration.class)) { Map<String, ConfigurationPropertiesBean> all = ConfigurationPropertiesBean.getAll(context); assertThat(all).containsOnlyKeys("configurationPropertiesBeanTests.StaticBeanMethodConfiguration"); } } @Test void getAllWhenHasBadBeanDoesNotFail() { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( NonAnnotatedComponent.class, AnnotatedComponent.class, AnnotatedBeanConfiguration.class, ValueObjectConfiguration.class, BadBeanConfiguration.class)) { Map<String, ConfigurationPropertiesBean> all = ConfigurationPropertiesBean.getAll(context); assertThat(all).isNotEmpty(); } } @Test void getWhenNotAnnotatedReturnsNull() throws Throwable { get(NonAnnotatedComponent.class, "nonAnnotatedComponent", (propertiesBean) -> assertThat(propertiesBean).isNull()); } @Test void getWhenBeanIsAnnotatedReturnsBean() throws Throwable { get(AnnotatedComponent.class, "annotatedComponent", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); assertThat(propertiesBean.getName()).isEqualTo("annotatedComponent"); assertThat(propertiesBean.getInstance()).isInstanceOf(AnnotatedComponent.class); assertThat(propertiesBean.getType()).isEqualTo(AnnotatedComponent.class); assertThat(propertiesBean.getAnnotation().prefix()).isEqualTo("prefix"); assertThat(propertiesBean.asBindTarget().getBindMethod()).isEqualTo(BindMethod.JAVA_BEAN); }); } @Test void getWhenFactoryMethodIsAnnotatedReturnsBean() throws Throwable { get(NonAnnotatedBeanConfiguration.class, "nonAnnotatedBean", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); assertThat(propertiesBean.getName()).isEqualTo("nonAnnotatedBean"); assertThat(propertiesBean.getInstance()).isInstanceOf(NonAnnotatedBean.class); assertThat(propertiesBean.getType()).isEqualTo(NonAnnotatedBean.class); assertThat(propertiesBean.getAnnotation().prefix()).isEqualTo("prefix"); assertThat(propertiesBean.asBindTarget().getBindMethod()).isEqualTo(BindMethod.JAVA_BEAN); }); } @Test void getWhenImportedFactoryMethodIsAnnotatedAndMetadataCachingIsDisabledReturnsBean() throws Throwable { getWithoutBeanMetadataCaching(NonAnnotatedBeanImportConfiguration.class, "nonAnnotatedBean", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); assertThat(propertiesBean.getName()).isEqualTo("nonAnnotatedBean"); assertThat(propertiesBean.getInstance()).isInstanceOf(NonAnnotatedBean.class); assertThat(propertiesBean.getType()).isEqualTo(NonAnnotatedBean.class); assertThat(propertiesBean.getAnnotation().prefix()).isEqualTo("prefix"); assertThat(propertiesBean.asBindTarget().getBindMethod()).isEqualTo(BindMethod.JAVA_BEAN); }); } @Test void getWhenImportedFactoryMethodIsAnnotatedReturnsBean() throws Throwable { get(NonAnnotatedBeanImportConfiguration.class, "nonAnnotatedBean", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); assertThat(propertiesBean.getName()).isEqualTo("nonAnnotatedBean"); assertThat(propertiesBean.getInstance()).isInstanceOf(NonAnnotatedBean.class); assertThat(propertiesBean.getType()).isEqualTo(NonAnnotatedBean.class); assertThat(propertiesBean.getAnnotation().prefix()).isEqualTo("prefix"); assertThat(propertiesBean.asBindTarget().getBindMethod()).isEqualTo(BindMethod.JAVA_BEAN); }); } @Test void getWhenHasFactoryMethodBindsUsingMethodReturnType() throws Throwable { get(NonAnnotatedGenericBeanConfiguration.class, "nonAnnotatedGenericBean", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); assertThat(propertiesBean.getType()).isEqualTo(NonAnnotatedGenericBean.class); assertThat(propertiesBean.asBindTarget().getBindMethod()).isEqualTo(BindMethod.JAVA_BEAN); ResolvableType type = propertiesBean.asBindTarget().getType(); assertThat(type.resolve()).isEqualTo(NonAnnotatedGenericBean.class); assertThat(type.resolveGeneric(0)).isEqualTo(String.class); }); } @Test void getWhenHasFactoryMethodWithoutAnnotationBindsUsingMethodType() throws Throwable { get(AnnotatedGenericBeanConfiguration.class, "annotatedGenericBean", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); assertThat(propertiesBean.getType()).isEqualTo(AnnotatedGenericBean.class); assertThat(propertiesBean.asBindTarget().getBindMethod()).isEqualTo(BindMethod.JAVA_BEAN); ResolvableType type = propertiesBean.asBindTarget().getType(); assertThat(type.resolve()).isEqualTo(AnnotatedGenericBean.class); assertThat(type.resolveGeneric(0)).isEqualTo(String.class); }); } @Test void getWhenHasNoFactoryMethodBindsUsingObjectType() throws Throwable { get(AnnotatedGenericComponent.class, "annotatedGenericComponent", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); assertThat(propertiesBean.getType()).isEqualTo(AnnotatedGenericComponent.class); assertThat(propertiesBean.asBindTarget().getBindMethod()).isEqualTo(BindMethod.JAVA_BEAN); ResolvableType type = propertiesBean.asBindTarget().getType(); assertThat(type.resolve()).isEqualTo(AnnotatedGenericComponent.class); assertThat(type.getGeneric(0).resolve()).isNull(); }); } @Test void getWhenHasFactoryMethodAndBeanAnnotationFavorsFactoryMethod() throws Throwable { get(AnnotatedBeanConfiguration.class, "annotatedBean", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); assertThat(propertiesBean.getAnnotation().prefix()).isEqualTo("factory"); }); } @Test void getWhenHasValidatedBeanBindsWithBeanAnnotation() throws Throwable { get(ValidatedBeanConfiguration.class, "validatedBean", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); Validated validated = propertiesBean.asBindTarget().getAnnotation(Validated.class); assertThat(validated).isNotNull(); assertThat(validated.value()).containsExactly(BeanGroup.class); }); } @Test void getWhenHasValidatedFactoryMethodBindsWithFactoryMethodAnnotation() throws Throwable { get(ValidatedMethodConfiguration.class, "annotatedBean", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); Validated validated = propertiesBean.asBindTarget().getAnnotation(Validated.class); assertThat(validated).isNotNull(); assertThat(validated.value()).containsExactly(FactoryMethodGroup.class); }); } @Test void getWhenHasValidatedBeanAndFactoryMethodBindsWithFactoryMethodAnnotation() throws Throwable { get(ValidatedMethodAndBeanConfiguration.class, "validatedBean", (propertiesBean) -> { assertThat(propertiesBean).isNotNull(); Validated validated = propertiesBean.asBindTarget().getAnnotation(Validated.class); assertThat(validated).isNotNull(); assertThat(validated.value()).containsExactly(FactoryMethodGroup.class); }); } @Test void forValueObjectWithConstructorBindingAnnotatedClassReturnsBean() { ConfigurationPropertiesBean propertiesBean = ConfigurationPropertiesBean .forValueObject(ConstructorBindingOnConstructor.class, "valueObjectBean"); assertThat(propertiesBean.getName()).isEqualTo("valueObjectBean"); assertThat(propertiesBean.getInstance()).isNull(); assertThat(propertiesBean.getType()).isEqualTo(ConstructorBindingOnConstructor.class); assertThat(propertiesBean.asBindTarget().getBindMethod()).isEqualTo(BindMethod.VALUE_OBJECT); assertThat(propertiesBean.getAnnotation()).isNotNull(); Bindable<?> target = propertiesBean.asBindTarget(); assertThat(target.getType()).isEqualTo(ResolvableType.forClass(ConstructorBindingOnConstructor.class)); assertThat(target.getValue()).isNull(); assertThat(BindConstructorProvider.DEFAULT.getBindConstructor(ConstructorBindingOnConstructor.class, false)) .isNotNull(); } @Test void forValueObjectWithRecordReturnsBean() { Class<?> implicitConstructorBinding = new ByteBuddy(ClassFileVersion.JAVA_V16).makeRecord() .name("org.springframework.boot.context.properties.ImplicitConstructorBinding") .annotateType(AnnotationDescription.Builder.ofType(ConfigurationProperties.class) .define("prefix", "implicit") .build()) .defineRecordComponent("someString", String.class) .defineRecordComponent("someInteger", Integer.class) .make() .load(getClass().getClassLoader()) .getLoaded(); ConfigurationPropertiesBean propertiesBean = ConfigurationPropertiesBean .forValueObject(implicitConstructorBinding, "implicitBindingRecord"); assertThat(propertiesBean.getName()).isEqualTo("implicitBindingRecord"); assertThat(propertiesBean.getInstance()).isNull(); assertThat(propertiesBean.getType()).isEqualTo(implicitConstructorBinding); assertThat(propertiesBean.asBindTarget().getBindMethod()).isEqualTo(BindMethod.VALUE_OBJECT); assertThat(propertiesBean.getAnnotation()).isNotNull(); Bindable<?> target = propertiesBean.asBindTarget(); assertThat(target.getType()).isEqualTo(ResolvableType.forClass(implicitConstructorBinding)); assertThat(target.getValue()).isNull(); Constructor<?> bindConstructor = BindConstructorProvider.DEFAULT.getBindConstructor(implicitConstructorBinding, false); assertThat(bindConstructor).isNotNull(); assertThat(bindConstructor.getParameterTypes()).containsExactly(String.class, Integer.class); } @Test void forValueObjectWhenJavaBeanBindTypeThrowsException() { assertThatIllegalStateException() .isThrownBy(() -> ConfigurationPropertiesBean.forValueObject(AnnotatedBean.class, "annotatedBean")) .withMessage("Bean 'annotatedBean' is not a @ConfigurationProperties value object"); assertThatIllegalStateException() .isThrownBy(() -> ConfigurationPropertiesBean.forValueObject(NonAnnotatedBean.class, "nonAnnotatedBean")) .withMessage("Bean 'nonAnnotatedBean' is not a @ConfigurationProperties value object"); } @Test void deduceBindMethodWhenNoConstructorBindingReturnsJavaBean() { BindMethod bindType = ConfigurationPropertiesBean.deduceBindMethod(NoConstructorBinding.class); assertThat(bindType).isEqualTo(BindMethod.JAVA_BEAN); } @Test void deduceBindMethodWhenConstructorBindingOnConstructorReturnsValueObject() { BindMethod bindType = ConfigurationPropertiesBean.deduceBindMethod(ConstructorBindingOnConstructor.class); assertThat(bindType).isEqualTo(BindMethod.VALUE_OBJECT); } @Test void deduceBindMethodWhenNoConstructorBindingAnnotationOnSingleParameterizedConstructorReturnsValueObject() { BindMethod bindType = ConfigurationPropertiesBean.deduceBindMethod(ConstructorBindingNoAnnotation.class); assertThat(bindType).isEqualTo(BindMethod.VALUE_OBJECT); } @Test void deduceBindMethodWhenConstructorBindingOnMultipleConstructorsThrowsException() { assertThatIllegalStateException() .isThrownBy( () -> ConfigurationPropertiesBean.deduceBindMethod(ConstructorBindingOnMultipleConstructors.class)) .withMessage(ConstructorBindingOnMultipleConstructors.class.getName() + " has more than one @ConstructorBinding constructor"); } @Test void deduceBindMethodWithMultipleConstructorsReturnJavaBean() { BindMethod bindType = ConfigurationPropertiesBean .deduceBindMethod(NoConstructorBindingOnMultipleConstructors.class); assertThat(bindType).isEqualTo(BindMethod.JAVA_BEAN); } @Test void deduceBindMethodWithNoArgConstructorReturnsJavaBean() { BindMethod bindType = ConfigurationPropertiesBean.deduceBindMethod(JavaBeanWithNoArgConstructor.class); assertThat(bindType).isEqualTo(BindMethod.JAVA_BEAN); } @Test void deduceBindMethodWithSingleArgAutowiredConstructorReturnsJavaBean() { BindMethod bindType = ConfigurationPropertiesBean.deduceBindMethod(JavaBeanWithAutowiredConstructor.class); assertThat(bindType).isEqualTo(BindMethod.JAVA_BEAN); } @Test void constructorBindingAndAutowiredConstructorsShouldThrowException() { assertThatIllegalStateException().isThrownBy( () -> ConfigurationPropertiesBean.deduceBindMethod(ConstructorBindingAndAutowiredConstructors.class)); } @Test void innerClassWithSyntheticFieldShouldReturnJavaBean() { BindMethod bindType = ConfigurationPropertiesBean.deduceBindMethod(Inner.class); assertThat(bindType).isEqualTo(BindMethod.JAVA_BEAN); } @Test void innerClassWithParameterizedConstructorShouldReturnJavaBean() { BindMethod bindType = ConfigurationPropertiesBean.deduceBindMethod(ParameterizedConstructorInner.class); assertThat(bindType).isEqualTo(BindMethod.JAVA_BEAN); } private void get(Class<?> configuration, String beanName, ThrowingConsumer<@Nullable ConfigurationPropertiesBean> consumer) throws Throwable { get(configuration, beanName, true, consumer); } private void getWithoutBeanMetadataCaching(Class<?> configuration, String beanName, ThrowingConsumer<@Nullable ConfigurationPropertiesBean> consumer) throws Throwable { get(configuration, beanName, false, consumer); } private void get(Class<?> configuration, String beanName, boolean cacheBeanMetadata, ThrowingConsumer<@Nullable ConfigurationPropertiesBean> consumer) throws Throwable { try (AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext()) { context.getBeanFactory().setCacheBeanMetadata(cacheBeanMetadata); context.register(configuration); context.refresh(); Object bean = context.getBean(beanName); consumer.accept(ConfigurationPropertiesBean.get(context, bean, beanName)); } } @Component("nonAnnotatedComponent") static
ConfigurationPropertiesBeanTests
java
netty__netty
codec-http2/src/main/java/io/netty/handler/codec/http2/AbstractHttp2ConnectionHandlerBuilder.java
{ "start": 1199, "end": 3616 }
class ____ defines commonly used features required to build {@link Http2ConnectionHandler} instances. * * <h3>Three ways to build a {@link Http2ConnectionHandler}</h3> * <h4>Let the builder create a {@link Http2ConnectionHandler}</h4> * Simply call all the necessary setter methods, and then use {@link #build()} to build a new * {@link Http2ConnectionHandler}. Setting the following properties are prohibited because they are used for * other ways of building a {@link Http2ConnectionHandler}. * conflicts with this option: * <ul> * <li>{@link #connection(Http2Connection)}</li> * <li>{@link #codec(Http2ConnectionDecoder, Http2ConnectionEncoder)}</li> * </ul> * * * <h4>Let the builder use the {@link Http2ConnectionHandler} you specified</h4> * Call {@link #connection(Http2Connection)} to tell the builder that you want to build the handler from the * {@link Http2Connection} you specified. Setting the following properties are prohibited and thus will trigger * an {@link IllegalStateException} because they conflict with this option. * <ul> * <li>{@link #server(boolean)}</li> * <li>{@link #codec(Http2ConnectionDecoder, Http2ConnectionEncoder)}</li> * </ul> * * <h4>Let the builder use the {@link Http2ConnectionDecoder} and {@link Http2ConnectionEncoder} you specified</h4> * Call {@link #codec(Http2ConnectionDecoder, Http2ConnectionEncoder)} to tell the builder that you want to built the * handler from the {@link Http2ConnectionDecoder} and {@link Http2ConnectionEncoder} you specified. Setting the * following properties are prohibited and thus will trigger an {@link IllegalStateException} because they conflict * with this option: * <ul> * <li>{@link #server(boolean)}</li> * <li>{@link #connection(Http2Connection)}</li> * <li>{@link #frameLogger(Http2FrameLogger)}</li> * <li>{@link #headerSensitivityDetector(SensitivityDetector)}</li> * <li>{@link #encoderEnforceMaxConcurrentStreams(boolean)}</li> * <li>{@link #encoderIgnoreMaxHeaderListSize(boolean)}</li> * </ul> * * <h3>Exposing necessary methods in a subclass</h3> * {@link #build()} method and all property access methods are {@code protected}. Choose the methods to expose to the * users of your builder implementation and make them {@code public}. * * @param <T> The type of handler created by this builder. * @param <B> The concrete type of this builder. */ public abstract
which
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ilm/IndexLifecycleFeatureSetUsage.java
{ "start": 3125, "end": 5233 }
class ____ implements ToXContentObject, Writeable { public static final ParseField INDICES_MANAGED_FIELD = new ParseField("indices_managed"); private final Map<String, PhaseStats> phaseStats; private final int indicesManaged; public PolicyStats(Map<String, PhaseStats> phaseStats, int numberIndicesManaged) { this.phaseStats = phaseStats; this.indicesManaged = numberIndicesManaged; } public PolicyStats(StreamInput in) throws IOException { this.phaseStats = in.readMap(PhaseStats::new); this.indicesManaged = in.readVInt(); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeMap(phaseStats, StreamOutput::writeWriteable); out.writeVInt(indicesManaged); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(LifecyclePolicy.PHASES_FIELD.getPreferredName(), phaseStats); builder.field(INDICES_MANAGED_FIELD.getPreferredName(), indicesManaged); builder.endObject(); return builder; } public Map<String, PhaseStats> getPhaseStats() { return phaseStats; } public int getIndicesManaged() { return indicesManaged; } @Override public int hashCode() { return Objects.hash(phaseStats, indicesManaged); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } PolicyStats other = (PolicyStats) obj; return Objects.equals(phaseStats, other.phaseStats) && Objects.equals(indicesManaged, other.indicesManaged); } @Override public String toString() { return Strings.toString(this); } } public static final
PolicyStats
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableHide.java
{ "start": 963, "end": 1270 }
class ____<T> extends AbstractObservableWithUpstream<T, T> { public ObservableHide(ObservableSource<T> source) { super(source); } @Override protected void subscribeActual(Observer<? super T> o) { source.subscribe(new HideDisposable<>(o)); } static final
ObservableHide
java
grpc__grpc-java
xds/src/main/java/io/grpc/xds/client/Locality.java
{ "start": 771, "end": 1056 }
class ____ { public abstract String region(); public abstract String zone(); public abstract String subZone(); public static Locality create(String region, String zone, String subZone) { return new io.grpc.xds.client.AutoValue_Locality(region, zone, subZone); } }
Locality
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/utils/RequestUtil.java
{ "start": 1029, "end": 3251 }
class ____ { public static final String CLIENT_APPNAME_HEADER = "Client-AppName"; /** * Get real client ip from context first, if no value, use * {@link com.alibaba.nacos.core.utils.WebUtils#getRemoteIp(HttpServletRequest)}. * * @param request {@link HttpServletRequest} * @return remote ip address. */ public static String getRemoteIp(HttpServletRequest request) { String remoteIp = RequestContextHolder.getContext().getBasicContext().getAddressContext().getSourceIp(); if (StringUtils.isBlank(remoteIp)) { remoteIp = RequestContextHolder.getContext().getBasicContext().getAddressContext().getRemoteIp(); } if (StringUtils.isBlank(remoteIp)) { remoteIp = WebUtils.getRemoteIp(request); } return remoteIp; } /** * Gets the name of the client application in the header. * * @param request {@link HttpServletRequest} * @return may be return null */ public static String getAppName(HttpServletRequest request) { String result = RequestContextHolder.getContext().getBasicContext().getApp(); return isUnknownApp(result) ? request.getHeader(CLIENT_APPNAME_HEADER) : result; } private static boolean isUnknownApp(String appName) { return StringUtils.isBlank(appName) || StringUtils.equalsIgnoreCase("unknown", appName); } /** * Gets the username of the client application in the Attribute. * * @param request {@link HttpServletRequest} * @return may be return null */ public static String getSrcUserName(HttpServletRequest request) { IdentityContext identityContext = RequestContextHolder.getContext().getAuthContext().getIdentityContext(); String result = StringUtils.EMPTY; if (null != identityContext) { result = (String) identityContext.getParameter( com.alibaba.nacos.plugin.auth.constant.Constants.Identity.IDENTITY_ID); } // If auth is disabled, get username from parameters by agreed key return StringUtils.isBlank(result) ? request.getParameter(Constants.USERNAME) : result; } }
RequestUtil
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/producer/generic/GenericProducerHierarchyTest.java
{ "start": 1263, "end": 1370 }
interface ____<T, R> extends Function<Function<T, R>, Optional<R>> { } @Singleton static
Produced
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/threadsafety/ThreadSafeCheckerTest.java
{ "start": 17421, "end": 17826 }
class ____<T> { // BUG: Diagnostic contains: 'T' is a non-thread-safe type variable private final T t = null; } """) .doTest(); } @Test public void mutableInstantiation() { compilationHelper .addSourceLines( "X.java", """ import com.google.common.collect.ImmutableList; public
Test
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/math/CastUnsignedLongToDoubleEvaluator.java
{ "start": 1184, "end": 3981 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(CastUnsignedLongToDoubleEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator v; private final DriverContext driverContext; private Warnings warnings; public CastUnsignedLongToDoubleEvaluator(Source source, EvalOperator.ExpressionEvaluator v, DriverContext driverContext) { this.source = source; this.v = v; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (LongBlock vBlock = (LongBlock) v.eval(page)) { LongVector vVector = vBlock.asVector(); if (vVector == null) { return eval(page.getPositionCount(), vBlock); } return eval(page.getPositionCount(), vVector).asBlock(); } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += v.baseRamBytesUsed(); return baseRamBytesUsed; } public DoubleBlock eval(int positionCount, LongBlock vBlock) { try(DoubleBlock.Builder result = driverContext.blockFactory().newDoubleBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { switch (vBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } long v = vBlock.getLong(vBlock.getFirstValueIndex(p)); result.appendDouble(Cast.castUnsignedLongToDouble(v)); } return result.build(); } } public DoubleVector eval(int positionCount, LongVector vVector) { try(DoubleVector.FixedBuilder result = driverContext.blockFactory().newDoubleVectorFixedBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { long v = vVector.getLong(p); result.appendDouble(p, Cast.castUnsignedLongToDouble(v)); } return result.build(); } } @Override public String toString() { return "CastUnsignedLongToDoubleEvaluator[" + "v=" + v + "]"; } @Override public void close() { Releasables.closeExpectNoException(v); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
CastUnsignedLongToDoubleEvaluator
java
google__dagger
javatests/dagger/internal/codegen/SubcomponentCreatorValidationTest.java
{ "start": 33615, "end": 33758 }
interface ____ extends Supertype {", " Bar bar();", "", " @Subcomponent.Builder", "
HasSupertype
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/method/configuration/PrePostMethodSecurityConfigurationTests.java
{ "start": 74111, "end": 75924 }
class ____ { private final Map<String, Flight> flights = new ConcurrentHashMap<>(); Iterator<Flight> findAll() { return this.flights.values().iterator(); } Page<Flight> findPage() { return new PageImpl<>(new ArrayList<>(this.flights.values())); } Slice<Flight> findSlice() { return new SliceImpl<>(new ArrayList<>(this.flights.values())); } GeoPage<Flight> findGeoPage() { List<GeoResult<Flight>> results = new ArrayList<>(); for (Flight flight : this.flights.values()) { results.add(new GeoResult<>(flight, new Distance(flight.altitude))); } return new GeoPage<>(new GeoResults<>(results)); } GeoResults<Flight> findGeoResults() { List<GeoResult<Flight>> results = new ArrayList<>(); for (Flight flight : this.flights.values()) { results.add(new GeoResult<>(flight, new Distance(flight.altitude))); } return new GeoResults<>(results); } Flight findById(String id) { return this.flights.get(id); } GeoResult<Flight> findGeoResultFlightById(String id) { Flight flight = this.flights.get(id); return new GeoResult<>(flight, new Distance(flight.altitude)); } Flight save(Flight flight) { this.flights.put(flight.getId(), flight); return flight; } void remove(String id) { this.flights.remove(id); } ResponseEntity<Flight> webFindById(String id) { Flight flight = this.flights.get(id); if (flight == null) { return ResponseEntity.notFound().build(); } return ResponseEntity.ok(flight); } ModelAndView webViewFindById(String id) { Flight flight = this.flights.get(id); if (flight == null) { return new ModelAndView("error", HttpStatusCode.valueOf(404)); } return new ModelAndView("flights", Map.of("flight", flight)); } } @AuthorizeReturnObject static
FlightRepository
java
apache__flink
flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/expressions/resolver/rules/ResolveCallByArgumentsRule.java
{ "start": 34036, "end": 35495 }
class ____ implements TableSemantics { private final QueryOperation operation; private final DataType dataType; private final StaticArgument staticArg; private TableApiTableSemantics( QueryOperation operation, DataType dataType, StaticArgument staticArg) { this.operation = operation; this.dataType = dataType; this.staticArg = staticArg; } @Override public DataType dataType() { final DataType typed = staticArg.getDataType().orElse(null); if (typed != null) { // Typed table argument return typed; } // Untyped table arguments return dataType; } @Override public int[] partitionByColumns() { if (!(operation instanceof PartitionQueryOperation)) { return new int[0]; } final PartitionQueryOperation partitionOperation = (PartitionQueryOperation) operation; return partitionOperation.getPartitionKeys(); } @Override public int[] orderByColumns() { return new int[0]; } @Override public int timeColumn() { return -1; } @Override public Optional<ChangelogMode> changelogMode() { return Optional.empty(); } } private static
TableApiTableSemantics
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/converters/RuntimeParamConverterTest.java
{ "start": 2638, "end": 3480 }
class ____ implements ParamConverterProvider { @SuppressWarnings("unchecked") @Override public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) { if (rawType.equals(Optional.class)) { if (genericType instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType) genericType; Type[] typeArguments = parameterizedType.getActualTypeArguments(); if (typeArguments.length == 1 && typeArguments[0].equals(Integer.class)) { return (ParamConverter<T>) new OptionalIntegerParamConverter(); } } } return null; } } public static
OptionalIntegerParamConverterProvider
java
elastic__elasticsearch
test/test-clusters/src/main/java/org/elasticsearch/test/cluster/local/LocalClusterConfigProvider.java
{ "start": 523, "end": 617 }
interface ____ { void apply(LocalClusterSpecBuilder<?> builder); }
LocalClusterConfigProvider
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-timelineservice-hbase/hadoop-yarn-server-timelineservice-hbase-common/src/main/java/org/apache/hadoop/yarn/server/timelineservice/storage/flow/AggregationOperation.java
{ "start": 2001, "end": 2117 }
enum ____ represents that string. * @param aggOpStr Aggregation operation. * @return the AggregationOperation
that