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
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvLastIntEvaluator.java
{ "start": 853, "end": 2760 }
class ____ extends AbstractMultivalueFunction.AbstractEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(MvLastIntEvaluator.class); public MvLastIntEvaluator(EvalOperator.ExpressionEvaluator field, DriverContext driverContext) { super(driverContext, field); } @Override public String name() { return "MvLast"; } /** * Evaluate blocks containing at least one multivalued field. */ @Override public Block evalNullable(Block fieldVal) { IntBlock v = (IntBlock) fieldVal; int positionCount = v.getPositionCount(); try (IntBlock.Builder builder = driverContext.blockFactory().newIntBlockBuilder(positionCount)) { for (int p = 0; p < positionCount; p++) { int valueCount = v.getValueCount(p); if (valueCount == 0) { builder.appendNull(); continue; } int first = v.getFirstValueIndex(p); int end = first + valueCount; int result = MvLast.process(v, first, end); builder.appendInt(result); } return builder.build(); } } /** * Evaluate blocks containing at least one multivalued field. */ @Override public Block evalNotNullable(Block fieldVal) { IntBlock v = (IntBlock) fieldVal; int positionCount = v.getPositionCount(); try (IntVector.FixedBuilder builder = driverContext.blockFactory().newIntVectorFixedBuilder(positionCount)) { for (int p = 0; p < positionCount; p++) { int valueCount = v.getValueCount(p); int first = v.getFirstValueIndex(p); int end = first + valueCount; int result = MvLast.process(v, first, end); builder.appendInt(result); } return builder.build().asBlock(); } } @Override public long baseRamBytesUsed() { return BASE_RAM_BYTES_USED + field.baseRamBytesUsed(); } public static
MvLastIntEvaluator
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsMocksTest.java
{ "start": 554, "end": 655 }
class ____ extends TestBase { private ReturnsMocks values = new ReturnsMocks();
ReturnsMocksTest
java
apache__flink
flink-filesystems/flink-s3-fs-base/src/main/java/org/apache/flink/fs/s3/common/token/AbstractS3DelegationTokenProvider.java
{ "start": 1725, "end": 4488 }
class ____ implements DelegationTokenProvider { private static final Logger LOG = LoggerFactory.getLogger(AbstractS3DelegationTokenProvider.class); private String region; private String accessKey; private String secretKey; @Override public void init(Configuration configuration) { region = configuration.getString(String.format("%s.region", serviceConfigPrefix()), null); if (!StringUtils.isNullOrWhitespaceOnly(region)) { LOG.debug("Region: " + region); } accessKey = configuration.getString( String.format("%s.access-key", serviceConfigPrefix()), null); if (!StringUtils.isNullOrWhitespaceOnly(accessKey)) { LOG.debug("Access key: " + accessKey); } secretKey = configuration.getString( String.format("%s.secret-key", serviceConfigPrefix()), null); if (!StringUtils.isNullOrWhitespaceOnly(secretKey)) { LOG.debug( "Secret key: " + GlobalConfiguration.HIDDEN_CONTENT + " (sensitive information)"); } } @Override public boolean delegationTokensRequired() { if (StringUtils.isNullOrWhitespaceOnly(region) || StringUtils.isNullOrWhitespaceOnly(accessKey) || StringUtils.isNullOrWhitespaceOnly(secretKey)) { LOG.debug("Not obtaining session credentials because not all configurations are set"); return false; } return true; } @Override public ObtainedDelegationTokens obtainDelegationTokens() throws Exception { LOG.info("Obtaining session credentials token with access key: {}", accessKey); AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder.standard() .withRegion(region) .withCredentials( new AWSStaticCredentialsProvider( new BasicAWSCredentials(accessKey, secretKey))) .build(); GetSessionTokenResult sessionTokenResult = stsClient.getSessionToken(); Credentials credentials = sessionTokenResult.getCredentials(); LOG.info( "Session credentials obtained successfully with access key: {} expiration: {}", credentials.getAccessKeyId(), credentials.getExpiration()); return new ObtainedDelegationTokens( InstantiationUtil.serializeObject(credentials), Optional.of(credentials.getExpiration().getTime())); } }
AbstractS3DelegationTokenProvider
java
quarkusio__quarkus
extensions/resteasy-reactive/rest-client/runtime/src/main/java/io/quarkus/rest/client/reactive/runtime/devui/RestClientsContainer.java
{ "start": 2553, "end": 2953 }
class ____ { public final List<RestClientInfo> clients; public final List<PossibleRestClientInfo> possibleClients; public RestClientData(List<RestClientInfo> clients, List<PossibleRestClientInfo> possibleClients) { this.clients = clients; this.possibleClients = possibleClients; // TODO: present this info } } public static
RestClientData
java
apache__flink
flink-queryable-state/flink-queryable-state-client-java/src/main/java/org/apache/flink/queryablestate/network/Client.java
{ "start": 2625, "end": 2914 }
class ____ every client in the queryable state module. It is using pure netty to send and * receive messages of type {@link MessageBody}. * * @param <REQ> the type of request the client will send. * @param <RESP> the type of response the client expects to receive. */ @Internal public
for
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/aop/introduction/MyDataSourceHelper3.java
{ "start": 378, "end": 903 }
class ____ { private final InjectionPoint<?> injectionPoint; private final Qualifier<?> qualifier; public MyDataSourceHelper3(InjectionPoint<?> injectionPoint, Qualifier<?> qualifier) { this.injectionPoint = injectionPoint; this.qualifier = qualifier; } public String getName() { return Qualifiers.findName(qualifier); } public String getInjectionPointQualifier() { return Qualifiers.findName(injectionPoint.getDeclaringBeanQualifier()); } }
MyDataSourceHelper3
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/script/UpsertCtxMapTests.java
{ "start": 672, "end": 3119 }
class ____ extends ESTestCase { UpsertCtxMap map; Metadata meta; long TS = 922860000000L; @Override @Before public void setUp() throws Exception { super.setUp(); map = new UpsertCtxMap("myIndex", "myId", "create", TS, Map.of("foo", "bar")); meta = map.getMetadata(); } @SuppressWarnings("unchecked") public void testSourceWrapping() { assertThat((Map<String, Object>) map.get("_source"), hasEntry("foo", "bar")); assertThat(map.getSource(), hasEntry("foo", "bar")); } public void testGetters() { assertEquals("myIndex", meta.getIndex()); assertEquals("myId", meta.getId()); assertEquals("create", meta.getOp()); UnsupportedOperationException err = expectThrows(UnsupportedOperationException.class, () -> meta.getVersion()); assertEquals("version is unavailable for insert", err.getMessage()); err = expectThrows(UnsupportedOperationException.class, () -> meta.getRouting()); assertEquals("routing is unavailable for insert", err.getMessage()); } public void testMetadataImmutable() { IllegalArgumentException err = expectThrows(IllegalArgumentException.class, () -> meta.put("_index", "myIndex2")); assertEquals("_index cannot be updated", err.getMessage()); err = expectThrows(IllegalArgumentException.class, () -> meta.put("_id", "myId")); assertEquals("_id cannot be updated", err.getMessage()); err = expectThrows(IllegalArgumentException.class, () -> meta.put("_now", 1234)); assertEquals("_now cannot be updated", err.getMessage()); } public void testValidOps() { List<String> ops = List.of("noop", "create"); for (String op : ops) { meta.setOp(op); assertEquals(op, meta.getOp()); } for (String op : ops) { map.put("op", op); assertEquals(op, map.get("op")); } } public void testNoneOp() { IllegalArgumentException err = expectThrows(IllegalArgumentException.class, () -> meta.setOp("none")); assertEquals("'none' is not allowed, use 'noop' instead", err.getMessage()); meta.put("op", "none"); assertEquals("noop", meta.getOp()); meta.remove("op"); assertEquals("noop", meta.getOp()); meta.put("op", "create"); assertEquals("create", meta.getOp()); } }
UpsertCtxMapTests
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/params/ParameterizedClassIntegrationTests.java
{ "start": 8705, "end": 13755 }
class ____ { @ParameterizedTest @ValueSource(classes = { NullAndEmptySourceConstructorInjectionTestCase.class, NullAndEmptySourceConstructorFieldInjectionTestCase.class }) void supportsNullAndEmptySource(Class<?> classTemplateClass) { var results = executeTestsForClass(classTemplateClass); results.allEvents().assertStatistics(stats -> stats.started(6).succeeded(6)); assertThat(invocationDisplayNames(results)) // .containsExactly("[1] value = null", "[2] value = \"\""); } @ParameterizedTest @ValueSource(classes = { CsvFileSourceConstructorInjectionTestCase.class, CsvFileSourceFieldInjectionTestCase.class }) void supportsCsvFileSource(Class<?> classTemplateClass) { var results = executeTestsForClass(classTemplateClass); results.allEvents().assertStatistics(stats -> stats.started(10).succeeded(10)); assertThat(invocationDisplayNames(results)) // .containsExactly("[1] name = \"foo\", value = \"1\"", "[2] name = \"bar\", value = \"2\"", "[3] name = \"baz\", value = \"3\"", "[4] name = \"qux\", value = \"4\""); } @ParameterizedTest @ValueSource(classes = { SingleEnumSourceConstructorInjectionTestCase.class, SingleEnumSourceFieldInjectionTestCase.class }) void supportsSingleEnumSource(Class<?> classTemplateClass) { var results = executeTestsForClass(classTemplateClass); results.allEvents().assertStatistics(stats -> stats.started(4).succeeded(4)); assertThat(invocationDisplayNames(results)) // .containsExactly("[1] value = FOO"); } @ParameterizedTest @ValueSource(classes = { RepeatedEnumSourceConstructorInjectionTestCase.class, RepeatedEnumSourceFieldInjectionTestCase.class }) void supportsRepeatedEnumSource(Class<?> classTemplateClass) { var results = executeTestsForClass(classTemplateClass); results.allEvents().assertStatistics(stats -> stats.started(6).succeeded(6)); assertThat(invocationDisplayNames(results)) // .containsExactly("[1] value = FOO", "[2] value = BAR"); } @ParameterizedTest @ValueSource(classes = { MethodSourceConstructorInjectionTestCase.class, MethodSourceFieldInjectionTestCase.class }) void supportsMethodSource(Class<?> classTemplateClass) { var results = executeTestsForClass(classTemplateClass); results.allEvents().assertStatistics(stats -> stats.started(6).succeeded(6)); assertThat(invocationDisplayNames(results)) // .containsExactly("[1] value = \"foo\"", "[2] value = \"bar\""); } @Test void doesNotSupportDerivingMethodName() { var results = executeTestsForClass(MethodSourceWithoutMethodNameTestCase.class); results.allEvents().failed() // .assertEventsMatchExactly(finishedWithFailure( message("You must specify a method name when using @MethodSource with @ParameterizedClass"))); } @ParameterizedTest @ValueSource(classes = { FieldSourceConstructorInjectionTestCase.class, FieldSourceFieldInjectionTestCase.class }) void supportsFieldSource(Class<?> classTemplateClass) { var results = executeTestsForClass(classTemplateClass); results.allEvents().assertStatistics(stats -> stats.started(6).succeeded(6)); assertThat(invocationDisplayNames(results)) // .containsExactly("[1] value = \"foo\"", "[2] value = \"bar\""); } @Test void doesNotSupportDerivingFieldName() { var results = executeTestsForClass(FieldSourceWithoutFieldNameTestCase.class); results.allEvents().failed() // .assertEventsMatchExactly(finishedWithFailure( message("You must specify a field name when using @FieldSource with @ParameterizedClass"))); } @ParameterizedTest @ValueSource(classes = { ArgumentsSourceConstructorInjectionTestCase.class, ArgumentsSourceFieldInjectionTestCase.class }) void supportsArgumentsSource(Class<?> classTemplateClass) { var results = executeTestsForClass(classTemplateClass); results.allEvents().assertStatistics(stats -> stats.started(6).succeeded(6)); assertThat(invocationDisplayNames(results)) // .containsExactly("[1] value = \"foo\"", "[2] value = \"bar\""); } @Test void failsWhenNoArgumentsSourceIsDeclared() { var results = executeTestsForClass(NoArgumentSourceTestCase.class); results.containerEvents().assertThatEvents() // .haveExactly(1, event(finishedWithFailure(message( "Configuration error: You must configure at least one arguments source for this @ParameterizedClass")))); } @Test void annotationsAreInherited() { var results = executeTestsForClass(ConcreteInheritanceTestCase.class); int numArgumentSets = 13; var numContainers = numArgumentSets * 3; // once for outer invocation, once for nested class, once for inner invocation var numTests = numArgumentSets * 2; // once for outer test, once for inner test results.containerEvents() // .assertStatistics(stats -> stats.started(numContainers + 2).succeeded(numContainers + 2)); results.testEvents() // .assertStatistics(stats -> stats.started(numTests).succeeded(numTests)); } } @Nested
Sources
java
google__guava
android/guava-tests/test/com/google/common/base/SuppliersTest.java
{ "start": 1918, "end": 2178 }
class ____ implements Supplier<Integer> { int calls = 0; @Override public Integer get() { calls++; return calls * 10; } @Override public String toString() { return "CountingSupplier"; } } static
CountingSupplier
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/annotatewith/WrongAnnotateWithEnum.java
{ "start": 200, "end": 244 }
enum ____ { EXISTING }
WrongAnnotateWithEnum
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/job/config/RuleScopeTests.java
{ "start": 752, "end": 3683 }
class ____ extends AbstractWireSerializingTestCase<RuleScope> { @Override protected RuleScope createTestInstance() { RuleScope.Builder scope = RuleScope.builder(); int count = randomIntBetween(0, 3); for (int i = 0; i < count; ++i) { if (randomBoolean()) { scope.include(randomAlphaOfLength(20), randomAlphaOfLength(20)); } else { scope.exclude(randomAlphaOfLength(20), randomAlphaOfLength(20)); } } return scope.build(); } @Override protected RuleScope mutateInstance(RuleScope instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Writeable.Reader<RuleScope> instanceReader() { return RuleScope::new; } public void testValidate_GivenEmpty() { RuleScope scope = RuleScope.builder().build(); assertThat(scope.isEmpty(), is(true)); scope.validate(Sets.newHashSet("a", "b")); } public void testValidate_GivenMultipleValidFields() { RuleScope scope = RuleScope.builder().include("foo", "filter1").exclude("bar", "filter2").include("foobar", "filter3").build(); assertThat(scope.isEmpty(), is(false)); scope.validate(Sets.newHashSet("foo", "bar", "foobar")); } public void testValidate_GivenNoAvailableFieldsForScope() { RuleScope scope = RuleScope.builder().include("foo", "filter1").build(); assertThat(scope.isEmpty(), is(false)); ElasticsearchStatusException e = expectThrows(ElasticsearchStatusException.class, () -> scope.validate(Collections.emptySet())); assertThat( e.getMessage(), equalTo("Invalid detector rule: scope field 'foo' is invalid; " + "detector has no available fields for scoping") ); } public void testValidate_GivenMultipleFieldsIncludingInvalid() { RuleScope scope = RuleScope.builder().include("foo", "filter1").exclude("bar", "filter2").include("foobar", "filter3").build(); assertThat(scope.isEmpty(), is(false)); ElasticsearchStatusException e = expectThrows( ElasticsearchStatusException.class, () -> scope.validate(new LinkedHashSet<>(Arrays.asList("foo", "foobar"))) ); assertThat(e.getMessage(), equalTo("Invalid detector rule: scope field 'bar' is invalid; select from [foo, foobar]")); } public void testGetReferencedFilters_GivenEmpty() { assertThat(RuleScope.builder().build().getReferencedFilters().isEmpty(), is(true)); } public void testGetReferencedFilters_GivenMultipleFields() { RuleScope scope = RuleScope.builder().include("foo", "filter1").exclude("bar", "filter2").include("foobar", "filter3").build(); assertThat(scope.getReferencedFilters(), contains("filter1", "filter2", "filter3")); } }
RuleScopeTests
java
hibernate__hibernate-orm
hibernate-jcache/src/test/java/org/hibernate/orm/test/jcache/domain/Account.java
{ "start": 148, "end": 505 }
class ____ { private Long id; private Person person; public Account() { // } public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String toString() { return super.toString(); } }
Account
java
elastic__elasticsearch
x-pack/plugin/ml/qa/single-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/ml/integration/InferenceIT.java
{ "start": 624, "end": 4668 }
class ____ extends InferenceTestCase { private static final String MODEL_ID = "a-complex-regression-model"; @Before public void setupModelAndData() throws IOException { putRegressionModel(MODEL_ID, """ { "description": "super complex model for tests", "input": {"field_names": ["avg_cost", "item"]}, "inference_config": { "regression": { "results_field": "regression-value", "num_top_feature_importance_values": 2 } }, "definition": { "preprocessors" : [{ "one_hot_encoding": { "field": "product_type", "hot_map": { "TV": "type_tv", "VCR": "type_vcr", "Laptop": "type_laptop" } } }], "trained_model": { "ensemble": { "feature_names": [], "target_type": "regression", "trained_models": [ { "tree": { "feature_names": [ "avg_cost", "type_tv", "type_vcr", "type_laptop" ], "tree_structure": [ { "node_index": 0, "split_feature": 0, "split_gain": 12, "threshold": 38, "decision_type": "lte", "default_left": true, "left_child": 1, "right_child": 2 }, { "node_index": 1, "leaf_value": 5.0 }, { "node_index": 2, "leaf_value": 2.0 } ], "target_type": "regression" } } ] } } } }"""); } @SuppressWarnings("unchecked") public void testInference() throws Exception { Response response = infer("a-complex-regression-model", "{\"item\": \"TV\", \"avg_cost\": 300}"); assertThat( (List<Double>) XContentMapValues.extractValue("inference_results.regression-value", responseAsMap(response)), equalTo(List.of(2.0)) ); } @SuppressWarnings("unchecked") public void testAllFieldsMissingWarning() throws IOException { Response response = infer("a-complex-regression-model", "{}"); assertThat( (List<String>) XContentMapValues.extractValue("inference_results.warning", responseAsMap(response)), equalTo(List.of("Model [a-complex-regression-model] could not be inferred as all fields were missing")) ); } private Response infer(String modelId, String body) throws IOException { Request request = new Request("POST", "/_ml/trained_models/" + modelId + "/_infer"); request.setJsonEntity(Strings.format(""" { "docs": [%s] } """, body)); return client().performRequest(request); } }
InferenceIT
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/util/concurrent/WeakConcurrentMap.java
{ "start": 8049, "end": 8768 }
class ____<T> { final T key; private final int hashCode; LatentKey(T key) { this.key = key; hashCode = System.identityHashCode(key); } @Override public boolean equals(Object other) { if (other instanceof LatentKey<?>) { return ((LatentKey<?>) other).key == key; } else { return ((WeakKey<?>) other).get() == key; } } @Override public int hashCode() { return hashCode; } } /** * A {@link WeakConcurrentMap} where stale entries are removed as a side effect of interacting with this map. */ public static
LatentKey
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/core/support/AsyncConnectionPoolSupportIntegrationTests.java
{ "start": 1188, "end": 9537 }
class ____ extends TestSupport { private static RedisClient client; private static Set<?> channels; private static RedisURI uri = RedisURI.Builder.redis(host, port).build(); @BeforeAll static void setupClient() { client = RedisClient.create(TestClientResources.create(), uri); client.setOptions(ClientOptions.create()); channels = (ChannelGroup) ReflectionTestUtils.getField(client, "channels"); } @AfterAll static void afterClass() { FastShutdown.shutdown(client); FastShutdown.shutdown(client.getResources()); } @Test void asyncPoolShouldWorkWithWrappedConnections() { BoundedAsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport .createBoundedObjectPool(() -> client.connectAsync(StringCodec.ASCII, uri), BoundedPoolConfig.create()); borrowAndReturn(pool); borrowAndClose(pool); borrowAndCloseAsync(pool); TestFutures.awaitOrTimeout(pool.release(TestFutures.getOrTimeout(pool.acquire()).sync().getStatefulConnection())); TestFutures.awaitOrTimeout(pool.release(TestFutures.getOrTimeout(pool.acquire()).async().getStatefulConnection())); assertThat(channels).hasSize(1); pool.close(); assertThat(channels).isEmpty(); } @Test void asyncPoolWithAsyncCreationWorkWithWrappedConnections() { BoundedAsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport .createBoundedObjectPoolAsync(() -> client.connectAsync(StringCodec.ASCII, uri), BoundedPoolConfig.create(), true) .toCompletableFuture().join(); borrowAndReturn(pool); borrowAndClose(pool); borrowAndCloseAsync(pool); TestFutures.awaitOrTimeout(pool.release(TestFutures.getOrTimeout(pool.acquire()).sync().getStatefulConnection())); TestFutures.awaitOrTimeout(pool.release(TestFutures.getOrTimeout(pool.acquire()).async().getStatefulConnection())); assertThat(channels).hasSize(1); pool.close(); assertThat(channels).isEmpty(); } @Test void asyncPoolShouldCloseConnectionsAboveMaxIdleSize() { GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig(); poolConfig.setMaxIdle(2); BoundedAsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport.createBoundedObjectPool( () -> client.connectAsync(StringCodec.ASCII, uri), CommonsPool2ConfigConverter.bounded(poolConfig)); borrowAndReturn(pool); borrowAndClose(pool); StatefulRedisConnection<String, String> c1 = TestFutures.getOrTimeout(pool.acquire()); StatefulRedisConnection<String, String> c2 = TestFutures.getOrTimeout(pool.acquire()); StatefulRedisConnection<String, String> c3 = TestFutures.getOrTimeout(pool.acquire()); assertThat(channels).hasSize(3); CompletableFuture.allOf(pool.release(c1), pool.release(c2), pool.release(c3)).join(); assertThat(channels).hasSize(2); pool.close(); assertThat(channels).isEmpty(); } @Test void asyncPoolShouldWorkWithPlainConnections() { AsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport .createBoundedObjectPool(() -> client.connectAsync(StringCodec.ASCII, uri), BoundedPoolConfig.create(), false); borrowAndReturn(pool); StatefulRedisConnection<String, String> connection = TestFutures.getOrTimeout(pool.acquire()); assertThat(Proxy.isProxyClass(connection.getClass())).isFalse(); pool.release(connection); pool.close(); } @Test void asyncPoolUsingWrappingShouldPropagateExceptionsCorrectly() { AsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport .createBoundedObjectPool(() -> client.connectAsync(StringCodec.ASCII, uri), BoundedPoolConfig.create()); StatefulRedisConnection<String, String> connection = TestFutures.getOrTimeout(pool.acquire()); RedisCommands<String, String> sync = connection.sync(); sync.set(key, value); try { sync.hgetall(key); fail("Missing RedisCommandExecutionException"); } catch (RedisCommandExecutionException e) { assertThat(e).hasMessageContaining("WRONGTYPE"); } connection.close(); pool.close(); } @Test void wrappedConnectionShouldUseWrappers() { AsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport .createBoundedObjectPool(() -> client.connectAsync(StringCodec.ASCII, uri), BoundedPoolConfig.create()); StatefulRedisConnection<String, String> connection = TestFutures.getOrTimeout(pool.acquire()); RedisCommands<String, String> sync = connection.sync(); assertThat(connection).isInstanceOf(StatefulRedisConnection.class) .isNotInstanceOf(StatefulRedisClusterConnectionImpl.class); assertThat(Proxy.isProxyClass(connection.getClass())).isTrue(); assertThat(sync).isInstanceOf(RedisCommands.class); assertThat(connection.async()).isInstanceOf(RedisAsyncCommands.class).isNotInstanceOf(RedisAsyncCommandsImpl.class); assertThat(connection.reactive()).isInstanceOf(RedisReactiveCommands.class) .isNotInstanceOf(RedisReactiveCommandsImpl.class); assertThat(sync.getStatefulConnection()).isInstanceOf(StatefulRedisConnection.class) .isNotInstanceOf(StatefulRedisConnectionImpl.class).isSameAs(connection); connection.close(); pool.close(); } @Test void wrappedObjectClosedAfterReturn() { AsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport .createBoundedObjectPool(() -> client.connectAsync(StringCodec.ASCII, uri), BoundedPoolConfig.create(), true); StatefulRedisConnection<String, String> connection = TestFutures.getOrTimeout(pool.acquire()); RedisCommands<String, String> sync = connection.sync(); sync.ping(); connection.close(); try { connection.isMulti(); fail("Missing RedisException"); } catch (RedisException e) { assertThat(e).hasMessageContaining("deallocated"); } pool.close(); } @Test void shouldPropagateAsyncFlow() { AsyncPool<StatefulRedisConnection<String, String>> pool = AsyncConnectionPoolSupport .createBoundedObjectPool(() -> client.connectAsync(StringCodec.ASCII, uri), BoundedPoolConfig.create()); CompletableFuture<String> pingResponse = pool.acquire().thenCompose(c -> { return c.async().ping().whenComplete((s, throwable) -> pool.release(c)); }); TestFutures.awaitOrTimeout(pingResponse); assertThat(pingResponse).isCompletedWithValue("PONG"); pool.close(); } private void borrowAndReturn(AsyncPool<StatefulRedisConnection<String, String>> pool) { for (int i = 0; i < 10; i++) { StatefulRedisConnection<String, String> connection = TestFutures.getOrTimeout(pool.acquire()); RedisCommands<String, String> sync = connection.sync(); sync.ping(); TestFutures.awaitOrTimeout(pool.release(connection)); } } private void borrowAndClose(AsyncPool<StatefulRedisConnection<String, String>> pool) { for (int i = 0; i < 10; i++) { StatefulRedisConnection<String, String> connection = TestFutures.getOrTimeout(pool.acquire()); RedisCommands<String, String> sync = connection.sync(); sync.ping(); connection.close(); } } private void borrowAndCloseAsync(AsyncPool<StatefulRedisConnection<String, String>> pool) { for (int i = 0; i < 10; i++) { StatefulRedisConnection<String, String> connection = TestFutures.getOrTimeout(pool.acquire()); RedisCommands<String, String> sync = connection.sync(); sync.ping(); TestFutures.getOrTimeout(connection.closeAsync()); } } }
AsyncConnectionPoolSupportIntegrationTests
java
square__retrofit
retrofit/src/main/java/retrofit2/CompletableFutureCallAdapterFactory.java
{ "start": 1039, "end": 2297 }
class ____ extends CallAdapter.Factory { @Override public @Nullable CallAdapter<?, ?> get( Type returnType, Annotation[] annotations, Retrofit retrofit) { if (getRawType(returnType) != CompletableFuture.class) { return null; } if (!(returnType instanceof ParameterizedType)) { throw new IllegalStateException( "CompletableFuture return type must be parameterized" + " as CompletableFuture<Foo> or CompletableFuture<? extends Foo>"); } Type innerType = getParameterUpperBound(0, (ParameterizedType) returnType); if (getRawType(innerType) != Response.class) { // Generic type is not Response<T>. Use it for body-only adapter. return new BodyCallAdapter<>(innerType); } // Generic type is Response<T>. Extract T and create the Response version of the adapter. if (!(innerType instanceof ParameterizedType)) { throw new IllegalStateException( "Response must be parameterized" + " as Response<Foo> or Response<? extends Foo>"); } Type responseType = getParameterUpperBound(0, (ParameterizedType) innerType); return new ResponseCallAdapter<>(responseType); } @IgnoreJRERequirement private static final
CompletableFutureCallAdapterFactory
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/io/file/tfile/TestTFileComparator2.java
{ "start": 1397, "end": 3544 }
class ____ { private static String ROOT = GenericTestUtils.getTestDir().getAbsolutePath(); private static final String name = "test-tfile-comparator2"; private final static int BLOCK_SIZE = 512; private static final String VALUE = "value"; private static final String jClassLongWritableComparator = "jclass:" + LongWritable.Comparator.class.getName(); private static final long NENTRY = 10000; private static long cube(long n) { return n*n*n; } private static String buildValue(long i) { return String.format("%s-%d", VALUE, i); } @Test public void testSortedLongWritable() throws IOException { Configuration conf = new Configuration(); Path path = new Path(ROOT, name); FileSystem fs = path.getFileSystem(conf); FSDataOutputStream out = fs.create(path); try { TFile.Writer writer = new Writer(out, BLOCK_SIZE, "gz", jClassLongWritableComparator, conf); try { LongWritable key = new LongWritable(0); for (long i=0; i<NENTRY; ++i) { key.set(cube(i-NENTRY/2)); DataOutputStream dos = writer.prepareAppendKey(-1); try { key.write(dos); } finally { dos.close(); } dos = writer.prepareAppendValue(-1); try { dos.write(buildValue(i).getBytes()); } finally { dos.close(); } } } finally { writer.close(); } } finally { out.close(); } FSDataInputStream in = fs.open(path); try { TFile.Reader reader = new TFile.Reader(in, fs.getFileStatus(path) .getLen(), conf); try { TFile.Reader.Scanner scanner = reader.createScanner(); long i=0; BytesWritable value = new BytesWritable(); for (; !scanner.atEnd(); scanner.advance()) { scanner.entry().getValue(value); assertEquals(buildValue(i), new String(value.getBytes(), 0, value .getLength())); ++i; } } finally { reader.close(); } } finally { in.close(); } } }
TestTFileComparator2
java
spring-projects__spring-boot
module/spring-boot-webtestclient/src/main/java/org/springframework/boot/webtestclient/autoconfigure/AutoConfigureWebTestClient.java
{ "start": 1524, "end": 1751 }
interface ____ { /** * The timeout duration for the client (in any format handled by * {@link Duration#parse(CharSequence)}). * @return the web client timeout */ String timeout() default ""; }
AutoConfigureWebTestClient
java
apache__camel
components/camel-slack/src/test/java/org/apache/camel/component/slack/SlackHelperTest.java
{ "start": 1045, "end": 1770 }
class ____ { @Test public void testCreateDefaultSlackConfigForNullServerUrl() { SlackConfig slackConfig = SlackHelper.createSlackConfig(null); assertEquals(SlackConfig.DEFAULT, slackConfig); } @Test public void testCreateDefaultSlackConfigForEmptyServerUrl() { SlackConfig slackConfig = SlackHelper.createSlackConfig(""); assertEquals(SlackConfig.DEFAULT, slackConfig); } @Test public void testCreateSlackConfigForServerUrl() { String serverUrl = "http://foo.bar.com"; SlackConfig slackConfig = SlackHelper.createSlackConfig(serverUrl); assertEquals(serverUrl + "/api/", slackConfig.getMethodsEndpointUrlPrefix()); } }
SlackHelperTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/admin/cluster/node/info/PluginsAndModules.java
{ "start": 1081, "end": 3221 }
class ____ implements ReportingService.Info { private final List<PluginRuntimeInfo> plugins; private final List<PluginDescriptor> modules; public PluginsAndModules(List<PluginRuntimeInfo> plugins, List<PluginDescriptor> modules) { this.plugins = Collections.unmodifiableList(plugins); this.modules = Collections.unmodifiableList(modules); } public PluginsAndModules(StreamInput in) throws IOException { this.plugins = in.readCollectionAsImmutableList(PluginRuntimeInfo::new); this.modules = in.readCollectionAsImmutableList(PluginDescriptor::new); } @Override public void writeTo(StreamOutput out) throws IOException { if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_3_0)) { out.writeCollection(plugins); } else { out.writeCollection(plugins.stream().map(PluginRuntimeInfo::descriptor).toList()); } out.writeCollection(modules); } /** * Returns an ordered list based on plugins name */ public List<PluginRuntimeInfo> getPluginInfos() { return plugins.stream().sorted(Comparator.comparing(p -> p.descriptor().getName())).toList(); } /** * Returns an ordered list based on modules name */ public List<PluginDescriptor> getModuleInfos() { List<PluginDescriptor> modules = new ArrayList<>(this.modules); Collections.sort(modules, Comparator.comparing(PluginDescriptor::getName)); return modules; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startArray("plugins"); for (PluginRuntimeInfo pluginInfo : plugins) { pluginInfo.toXContent(builder, params); } builder.endArray(); // TODO: not ideal, make a better api for this (e.g. with jar metadata, and so on) builder.startArray("modules"); for (PluginDescriptor moduleInfo : getModuleInfos()) { moduleInfo.toXContent(builder, params); } builder.endArray(); return builder; } }
PluginsAndModules
java
quarkusio__quarkus
extensions/jdbc/jdbc-mariadb/deployment/src/test/java/io/quarkus/jdbc/mariadb/deployment/DevServicesMariaDBDatasourceTestCase.java
{ "start": 715, "end": 2434 }
class ____ { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .withEmptyApplication() // Expect no warnings (in particular from Agroal) .setLogRecordPredicate(record -> record.getLevel().intValue() >= Level.WARNING.intValue() // There are other warnings: JDK8, TestContainers, drivers, ... // Ignore them: we're only interested in Agroal here. && record.getMessage().contains("Agroal")) .assertLogRecords(records -> assertThat(records) // This is just to get meaningful error messages, as LogRecord doesn't have a toString() .extracting(LogRecord::getMessage) .isEmpty()); @Inject AgroalDataSource dataSource; @Test public void testDatasource() throws Exception { AgroalConnectionPoolConfiguration configuration = null; try { configuration = dataSource.getConfiguration().connectionPoolConfiguration(); } catch (NullPointerException e) { // we catch the NPE here as we have a proxycd and we can't test dataSource directly fail("Datasource should not be null"); } assertTrue(configuration.connectionFactoryConfiguration().jdbcUrl().contains("jdbc:mariadb:")); assertEquals("quarkus", configuration.connectionFactoryConfiguration().principal().getName()); assertEquals(50, configuration.maxSize()); assertThat(configuration.exceptionSorter()).isInstanceOf(MySQLExceptionSorter.class); try (Connection connection = dataSource.getConnection()) { } } }
DevServicesMariaDBDatasourceTestCase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/mapping/fetch/subselect/SubselectFetchCollectionFromBatchTest.java
{ "start": 1830, "end": 12483 }
class ____ { @Test @JiraKey( value = "HHH-10679") public void testSubselectFetchFromEntityBatch(SessionFactoryScope scope) { final EmployeeGroup[] createdGroups = scope.fromTransaction( (s) -> { EmployeeGroup group1 = new EmployeeGroup(); Employee employee1 = new Employee("Jane"); Employee employee2 = new Employee("Jeff"); group1.addEmployee(employee1); group1.addEmployee(employee2); EmployeeGroup group2 = new EmployeeGroup(); Employee employee3 = new Employee("Joan"); Employee employee4 = new Employee("John"); group2.addEmployee(employee3); group2.addEmployee( employee4 ); s.persist( group1 ); s.persist( group2 ); return new EmployeeGroup[] { group1, group2 }; }); final SQLStatementInspector statementInspector = scope.getCollectingStatementInspector(); statementInspector.clear(); scope.inTransaction( (s) -> { EmployeeGroup[] loadedGroups = new EmployeeGroup[] { s.getReference(EmployeeGroup.class, createdGroups[0].getId()), s.getReference(EmployeeGroup.class, createdGroups[1].getId()) }; // there should have been no SQL queries performed and loadedGroups should only contain proxies assertThat( statementInspector.getSqlQueries() ).hasSize( 0 ); for (EmployeeGroup group : loadedGroups) { assertFalse( Hibernate.isInitialized( group ) ); } // because EmployeeGroup defines batch fetching, both of the EmployeeGroup references // should get initialized when we initialize one of them Hibernate.initialize( loadedGroups[0] ); assertThat( statementInspector.getSqlQueries() ).hasSize( 1 ); assertThat( Hibernate.isInitialized( loadedGroups[0] ) ).isTrue(); assertThat( Hibernate.isInitialized( loadedGroups[1] ) ).isTrue(); // their collections however should still be unintialized assertThat( Hibernate.isInitialized( loadedGroups[0].getEmployees() ) ).isFalse(); assertThat( Hibernate.isInitialized( loadedGroups[1].getEmployees() ) ).isFalse(); statementInspector.clear(); // now initialize the collection in the first; collections in both loadedGroups // should get initialized Hibernate.initialize( loadedGroups[0].getEmployees() ); assertThat( statementInspector.getSqlQueries() ).hasSize( 1 ); // both collections should be initialized assertThat( Hibernate.isInitialized( loadedGroups[0].getEmployees() ) ).isTrue(); assertThat( Hibernate.isInitialized( loadedGroups[1].getEmployees() ) ).isTrue(); } ); } @Test public void testSubselectFetchFromQueryList(SessionFactoryScope scope) { final Long[] createdIds = scope.fromTransaction( (s) -> { EmployeeGroup group1 = new EmployeeGroup(); Employee employee1 = new Employee("Jane"); Employee employee2 = new Employee("Jeff"); group1.addEmployee(employee1); group1.addEmployee(employee2); EmployeeGroup group2 = new EmployeeGroup(); Employee employee3 = new Employee("Joan"); Employee employee4 = new Employee("John"); group2.addEmployee(employee3); group2.addEmployee( employee4 ); s.persist( group1 ); s.persist( group2 ); return new Long[] { group1.id, group2.id }; } ); scope.getSessionFactory().getStatistics().clear(); scope.inTransaction( (s) -> { List<EmployeeGroup> results = s .createQuery( "from EmployeeGroup where id in :groups" ) .setParameterList( "groups", createdIds ) .list(); assertEquals( 1, scope.getSessionFactory().getStatistics().getPrepareStatementCount() ); scope.getSessionFactory().getStatistics().clear(); for (EmployeeGroup group : results) { assertTrue( Hibernate.isInitialized( group ) ); assertFalse( Hibernate.isInitialized( group.getEmployees() ) ); } assertEquals( 0, scope.getSessionFactory().getStatistics().getPrepareStatementCount() ); // now initialize the collection in the first; collections in both groups // should get initialized Hibernate.initialize( results.get( 0 ).getEmployees() ); assertEquals( 1, scope.getSessionFactory().getStatistics().getPrepareStatementCount() ); scope.getSessionFactory().getStatistics().clear(); // all collections should be initialized now for (EmployeeGroup group : results) { assertTrue( Hibernate.isInitialized( group.getEmployees() ) ); } assertEquals( 0, scope.getSessionFactory().getStatistics().getPrepareStatementCount() ); } ); } @Test @JiraKey( value = "HHH-10679") public void testMultiSubselectFetchSamePersisterQueryList(SessionFactoryScope scope) { final Long[] createdIds = scope.fromTransaction( (s) -> { EmployeeGroup group1 = new EmployeeGroup(); Employee employee1 = new Employee("Jane"); Employee employee2 = new Employee("Jeff"); group1.addEmployee( employee1 ); group1.addEmployee( employee2 ); group1.setManager( new Employee( "group1 manager" ) ); group1.getManager().addCollaborator( new Employee( "group1 manager's collaborator#1" ) ); group1.getManager().addCollaborator( new Employee( "group1 manager's collaborator#2" ) ); group1.setLead( new Employee( "group1 lead" ) ); group1.getLead().addCollaborator( new Employee( "group1 lead's collaborator#1" ) ); EmployeeGroup group2 = new EmployeeGroup(); Employee employee3 = new Employee("Joan"); Employee employee4 = new Employee("John"); group2.addEmployee( employee3 ); group2.addEmployee( employee4 ); group2.setManager( new Employee( "group2 manager" ) ); group2.getManager().addCollaborator( new Employee( "group2 manager's collaborator#1" ) ); group2.getManager().addCollaborator( new Employee( "group2 manager's collaborator#2" ) ); group2.getManager().addCollaborator( new Employee( "group2 manager's collaborator#3" ) ); group2.setLead( new Employee( "group2 lead" ) ); group2.getLead().addCollaborator( new Employee( "group2 lead's collaborator#1" ) ); group2.getLead().addCollaborator( new Employee( "group2 lead's collaborator#2" ) ); s.persist( group1 ); s.persist( group2 ); return new Long[] { group1.id, group2.id }; } ); final SessionFactoryImplementor sessionFactory = scope.getSessionFactory(); sessionFactory.getStatistics().clear(); scope.inTransaction( (s) -> { EmployeeGroup[] loadedGroups = new EmployeeGroup[] { s.getReference(EmployeeGroup.class, createdIds[0]), s.getReference(EmployeeGroup.class, createdIds[1]) }; // loadedGroups should only contain proxies assertEquals( 0, sessionFactory.getStatistics().getPrepareStatementCount() ); for (EmployeeGroup group : loadedGroups) { assertFalse( Hibernate.isInitialized( group ) ); } assertEquals( 0, sessionFactory.getStatistics().getPrepareStatementCount() ); for ( EmployeeGroup group : loadedGroups ) { // Both loadedGroups get initialized and are added to the PersistenceContext when i == 0; // Still need to call Hibernate.initialize( loadedGroups[i] ) for i > 0 so that the entity // in the PersistenceContext gets assigned to its respective proxy target (is this a // bug???) Hibernate.initialize( group ); assertTrue( Hibernate.isInitialized( group ) ); assertTrue( Hibernate.isInitialized( group.getLead() ) ); assertFalse( Hibernate.isInitialized( group.getLead().getCollaborators() ) ); assertTrue( Hibernate.isInitialized( group.getManager() ) ); assertFalse( Hibernate.isInitialized( group.getManager().getCollaborators() ) ); // the collections should be uninitialized assertFalse( Hibernate.isInitialized( group.getEmployees() ) ); } // both Group proxies should have been loaded in the same batch; assertEquals( 1, sessionFactory.getStatistics().getPrepareStatementCount() ); sessionFactory.getStatistics().clear(); for ( EmployeeGroup group : loadedGroups ) { assertTrue( Hibernate.isInitialized( group ) ); assertFalse( Hibernate.isInitialized( group.getEmployees() ) ); } assertEquals( 0, sessionFactory.getStatistics().getPrepareStatementCount() ); // now initialize the collection in the first; collections in both loadedGroups // should get initialized Hibernate.initialize( loadedGroups[0].getEmployees() ); assertEquals( 1, sessionFactory.getStatistics().getPrepareStatementCount() ); sessionFactory.getStatistics().clear(); // all EmployeeGroup#employees should be initialized now for (EmployeeGroup group : loadedGroups) { assertTrue( Hibernate.isInitialized( group.getEmployees() ) ); assertFalse( Hibernate.isInitialized( group.getLead().getCollaborators() ) ); assertFalse( Hibernate.isInitialized( group.getManager().getCollaborators() ) ); } assertEquals( 0, sessionFactory.getStatistics().getPrepareStatementCount() ); // now initialize loadedGroups[0].getLead().getCollaborators(); // loadedGroups[1].getLead().getCollaborators() should also be initialized Hibernate.initialize( loadedGroups[0].getLead().getCollaborators() ); assertEquals( 1, sessionFactory.getStatistics().getPrepareStatementCount() ); sessionFactory.getStatistics().clear(); for (EmployeeGroup group : loadedGroups) { assertTrue( Hibernate.isInitialized( group.getLead().getCollaborators() ) ); assertFalse( Hibernate.isInitialized( group.getManager().getCollaborators() ) ); } assertEquals( 0, sessionFactory.getStatistics().getPrepareStatementCount() ); // now initialize loadedGroups[0].getManager().getCollaborators(); // loadedGroups[1].getManager().getCollaborators() should also be initialized Hibernate.initialize( loadedGroups[0].getManager().getCollaborators() ); assertEquals( 1, sessionFactory.getStatistics().getPrepareStatementCount() ); sessionFactory.getStatistics().clear(); for (EmployeeGroup group : loadedGroups) { assertTrue( Hibernate.isInitialized( group.getManager().getCollaborators() ) ); } assertEquals( 0, sessionFactory.getStatistics().getPrepareStatementCount() ); assertEquals( loadedGroups[0].getLead().getCollaborators().size(), loadedGroups[0].getLead().getCollaborators().size() ); assertEquals( loadedGroups[1].getLead().getCollaborators().size(), loadedGroups[1].getLead().getCollaborators().size() ); assertEquals( loadedGroups[0].getManager().getCollaborators().size(), loadedGroups[0].getManager().getCollaborators().size() ); assertEquals( loadedGroups[1].getManager().getCollaborators().size(), loadedGroups[1].getManager().getCollaborators().size() ); assertEquals( 0, sessionFactory.getStatistics().getPrepareStatementCount() ); } ); } @Entity(name = "EmployeeGroup") @Table(name = "EmployeeGroup") @BatchSize(size = 1000) public static
SubselectFetchCollectionFromBatchTest
java
alibaba__nacos
common/src/test/java/com/alibaba/nacos/common/notify/NotifyCenterTest.java
{ "start": 11313, "end": 11468 }
class ____ extends SlowEvent { private static final long serialVersionUID = 5946729801676058102L; } private static
TestSlowEvent1
java
elastic__elasticsearch
x-pack/plugin/mapper-counted-keyword/src/test/java/org/elasticsearch/xpack/countedkeyword/CountedKeywordFieldTypeTests.java
{ "start": 4066, "end": 5224 }
class ____ extends BinaryDocValues { private final List<BytesRef> docValues; private final DocIdSetIterator disi; private int current = -1; private CollectionBasedBinaryDocValues(List<BytesRef> docValues) { this.docValues = docValues; this.disi = DocIdSetIterator.all(docValues.size()); } @Override public BytesRef binaryValue() { return docValues.get(current); } @Override public boolean advanceExact(int target) throws IOException { current = target; return disi.advance(target) == target; } @Override public int docID() { return disi.docID(); } @Override public int nextDoc() throws IOException { current = -1; return disi.nextDoc(); } @Override public int advance(int target) throws IOException { current = -1; return disi.advance(target); } @Override public long cost() { return disi.cost(); } } }
CollectionBasedBinaryDocValues
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configurers/oauth2/server/resource/OAuth2ResourceServerConfigurerTests.java
{ "start": 93217, "end": 93856 }
class ____ { @Bean SecurityFilterChain filterChain(HttpSecurity http) throws Exception { // @formatter:off http .authorizeHttpRequests((requests) -> requests .anyRequest().authenticated()) .oauth2ResourceServer((server) -> server .jwt(Customizer.withDefaults())); return http.build(); // @formatter:on } @Bean JwtDecoder jwtDecoder() { return mock(JwtDecoder.class); } @Bean AuthenticationEventPublisher authenticationEventPublisher() { return mock(AuthenticationEventPublisher.class); } } @Configuration @EnableWebSecurity @EnableWebMvc static
CustomAuthenticationEventPublisher
java
micronaut-projects__micronaut-core
test-suite/src/test/java/io/micronaut/docs/inject/scope/RefreshEventSpec.java
{ "start": 1869, "end": 3718 }
class ____ { private static EmbeddedServer embeddedServer; private static HttpClient client; @BeforeAll static void setup() { embeddedServer = ApplicationContext.run(EmbeddedServer.class, new HashMap<>() {{ put("spec.name", "RefreshEventSpec"); put("spec.lang", "java"); }}, Environment.TEST); client = HttpClient.create(embeddedServer.getURL()); } @AfterAll static void teardown() { if (client != null) { client.close(); } if (embeddedServer != null) { embeddedServer.close(); } } @Test void publishingARefreshEventDestroysBeanWithRefreshableScope() { String firstResponse = fetchForecast(); assertTrue(firstResponse.contains("{\"forecast\":\"Scattered Clouds")); String secondResponse = fetchForecast(); assertEquals(firstResponse, secondResponse); String response = evictForecast(); assertEquals("{\"msg\":\"OK\"}", response); AtomicReference<String> thirdResponse = new AtomicReference<>(fetchForecast()); await().atMost(5, SECONDS).until(() -> { if (!thirdResponse.get().equals(secondResponse)) { return true; } thirdResponse.set(fetchForecast()); return false; }); assertNotEquals(thirdResponse.get(), secondResponse); assertTrue(thirdResponse.get().contains("\"forecast\":\"Scattered Clouds")); } String fetchForecast() { return client.toBlocking().retrieve(HttpRequest.GET("/weather/forecast")); } String evictForecast() { return client.toBlocking().retrieve(HttpRequest.POST("/weather/evict", new LinkedHashMap())); } //tag::weatherService[] @Refreshable // <1> static
RefreshEventSpec
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/context/support/AnnotationConfigWebApplicationContext.java
{ "start": 2124, "end": 2514 }
class ____ as config * locations) as well as via classpath scanning (specifying base packages as config * locations). * * <p>This is essentially the equivalent of * {@link org.springframework.context.annotation.AnnotationConfigApplicationContext * AnnotationConfigApplicationContext} for a web environment. However, in contrast to * {@code AnnotationConfigApplicationContext}, this
names
java
apache__maven
its/core-it-suite/src/test/resources/mng-3693/maven-mng3693-plugin/src/main/java/plugin/MyMojo.java
{ "start": 1738, "end": 2391 }
class ____ extends AbstractMojo { /** * @parameter expression="${project}" * @required */ private MavenProject project; public void execute() throws MojoExecutionException { File pomFile = project.getFile(); File movedPomFile = new File(project.getBuild().getDirectory(), "pom.xml"); movedPomFile.getParentFile().mkdirs(); try { FileUtils.copyFile(pomFile, movedPomFile); } catch (IOException e) { throw new MojoExecutionException("Failed to copy pom file: " + pomFile + " to: " + movedPomFile, e); } project.setFile(movedPomFile); } }
MyMojo
java
spring-projects__spring-security
taglibs/src/test/java/org/springframework/security/taglibs/csrf/AbstractCsrfTagTests.java
{ "start": 1330, "end": 3562 }
class ____ { public MockTag tag; private MockHttpServletRequest request; private MockHttpServletResponse response; @BeforeEach public void setUp() { MockServletContext servletContext = new MockServletContext(); this.request = new MockHttpServletRequest(servletContext); this.response = new MockHttpServletResponse(); MockPageContext pageContext = new MockPageContext(servletContext, this.request, this.response); this.tag = new MockTag(); this.tag.setPageContext(pageContext); } @Test public void noCsrfDoesNotRender() throws JspException, UnsupportedEncodingException { this.tag.handleReturn = "shouldNotBeRendered"; int returned = this.tag.doEndTag(); assertThat(returned).as("The returned value is not correct.").isEqualTo(Tag.EVAL_PAGE); assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.") .isEqualTo(""); } @Test public void hasCsrfRendersReturnedValue() throws JspException, UnsupportedEncodingException { CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf", "abc123def456ghi789"); this.request.setAttribute(CsrfToken.class.getName(), token); this.tag.handleReturn = "fooBarBazQux"; int returned = this.tag.doEndTag(); assertThat(returned).as("The returned value is not correct.").isEqualTo(Tag.EVAL_PAGE); assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.") .isEqualTo("fooBarBazQux"); assertThat(this.tag.token).as("The token is not correct.").isSameAs(token); } @Test public void hasCsrfRendersDifferentValue() throws JspException, UnsupportedEncodingException { CsrfToken token = new DefaultCsrfToken("X-Csrf-Token", "_csrf", "abc123def456ghi789"); this.request.setAttribute(CsrfToken.class.getName(), token); this.tag.handleReturn = "<input type=\"hidden\" />"; int returned = this.tag.doEndTag(); assertThat(returned).as("The returned value is not correct.").isEqualTo(Tag.EVAL_PAGE); assertThat(this.response.getContentAsString()).withFailMessage("The output value is not correct.") .isEqualTo("<input type=\"hidden\" />"); assertThat(this.tag.token).as("The token is not correct.").isSameAs(token); } private static
AbstractCsrfTagTests
java
apache__kafka
metadata/src/main/java/org/apache/kafka/controller/BrokerHeartbeatTracker.java
{ "start": 1515, "end": 5213 }
class ____ { /** * The clock to use. */ private final Time time; /** * The broker session timeout in nanoseconds. */ private final long sessionTimeoutNs; /** * Maps a broker ID and epoch to the last contact time in monotonic nanoseconds. */ private final ConcurrentHashMap<BrokerIdAndEpoch, Long> contactTimes; BrokerHeartbeatTracker(Time time, long sessionTimeoutNs) { this.time = time; this.sessionTimeoutNs = sessionTimeoutNs; this.contactTimes = new ConcurrentHashMap<>(); } Time time() { return time; } /** * Update the contact time for the given broker ID and epoch to be the current time. * * @param idAndEpoch The broker ID and epoch. */ void updateContactTime(BrokerIdAndEpoch idAndEpoch) { updateContactTime(idAndEpoch, time.nanoseconds()); } /** * Update the contact time for the given broker ID and epoch to be the given time. * * @param idAndEpoch The broker ID and epoch. * @param timeNs The monotonic time in nanoseconds. */ void updateContactTime(BrokerIdAndEpoch idAndEpoch, long timeNs) { contactTimes.put(idAndEpoch, timeNs); } /** * Get the contact time for the given broker ID and epoch. * * @param idAndEpoch The broker ID and epoch. * @return The contact time, or Optional.empty if none is known. */ OptionalLong contactTime(BrokerIdAndEpoch idAndEpoch) { Long value = contactTimes.get(idAndEpoch); if (value == null) return OptionalLong.empty(); return OptionalLong.of(value); } /** * Remove either one or zero expired brokers from the map. * * @return The expired broker that was removed, or Optional.empty if there was none. */ Optional<BrokerIdAndEpoch> maybeRemoveExpired() { return maybeRemoveExpired(time.nanoseconds()); } /** * Remove either one or zero expired brokers from the map. * * @param nowNs The current time in monotonic nanoseconds. * * @return The expired broker that was removed, or Optional.empty if there was none. */ Optional<BrokerIdAndEpoch> maybeRemoveExpired(long nowNs) { Iterator<Entry<BrokerIdAndEpoch, Long>> iterator = contactTimes.entrySet().iterator(); while (iterator.hasNext()) { Entry<BrokerIdAndEpoch, Long> entry = iterator.next(); if (isExpired(entry.getValue(), nowNs)) { iterator.remove(); return Optional.of(entry.getKey()); } } return Optional.empty(); } /** * Return true if the given time is outside the expiration window. * If the timestamp has undergone 64-bit rollover, we will not expire anything. * * @param timeNs The provided time in monotonic nanoseconds. * @param nowNs The current time in monotonic nanoseconds. * @return True if the timestamp is expired. */ boolean isExpired(long timeNs, long nowNs) { return (nowNs > timeNs) && (timeNs + sessionTimeoutNs < nowNs); } /** * Return true if the given broker has a session whose time has not yet expired. * * @param idAndEpoch The broker id and epoch. * @return True only if the broker session was found and is still valid. */ boolean hasValidSession(BrokerIdAndEpoch idAndEpoch) { Long timeNs = contactTimes.get(idAndEpoch); if (timeNs == null) return false; return !isExpired(timeNs, time.nanoseconds()); } }
BrokerHeartbeatTracker
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/model/source/spi/IdentifierSourceSimple.java
{ "start": 367, "end": 754 }
interface ____ extends IdentifierSource { /** * Obtain the source descriptor for the identifier attribute. * * @return The identifier attribute source. */ SingularAttributeSource getIdentifierAttributeSource(); /** * Returns the "unsaved" entity identifier value. * * @return the "unsaved" entity identifier value */ String getUnsavedValue(); }
IdentifierSourceSimple
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/pool/exception/OracleExceptionSorterTest_stmt_getMoreResults.java
{ "start": 586, "end": 2545 }
class ____ extends TestCase { private DruidDataSource dataSource; protected void setUp() throws Exception { assertEquals(0, JdbcStatManager.getInstance().getSqlList().size()); dataSource = new DruidDataSource(); dataSource.setExceptionSorter(new OracleExceptionSorter()); dataSource.setDriver(new OracleMockDriver()); dataSource.setUrl("jdbc:mock:xxx"); dataSource.setPoolPreparedStatements(true); dataSource.setMaxOpenPreparedStatements(100); } @Override protected void tearDown() throws Exception { JdbcUtils.close(dataSource); assertEquals(0, DruidDataSourceStatManager.getInstance().getDataSourceList().size()); } public void test_connect() throws Exception { String sql = "SELECT 1"; { DruidPooledConnection conn = dataSource.getConnection(); PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.execute(); pstmt.close(); conn.close(); } DruidPooledConnection conn = dataSource.getConnection(); MockConnection mockConn = conn.unwrap(MockConnection.class); assertNotNull(mockConn); Statement stmt = conn.createStatement(); stmt.execute(sql); SQLException exception = new SQLException("xx", "xxx", 28); mockConn.setError(exception); SQLException stmtErrror = null; try { stmt.getMoreResults(); } catch (SQLException ex) { stmtErrror = ex; } assertNotNull(stmtErrror); assertSame(exception, stmtErrror); SQLException commitError = null; try { conn.commit(); } catch (SQLException ex) { commitError = ex; } assertNotNull(commitError); assertSame(exception, commitError.getCause()); conn.close(); } }
OracleExceptionSorterTest_stmt_getMoreResults
java
FasterXML__jackson-databind
src/test/java/org/hibernate/repackage/cglib/Callback.java
{ "start": 217, "end": 277 }
interface ____ this location. * @author Rob Winch */ public
to
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/inference/trainedmodel/FillMaskConfig.java
{ "start": 8159, "end": 10333 }
class ____ { private VocabularyConfig vocabularyConfig; private Tokenization tokenization; private Integer numTopClasses; private String resultsField; private String maskToken; Builder() {} Builder(FillMaskConfig config) { this.vocabularyConfig = config.vocabularyConfig; this.tokenization = config.tokenization; this.numTopClasses = config.numTopClasses; this.resultsField = config.resultsField; } public FillMaskConfig.Builder setVocabularyConfig(VocabularyConfig vocabularyConfig) { this.vocabularyConfig = vocabularyConfig; return this; } public FillMaskConfig.Builder setTokenization(Tokenization tokenization) { this.tokenization = tokenization; return this; } public FillMaskConfig.Builder setNumTopClasses(Integer numTopClasses) { this.numTopClasses = numTopClasses; return this; } public FillMaskConfig.Builder setResultsField(String resultsField) { this.resultsField = resultsField; return this; } public FillMaskConfig.Builder setMaskToken(String maskToken) { this.maskToken = maskToken; return this; } public FillMaskConfig build() throws IllegalArgumentException { if (tokenization == null) { tokenization = Tokenization.createDefault(); } validateMaskToken(tokenization.getMaskToken()); return new FillMaskConfig(vocabularyConfig, tokenization, numTopClasses, resultsField); } private void validateMaskToken(String tokenizationMaskToken) throws IllegalArgumentException { if (maskToken != null) { if (maskToken.equals(tokenizationMaskToken) == false) { throw new IllegalArgumentException( Strings.format("Mask token requested was [%s] but must be [%s] for this model", maskToken, tokenizationMaskToken) ); } } } } }
Builder
java
apache__rocketmq
broker/src/main/java/org/apache/rocketmq/broker/schedule/ScheduleMessageService.java
{ "start": 24664, "end": 26896 }
class ____ implements Runnable { private final int delayLevel; public HandlePutResultTask(int delayLevel) { this.delayLevel = delayLevel; } @Override public void run() { LinkedBlockingQueue<PutResultProcess> pendingQueue = ScheduleMessageService.this.deliverPendingTable.get(this.delayLevel); PutResultProcess putResultProcess; while ((putResultProcess = pendingQueue.peek()) != null) { try { switch (putResultProcess.getStatus()) { case SUCCESS: ScheduleMessageService.this.updateOffset(this.delayLevel, putResultProcess.getNextOffset()); pendingQueue.remove(); break; case RUNNING: scheduleNextTask(); return; case EXCEPTION: if (!isStarted()) { log.warn("HandlePutResultTask shutdown, info={}", putResultProcess.toString()); return; } log.warn("putResultProcess error, info={}", putResultProcess.toString()); putResultProcess.doResend(); break; case SKIP: log.warn("putResultProcess skip, info={}", putResultProcess.toString()); pendingQueue.remove(); break; } } catch (Exception e) { log.error("HandlePutResultTask exception. info={}", putResultProcess.toString(), e); putResultProcess.doResend(); } } scheduleNextTask(); } private void scheduleNextTask() { if (isStarted()) { ScheduleMessageService.this.handleExecutorService .schedule(new HandlePutResultTask(this.delayLevel), DELAY_FOR_A_SLEEP, TimeUnit.MILLISECONDS); } } } public
HandlePutResultTask
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/selection/methodgenerics/wildcards/IntersectionMapper.java
{ "start": 328, "end": 597 }
interface ____ { IntersectionMapper INSTANCE = Mappers.getMapper( IntersectionMapper.class ); Target map( Source source); default <T extends TypeB & Serializable> T unwrap(Wrapper<? extends T> t) { return t.getWrapped(); }
IntersectionMapper
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/AggregatorReducer.java
{ "start": 632, "end": 1058 }
interface ____ extends Releasable { /** * Adds an aggregation for reduction. In <b>most</b> cases, the assumption will be the all given * aggregations are of the same type (the same type as this aggregation). */ void accept(InternalAggregation aggregation); /** * returns the final aggregation. */ InternalAggregation get(); @Override default void close() {} }
AggregatorReducer
java
google__auto
value/src/main/java/com/google/auto/value/processor/TypeEncoder.java
{ "start": 5792, "end": 6240 }
class ____ for {@link TypeEncoder} * covers the details of annotation encoding. * * @param extraAnnotations additional type annotations to include with the type */ static String encodeWithAnnotations( AnnotatedTypeMirror type, ImmutableList<AnnotationMirror> extraAnnotations) { return encodeWithAnnotations(type, extraAnnotations, ImmutableSet.of()); } /** * Encodes the given type and its type annotations. The
comment
java
apache__camel
components/camel-fory/src/test/java/org/apache/camel/component/fory/ForyTest.java
{ "start": 1041, "end": 1953 }
class ____ extends CamelTestSupport { @Test public void testMarshalAndUnmarshalMap() throws Exception { TestPojo pojo = new TestPojo(); pojo.setName("camel"); MockEndpoint mock = getMockEndpoint("mock:reverse"); mock.expectedMessageCount(1); mock.message(0).body().isInstanceOf(TestPojo.class); mock.message(0).body().isEqualTo(pojo); Object marshalled = template.requestBody("direct:in", pojo); template.sendBody("direct:back", marshalled); mock.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:in").marshal().fory(TestPojo.class); from("direct:back").unmarshal().fory(TestPojo.class).to("mock:reverse"); } }; } }
ForyTest
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java
{ "start": 86497, "end": 96292 }
class ____ extends AbstractFsPathRunner<Integer> { private InputStream in = null; private HttpURLConnection cachedConnection = null; private byte[] readBuffer; private int readOffset; private int readLength; private RunnerState runnerState = RunnerState.SEEK; private URL originalUrl = null; private URL resolvedUrl = null; private final Path path; private final int bufferSize; private long pos = 0; private long fileLength = 0; private FileEncryptionInfo feInfo = null; /* The following methods are WebHdfsInputStream helpers. */ ReadRunner(Path p, int bs) throws IOException { super(GetOpParam.Op.OPEN, p, new BufferSizeParam(bs)); this.path = p; this.bufferSize = bs; getRedirectedUrl(); } private void getRedirectedUrl() throws IOException { URLRunner urlRunner = new URLRunner(GetOpParam.Op.OPEN, null, false, false) { @Override protected URL getUrl() throws IOException { return toUrl(op, path, new BufferSizeParam(bufferSize)); } }; HttpURLConnection conn = urlRunner.run(); String feInfoStr = conn.getHeaderField(FEFINFO_HEADER); if (feInfoStr != null) { Decoder decoder = Base64.getDecoder(); byte[] decodedBytes = decoder.decode( feInfoStr.getBytes(StandardCharsets.UTF_8)); feInfo = PBHelperClient .convert(FileEncryptionInfoProto.parseFrom(decodedBytes)); } String location = conn.getHeaderField("Location"); if (location != null) { // This saves the location for datanode where redirect was issued. // Need to remove offset because seek can be called after open. resolvedUrl = removeOffsetParam(new URL(location)); } else { // This is cached for proxies like httpfsfilesystem. cachedConnection = conn; } originalUrl = super.getUrl(); } int read(byte[] b, int off, int len) throws IOException { if (runnerState == RunnerState.CLOSED) { throw new IOException("Stream closed"); } if (len == 0) { return 0; } // Before the first read, pos and fileLength will be 0 and readBuffer // will all be null. They will be initialized once the first connection // is made. Only after that it makes sense to compare pos and fileLength. if (pos >= fileLength && readBuffer != null) { return -1; } // If a seek is occurring, the input stream will have been closed, so it // needs to be reopened. Use the URLRunner to call AbstractRunner#connect // with the previously-cached resolved URL and with the 'redirected' flag // set to 'true'. The resolved URL contains the URL of the previously // opened DN as opposed to the NN. It is preferable to use the resolved // URL when creating a connection because it does not hit the NN or every // seek, nor does it open a connection to a new DN after every seek. // The redirect flag is needed so that AbstractRunner#connect knows the // URL is already resolved. // Note that when the redirected flag is set, retries are not attempted. // So, if the connection fails using URLRunner, clear out the connection // and fall through to establish the connection using ReadRunner. if (runnerState == RunnerState.SEEK) { try { final URL rurl = new URL(resolvedUrl + "&" + new OffsetParam(pos)); cachedConnection = new URLRunner(GetOpParam.Op.OPEN, rurl, true, false).run(); } catch (IOException ioe) { closeInputStream(RunnerState.DISCONNECTED); } } readBuffer = b; readOffset = off; readLength = len; int count = -1; count = this.run(); if (count >= 0) { statistics.incrementBytesRead(count); pos += count; } else if (pos < fileLength) { throw new EOFException( "Premature EOF: pos=" + pos + " < filelength=" + fileLength); } return count; } void seek(long newPos) throws IOException { if (pos != newPos) { pos = newPos; closeInputStream(RunnerState.SEEK); } } public void close() throws IOException { closeInputStream(RunnerState.CLOSED); } /* The following methods are overriding AbstractRunner methods, * to be called within the retry policy context by runWithRetry. */ @Override protected URL getUrl() throws IOException { // This method is called every time either a read is executed. // The check for connection == null is to ensure that a new URL is only // created upon a new connection and not for every read. if (cachedConnection == null) { // Update URL with current offset. BufferSize doesn't change, but it // still must be included when creating the new URL. updateURLParameters(new BufferSizeParam(bufferSize), new OffsetParam(pos)); originalUrl = super.getUrl(); } return originalUrl; } /* Only make the connection if it is not already open. Don't cache the * connection here. After this method is called, runWithRetry will call * validateResponse, and then call the below ReadRunner#getResponse. If * the code path makes it that far, then we can cache the connection. */ @Override protected HttpURLConnection connect(URL url) throws IOException { HttpURLConnection conn = cachedConnection; if (conn == null) { try { conn = super.connect(url); } catch (IOException e) { closeInputStream(RunnerState.DISCONNECTED); throw e; } } return conn; } /* * This method is used to perform reads within the retry policy context. * This code is relying on runWithRetry to always call the above connect * method and the verifyResponse method prior to calling getResponse. */ @Override Integer getResponse(final HttpURLConnection conn) throws IOException { try { // In the "open-then-read" use case, runWithRetry will have executed // ReadRunner#connect to make the connection and then executed // validateResponse to validate the response code. Only then do we want // to cache the connection. // In the "read-after-seek" use case, the connection is made and the // response is validated by the URLRunner. ReadRunner#read then caches // the connection and the ReadRunner#connect will pass on the cached // connection // In either case, stream initialization is done here if necessary. cachedConnection = conn; if (in == null) { in = initializeInputStream(conn); } int count = in.read(readBuffer, readOffset, readLength); if (count < 0 && pos < fileLength) { throw new EOFException( "Premature EOF: pos=" + pos + " < filelength=" + fileLength); } return Integer.valueOf(count); } catch (IOException e) { String redirectHost = resolvedUrl.getAuthority(); if (excludeDatanodes.getValue() != null) { excludeDatanodes = new ExcludeDatanodesParam(redirectHost + "," + excludeDatanodes.getValue()); } else { excludeDatanodes = new ExcludeDatanodesParam(redirectHost); } // If an exception occurs, close the input stream and null it out so // that if the abstract runner decides to retry, it will reconnect. closeInputStream(RunnerState.DISCONNECTED); throw e; } } @VisibleForTesting InputStream initializeInputStream(HttpURLConnection conn) throws IOException { // Cache the resolved URL so that it can be used in the event of // a future seek operation. resolvedUrl = removeOffsetParam(conn.getURL()); final String cl = conn.getHeaderField(HttpHeaders.CONTENT_LENGTH); InputStream inStream = conn.getInputStream(); if (LOG.isDebugEnabled()) { LOG.debug("open file: " + conn.getURL()); } if (cl != null) { long streamLength = Long.parseLong(cl); fileLength = pos + streamLength; // Java has a bug with >2GB request streams. It won't bounds check // the reads so the transfer blocks until the server times out inStream = new BoundedInputStream(inStream, streamLength); } else { fileLength = getHdfsFileStatus(path).getLen(); } // Wrapping in BufferedInputStream because it is more performant than // BoundedInputStream by itself. runnerState = RunnerState.OPEN; return new BufferedInputStream(inStream, bufferSize); } // Close both the InputStream and the connection. @VisibleForTesting void closeInputStream(RunnerState rs) throws IOException { if (in != null) { in = null; } if (cachedConnection != null) { IOUtils.close(cachedConnection); cachedConnection = null; } runnerState = rs; } /* Getters and Setters */ @VisibleForTesting protected InputStream getInputStream() { return in; } @VisibleForTesting protected void setInputStream(InputStream inStream) { in = inStream; } Path getPath() { return path; } int getBufferSize() { return bufferSize; } long getFileLength() { return fileLength; } void setFileLength(long len) { fileLength = len; } long getPos() { return pos; } protected FileEncryptionInfo getFileEncryptionInfo() { return feInfo; } } }
ReadRunner
java
google__error-prone
core/src/main/java/com/google/errorprone/refaster/UTemplater.java
{ "start": 37306, "end": 37518 }
class ____ and append remainder of full type name with '.' -> '$' String className = type.getQualifiedName().toString(); return className + typeName.substring(className.length()).replace('.', '$'); } }
name
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/doublearray/DoubleArrayAssert_containsOnlyOnce_Test.java
{ "start": 1142, "end": 1985 }
class ____ extends DoubleArrayAssertBaseTest { @Override protected DoubleArrayAssert invoke_api_method() { return assertions.containsOnlyOnce(6d, 8d); } @Override protected void verify_internal_effects() { verify(arrays).assertContainsOnlyOnce(getInfo(assertions), getActual(assertions), arrayOf(6d, 8d)); } @Test void should_pass_with_precision_specified_as_last_argument() { // GIVEN double[] actual = arrayOf(1.0, 2.0); // THEN assertThat(actual).containsOnlyOnce(arrayOf(1.01, 2.0), withPrecision(0.1)); } @Test void should_pass_with_precision_specified_in_comparator() { // GIVEN double[] actual = arrayOf(1.0, 2.0); // THEN assertThat(actual).usingComparatorWithPrecision(0.1) .containsOnlyOnce(1.01, 2.0); } }
DoubleArrayAssert_containsOnlyOnce_Test
java
resilience4j__resilience4j
resilience4j-spring-boot2/src/main/java/io/github/resilience4j/bulkhead/autoconfigure/BulkheadMetricsAutoConfiguration.java
{ "start": 2023, "end": 2787 }
class ____ { @Bean @ConditionalOnProperty(value = "resilience4j.bulkhead.metrics.legacy.enabled", havingValue = "true") @ConditionalOnMissingBean public TaggedBulkheadMetrics registerBulkheadMetrics(BulkheadRegistry bulkheadRegistry) { return TaggedBulkheadMetrics.ofBulkheadRegistry(bulkheadRegistry); } @Bean @ConditionalOnBean(MeterRegistry.class) @ConditionalOnProperty(value = "resilience4j.bulkhead.metrics.legacy.enabled", havingValue = "false", matchIfMissing = true) @ConditionalOnMissingBean public TaggedBulkheadMetricsPublisher taggedBulkheadMetricsPublisher( MeterRegistry meterRegistry) { return new TaggedBulkheadMetricsPublisher(meterRegistry); } }
BulkheadMetricsAutoConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/resource/jdbc/internal/ResultsetsTrackingContainerTest.java
{ "start": 514, "end": 5454 }
class ____ { private ResultsetsTrackingContainer container; @Mock private Statement statement1; @Mock private Statement statement2; @Mock private Statement statement3; @Mock private ResultSet resultSet1; @Mock private ResultSet resultSet2; @Mock private ResultSet resultSet3; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); container = new ResultsetsTrackingContainer(); } @Test void initialStateHasNoRegisteredResources() { assertFalse(container.hasRegisteredResources()); } @Test void registeringSingleStatementShouldWork() { container.registerExpectingNew(statement1); assertTrue(container.hasRegisteredResources()); } @Test void storingAssociatedResultSetForUnregisteredStatementShouldWork() { container.storeAssociatedResultset(statement1, resultSet1); assertTrue(container.hasRegisteredResources()); } @Test void storingMultipleResultSetsForSameStatement() { container.registerExpectingNew(statement1); container.storeAssociatedResultset(statement1, resultSet1); container.storeAssociatedResultset(statement1, resultSet2); ResultSetsSet resultSets = container.getForResultSetRemoval(statement1); assertNotNull(resultSets); List<ResultSet> stored = new ArrayList<>(); resultSets.forEachResultSet(stored::add); assertEquals(2, stored.size()); assertTrue(stored.contains(resultSet1)); assertTrue(stored.contains(resultSet2)); } @Test void removingStatementShouldReturnAssociatedResultSets() { container.registerExpectingNew(statement1); container.storeAssociatedResultset(statement1, resultSet1); ResultSetsSet removed = container.remove(statement1); assertNotNull(removed); List<ResultSet> stored = new ArrayList<>(); removed.forEachResultSet(stored::add); assertEquals(1, stored.size()); assertTrue(stored.contains(resultSet1)); assertFalse(container.hasRegisteredResources()); } @Test void removingNonExistentStatementShouldReturnNull() { assertNull(container.remove(statement1)); } @Test void handlingMultipleStatements() { container.registerExpectingNew(statement1); container.registerExpectingNew(statement2); container.storeAssociatedResultset(statement1, resultSet1); container.storeAssociatedResultset(statement2, resultSet2); assertTrue(container.hasRegisteredResources()); List<Statement> processedStatements = new ArrayList<>(); List<ResultSetsSet> processedResultSets = new ArrayList<>(); container.forEach((stmt, results) -> { processedStatements.add(stmt); processedResultSets.add(results); }); assertEquals(2, processedStatements.size()); assertTrue(processedStatements.contains(statement1)); assertTrue(processedStatements.contains(statement2)); } @Test void clearingShouldRemoveAllResources() { container.registerExpectingNew(statement1); container.registerExpectingNew(statement2); container.storeAssociatedResultset(statement1, resultSet1); container.storeAssociatedResultset(statement2, resultSet2); container.clear(); assertFalse(container.hasRegisteredResources()); assertNull(container.getForResultSetRemoval(statement1)); assertNull(container.getForResultSetRemoval(statement2)); } @Test void trickleDownShouldMoveEntryFromXrefToMainSlot() { container.registerExpectingNew(statement1); container.registerExpectingNew(statement2); container.storeAssociatedResultset(statement1, resultSet1); container.storeAssociatedResultset(statement2, resultSet2); container.remove(statement1); // This should trigger trickle down assertTrue(container.hasRegisteredResources()); assertNotNull(container.getForResultSetRemoval(statement2)); List<Statement> processedStatements = new ArrayList<>(); container.forEach((stmt, results) -> processedStatements.add(stmt)); assertEquals(1, processedStatements.size()); assertEquals(statement2, processedStatements.get(0)); } @Test void getForRemovalShouldReturnCorrectResultSets() { container.registerExpectingNew(statement1); container.storeAssociatedResultset(statement1, resultSet1); ResultSetsSet resultSets = container.getForResultSetRemoval(statement1); assertNotNull(resultSets); List<ResultSet> stored = new ArrayList<>(); resultSets.forEachResultSet(stored::add); assertEquals(1, stored.size()); assertTrue(stored.contains(resultSet1)); } @Test void forEachShouldProcessAllEntries() { container.registerExpectingNew(statement1); container.registerExpectingNew(statement2); container.storeAssociatedResultset(statement1, resultSet1); container.storeAssociatedResultset(statement2, resultSet2); @SuppressWarnings("unchecked") BiConsumer<Statement, ResultSetsSet> mockConsumer = mock(BiConsumer.class); container.forEach(mockConsumer); verify(mockConsumer, times(2)).accept(any(), any()); verify(mockConsumer).accept(eq(statement1), any()); verify(mockConsumer).accept(eq(statement2), any()); } }
ResultsetsTrackingContainerTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/ChainingConstructorIgnoresParameterTest.java
{ "start": 2570, "end": 2754 }
class ____ { HasNestedClassCallerFirst(String foo) { // BUG: Diagnostic contains: this(foo, false) this("somethingElse", false); } static
HasNestedClassCallerFirst
java
apache__flink
flink-queryable-state/flink-queryable-state-runtime/src/main/java/org/apache/flink/queryablestate/server/KvStateServerImpl.java
{ "start": 1659, "end": 4763 }
class ____ extends AbstractServerBase<KvStateInternalRequest, KvStateResponse> implements KvStateServer { /** The {@link KvStateRegistry} to query for state instances. */ private final KvStateRegistry kvStateRegistry; private final KvStateRequestStats stats; private MessageSerializer<KvStateInternalRequest, KvStateResponse> serializer; /** * Creates the state server. * * <p>The server is instantiated using reflection by the {@link * org.apache.flink.runtime.query.QueryableStateUtils#createKvStateServer(String, Iterator, int, * int, KvStateRegistry, KvStateRequestStats) * QueryableStateUtils.createKvStateServer(InetAddress, Iterator, int, int, KvStateRegistry, * KvStateRequestStats)}. * * <p>The server needs to be started via {@link #start()} in order to bind to the configured * bind address. * * @param bindAddress the address to listen to. * @param bindPortIterator the port range to try to bind to. * @param numEventLoopThreads number of event loop threads. * @param numQueryThreads number of query threads. * @param kvStateRegistry {@link KvStateRegistry} to query for state instances. * @param stats the statistics collector. */ public KvStateServerImpl( final String bindAddress, final Iterator<Integer> bindPortIterator, final Integer numEventLoopThreads, final Integer numQueryThreads, final KvStateRegistry kvStateRegistry, final KvStateRequestStats stats) { super( "Queryable State Server", bindAddress, bindPortIterator, numEventLoopThreads, numQueryThreads); this.stats = Preconditions.checkNotNull(stats); this.kvStateRegistry = Preconditions.checkNotNull(kvStateRegistry); } @Override public AbstractServerHandler<KvStateInternalRequest, KvStateResponse> initializeHandler() { this.serializer = new MessageSerializer<>( new KvStateInternalRequest.KvStateInternalRequestDeserializer(), new KvStateResponse.KvStateResponseDeserializer()); return new KvStateServerHandler(this, kvStateRegistry, serializer, stats); } public MessageSerializer<KvStateInternalRequest, KvStateResponse> getSerializer() { Preconditions.checkState( serializer != null, "Server " + getServerName() + " has not been started."); return serializer; } @Override public void start() throws Throwable { super.start(); } @Override public InetSocketAddress getServerAddress() { return super.getServerAddress(); } @Override public void shutdown() { try { shutdownServer().get(10L, TimeUnit.SECONDS); log.info("{} was shutdown successfully.", getServerName()); } catch (Exception e) { log.warn("{} shutdown failed: {}", getServerName(), e); } } }
KvStateServerImpl
java
google__gson
gson/src/main/java/com/google/gson/internal/sql/SqlTypesSupport.java
{ "start": 1338, "end": 2947 }
class ____ { /** {@code true} if {@code java.sql} types are supported, {@code false} otherwise */ public static final boolean SUPPORTS_SQL_TYPES; public static final DateType<? extends Date> DATE_DATE_TYPE; public static final DateType<? extends Date> TIMESTAMP_DATE_TYPE; public static final TypeAdapterFactory DATE_FACTORY; public static final TypeAdapterFactory TIME_FACTORY; public static final TypeAdapterFactory TIMESTAMP_FACTORY; static { boolean sqlTypesSupport; try { Class.forName("java.sql.Date"); sqlTypesSupport = true; } catch (ClassNotFoundException classNotFoundException) { sqlTypesSupport = false; } SUPPORTS_SQL_TYPES = sqlTypesSupport; if (SUPPORTS_SQL_TYPES) { DATE_DATE_TYPE = new DateType<java.sql.Date>(java.sql.Date.class) { @Override protected java.sql.Date deserialize(Date date) { return new java.sql.Date(date.getTime()); } }; TIMESTAMP_DATE_TYPE = new DateType<Timestamp>(Timestamp.class) { @Override protected Timestamp deserialize(Date date) { return new Timestamp(date.getTime()); } }; DATE_FACTORY = SqlDateTypeAdapter.FACTORY; TIME_FACTORY = SqlTimeTypeAdapter.FACTORY; TIMESTAMP_FACTORY = SqlTimestampTypeAdapter.FACTORY; } else { DATE_DATE_TYPE = null; TIMESTAMP_DATE_TYPE = null; DATE_FACTORY = null; TIME_FACTORY = null; TIMESTAMP_FACTORY = null; } } private SqlTypesSupport() {} }
SqlTypesSupport
java
apache__logging-log4j2
log4j-taglib/src/test/java/org/apache/logging/log4j/taglib/ExceptionAwareTagSupportTest.java
{ "start": 1052, "end": 1848 }
class ____ { private ExceptionAwareTagSupport tag; @BeforeEach void setUp() { this.tag = new ExceptionAwareTagSupport() { private static final long serialVersionUID = 1L; }; } @Test void testException() { assertNull(this.tag.getException(), "The exception should be null (1)."); Exception e = new Exception(); this.tag.setException(e); assertSame(e, this.tag.getException(), "The exception is not correct (1)."); this.tag.init(); assertNull(this.tag.getException(), "The exception should be null (2)."); e = new RuntimeException(); this.tag.setException(e); assertSame(e, this.tag.getException(), "The exception is not correct (2)."); } }
ExceptionAwareTagSupportTest
java
spring-projects__spring-framework
spring-core/src/test/java/org/springframework/core/annotation/MergedAnnotationsComposedOnSingleAnnotatedElementTests.java
{ "start": 7704, "end": 7878 }
interface ____ { @AliasFor(annotation = Cacheable.class) String key() default ""; } @FooCache(key = "fooKey") @BarCache(key = "barKey") private static
NoninheritedCache2
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/runtime/src/main/java/org/jboss/resteasy/reactive/server/core/parameters/converters/ParameterConverterSupport.java
{ "start": 240, "end": 1087 }
class ____ { private ParameterConverterSupport() { } /** * Normally the reflective instantiation would not be needed, and we could just instantiate normally, * however that could break dev-mode when the converters are in a different module and non-standard Maven * configuration is used (see <a href="https://github.com/quarkusio/quarkus/issues/39773#issuecomment-2030493539">this</a>) */ public static ParameterConverter create(String className) { try { Class<?> clazz = Class.forName(className, true, Thread.currentThread().getContextClassLoader()); return (ParameterConverter) clazz.getConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException("Unable to create instance of " + className, e); } } }
ParameterConverterSupport
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/comparator/NullSafeComparator.java
{ "start": 1259, "end": 4129 }
class ____<T> implements Comparator<T> { /** * A shared default instance of this comparator, treating nulls lower * than non-null objects. * @see Comparators#nullsLow() */ @SuppressWarnings("rawtypes") public static final NullSafeComparator NULLS_LOW = new NullSafeComparator<>(true); /** * A shared default instance of this comparator, treating nulls higher * than non-null objects. * @see Comparators#nullsHigh() */ @SuppressWarnings("rawtypes") public static final NullSafeComparator NULLS_HIGH = new NullSafeComparator<>(false); private final Comparator<T> nonNullComparator; private final boolean nullsLow; /** * Create a NullSafeComparator that sorts {@code null} based on * the provided flag, working on Comparables. * <p>When comparing two non-null objects, their Comparable implementation * will be used: this means that non-null elements (that this Comparator * will be applied to) need to implement Comparable. * <p>As a convenience, you can use the default shared instances: * {@code NullSafeComparator.NULLS_LOW} and * {@code NullSafeComparator.NULLS_HIGH}. * @param nullsLow whether to treat nulls lower or higher than non-null objects * @see Comparable * @see #NULLS_LOW * @see #NULLS_HIGH */ private NullSafeComparator(boolean nullsLow) { this.nonNullComparator = Comparators.comparable(); this.nullsLow = nullsLow; } /** * Create a NullSafeComparator that sorts {@code null} based on the * provided flag, decorating the given Comparator. * <p>When comparing two non-null objects, the specified Comparator will be used. * The given underlying Comparator must be able to handle the elements that this * Comparator will be applied to. * @param comparator the comparator to use when comparing two non-null objects * @param nullsLow whether to treat nulls lower or higher than non-null objects */ public NullSafeComparator(Comparator<T> comparator, boolean nullsLow) { Assert.notNull(comparator, "Comparator must not be null"); this.nonNullComparator = comparator; this.nullsLow = nullsLow; } @Override public int compare(@Nullable T left, @Nullable T right) { Comparator<T> comparator = this.nullsLow ? Comparator.nullsFirst(this.nonNullComparator) : Comparator.nullsLast(this.nonNullComparator); return comparator.compare(left, right); } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof NullSafeComparator<?> that && this.nonNullComparator.equals(that.nonNullComparator) && this.nullsLow == that.nullsLow)); } @Override public int hashCode() { return Boolean.hashCode(this.nullsLow); } @Override public String toString() { return "NullSafeComparator: non-null comparator [" + this.nonNullComparator + "]; " + (this.nullsLow ? "nulls low" : "nulls high"); } }
NullSafeComparator
java
playframework__playframework
web/play-java-forms/src/test/java/play/data/BlueValidator.java
{ "start": 245, "end": 515 }
class ____ extends Constraints.Validator<String> { public boolean isValid(String value) { return "blue".equals(value); } public F.Tuple<String, Object[]> getErrorMessageKey() { return F.Tuple("notblue", new Object[] {"argOne", "argTwo"}); } }
BlueValidator
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/boot/models/xml/spi/XmlDocumentContext.java
{ "start": 659, "end": 1940 }
interface ____ { /** * The XML document */ XmlDocument getXmlDocument(); EffectiveMappingDefaults getEffectiveDefaults(); /** * Access to the containing ModelsContext */ ModelsContext getModelBuildingContext(); /** * Access to the containing BootstrapContext */ BootstrapContext getBootstrapContext(); /** * Resolve a ClassDetails by name, accounting for XML-defined package name if one. */ default MutableClassDetails resolveJavaType(String name) { try { return (MutableClassDetails) XmlAnnotationHelper.resolveJavaType( name, this ); } catch (Exception e) { final HibernateException hibernateException = new HibernateException( "Unable to resolve Java type " + name ); hibernateException.addSuppressed( e ); throw hibernateException; } } default String resolveClassName(String specifiedName) { final SimpleTypeInterpretation simpleTypeInterpretation = SimpleTypeInterpretation.interpret( specifiedName ); if ( simpleTypeInterpretation != null ) { return simpleTypeInterpretation.getJavaType().getName(); } if ( specifiedName.contains( "." ) ) { return specifiedName; } return StringHelper.qualifyConditionallyIfNot( getXmlDocument().getDefaults().getPackage(), specifiedName ); } }
XmlDocumentContext
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng4747JavaAgentUsedByPluginTest.java
{ "start": 1465, "end": 2287 }
class ____. * * @throws Exception in case of failure */ @Test public void testit() throws Exception { File testDir = extractResources("/mng-4747"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.setEnvironmentVariable("MAVEN_OPTS", "-javaagent:agent.jar"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); Properties props1 = verifier.loadProperties("target/agent.properties"); Properties props2 = verifier.loadProperties("target/plugin.properties"); assertNotNull(props1.get("Mng4747Agent")); assertEquals(props1.get("Mng4747Agent"), props2.get("Mng4747Agent")); } }
loader
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/index/IndexesCreationTest.java
{ "start": 1222, "end": 2638 }
class ____ { @Test public void testTheIndexIsGenerated(ServiceRegistryScope registryScope, DomainModelScope modelScope) { final List<String> commands = new SchemaCreatorImpl( registryScope.getRegistry() ) .generateCreationCommands( modelScope.getDomainModel(), false ); assertThatCreateIndexCommandIsGenerated( "CREATE INDEX FIELD_1_INDEX ON TEST_ENTITY (FIELD_1)", commands ); assertThatCreateIndexCommandIsGenerated( "CREATE INDEX FIELD_2_INDEX ON TEST_ENTITY (FIELD_2 DESC, FIELD_3 ASC)", commands ); assertThatCreateIndexCommandIsGenerated( "CREATE INDEX FIELD_4_INDEX ON TEST_ENTITY (FIELD_4 ASC)", commands ); } private void assertThatCreateIndexCommandIsGenerated(String expectedCommand, List<String> commands) { boolean createIndexCommandIsGenerated = false; for ( String command : commands ) { if ( command.toLowerCase().contains( expectedCommand.toLowerCase() ) ) { createIndexCommandIsGenerated = true; break; } } Assertions.assertTrue( createIndexCommandIsGenerated, "Expected " + expectedCommand + " command not found" ); } @Entity(name = "TestEntity") @Table(name = "TEST_ENTITY", indexes = { @Index(name = "FIELD_1_INDEX", columnList = "FIELD_1"), @Index(name = "FIELD_2_INDEX", columnList = "FIELD_2 DESC, FIELD_3 ASC"), @Index(name = "FIELD_4_INDEX", columnList = "FIELD_4 ASC") } ) public static
IndexesCreationTest
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/cglib/proxy/Dispatcher.java
{ "start": 870, "end": 1171 }
interface ____ extends Callback { /** * Return the object which the original method invocation should * be dispatched. This method is called for <b>every</b> method invocation. * @return an object that can invoke the method */ Object loadObject() throws Exception; }
Dispatcher
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/OptionalMapUnusedValue.java
{ "start": 1849, "end": 3271 }
class ____ extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<ExpressionTree> METHOD_IS_OPTIONAL_MAP = instanceMethod().onExactClass("java.util.Optional").named("map"); private static final Matcher<ExpressionTree> PARENT_IS_STATEMENT = parentNode(kindIs(Kind.EXPRESSION_STATEMENT)); private static final Matcher<MethodInvocationTree> ARG_IS_VOID_COMPATIBLE = argument( 0, anyOf(kindIs(Kind.MEMBER_REFERENCE), OptionalMapUnusedValue::isVoidCompatibleLambda)); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (METHOD_IS_OPTIONAL_MAP.matches(tree, state) && PARENT_IS_STATEMENT.matches(tree, state) && ARG_IS_VOID_COMPATIBLE.matches(tree, state)) { return describeMatch(tree, SuggestedFixes.renameMethodInvocation(tree, "ifPresent", state)); } return NO_MATCH; } // TODO(b/170476239): Cover all the cases in which the argument is void-compatible, see // JLS 15.12.2.1 private static boolean isVoidCompatibleLambda(ExpressionTree tree, VisitorState state) { if (tree instanceof LambdaExpressionTree lambdaTree) { if (lambdaTree.getBodyKind().equals(LambdaExpressionTree.BodyKind.EXPRESSION)) { return kindIs(Kind.METHOD_INVOCATION).matches(lambdaTree.getBody(), state); } } return false; } }
OptionalMapUnusedValue
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/groovy/GroovyBeanDefinitionReaderTests.java
{ "start": 29710, "end": 29844 }
class ____ { Bean5(List<Bean1> people) { this.people = people; } List<Bean1> people; } // bean with Map-valued constructor arg
Bean5
java
quarkusio__quarkus
extensions/panache/hibernate-orm-panache/deployment/src/test/java/io/quarkus/hibernate/orm/panache/deployment/test/record/Person.java
{ "start": 173, "end": 310 }
class ____ extends PanacheEntity { public String firstname; public String lastname; public Status status = Status.ALIVE; }
Person
java
apache__flink
flink-table/flink-sql-client/src/test/java/org/apache/flink/table/client/cli/CliResultViewTest.java
{ "start": 4728, "end": 6074 }
class ____ implements Runnable { private final CliResultView<?> realResultView; @SuppressWarnings("unchecked") public TestingCliResultView( Terminal terminal, ResultDescriptor descriptor, boolean isTableMode, TypedResult<?> typedResult, CountDownLatch cancellationCounterLatch) { if (isTableMode) { realResultView = new CliTableResultView( terminal, descriptor, new TestMaterializedResult( (TypedResult<Integer>) typedResult, cancellationCounterLatch)); } else { realResultView = new CliChangelogResultView( terminal, descriptor, new TestChangelogResult( (TypedResult<List<RowData>>) typedResult, cancellationCounterLatch)); } } @Override public void run() { realResultView.open(); } } private static
TestingCliResultView
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/annotation/AnnotationValueResolver.java
{ "start": 4316, "end": 13911 }
class ____ */ Optional<AnnotationClassValue<?>> annotationClassValue(@NonNull String member); /** * The integer value of the given member. * * @param member The annotation member * @return An {@link OptionalInt} */ OptionalInt intValue(@NonNull String member); /** * The byte value of the given member. * * @return An {@link Optional} of {@link Byte} * @since 3.0.0 */ default Optional<Byte> byteValue() { return byteValue(AnnotationMetadata.VALUE_MEMBER); } /** * The byte value of the given member. * * @param member The annotation member * @return An {@link Optional} of {@link Byte} * @since 3.0.0 */ Optional<Byte> byteValue(@NonNull String member); /** * The char value of the given member. * * @return An {@link Optional} of {@link Character} * @since 3.0.0 */ default Optional<Character> charValue() { return charValue(AnnotationMetadata.VALUE_MEMBER); } /** * The char value of the given member. * * @param member The annotation member * @return An {@link Optional} of {@link Character} * @since 3.0.0 */ Optional<Character> charValue(@NonNull String member); /** * The integer value of the given member. * * @return An {@link OptionalInt} */ default OptionalInt intValue() { return intValue(AnnotationMetadata.VALUE_MEMBER); } /** * The long value of the given member. * * @param member The annotation member * @return An {@link OptionalLong} */ OptionalLong longValue(@NonNull String member); /** * The long value of the given member. * * @return An {@link OptionalLong} */ default OptionalLong longValue() { return longValue(AnnotationMetadata.VALUE_MEMBER); } /** * The short value of the given member. * * @param member The annotation member * @return An {@link Optional} of {@link Short} */ Optional<Short> shortValue(@NonNull String member); /** * The integer value of the given member. * * @return An {@link Optional} of */ default Optional<Short> shortValue() { return shortValue(AnnotationMetadata.VALUE_MEMBER); } /** * The double value of the given member. * * @param member The annotation member * @return An {@link OptionalDouble} */ OptionalDouble doubleValue(@NonNull String member); /** * The float value of the given member. * * @return An {@link Optional} of {@link Float} * @since 3.0.0 */ default Optional<Float> floatValue() { return floatValue(AnnotationMetadata.VALUE_MEMBER); } /** * The double value of the given member. * * @param member The annotation member * @return An {@link OptionalDouble} * @since 3.0.0 */ Optional<Float> floatValue(@NonNull String member); /** * The double value of the given member. * * @return An {@link OptionalDouble} */ default OptionalDouble doubleValue() { return doubleValue(AnnotationMetadata.VALUE_MEMBER); } /** * The string value of the given member. * * @param member The annotation member * @return An {@link OptionalInt} */ Optional<String> stringValue(@NonNull String member); /** * The string value of the given member. * * @return An {@link OptionalInt} */ default Optional<String> stringValue() { return stringValue(AnnotationMetadata.VALUE_MEMBER); } /** * The boolean value of the given member. * * @param member The annotation member * @return An {@link Optional} boolean */ Optional<Boolean> booleanValue(@NonNull String member); /** * The Boolean value of the given member. * * @return An {@link Optional} boolean */ default Optional<Boolean> booleanValue() { return booleanValue(AnnotationMetadata.VALUE_MEMBER); } /** * The string values for the given member. * * @param member The annotation member * @return An array of {@link String} */ @NonNull String[] stringValues(@NonNull String member); /** * The string values for the given member. * * @return An array of {@link String} */ default @NonNull String[] stringValues() { return stringValues(AnnotationMetadata.VALUE_MEMBER); } /** * The boolean[] value for the given member. * * @param member The annotation member * @return An array of {@code boolean} * @since 3.0.0 */ @NonNull boolean[] booleanValues(@NonNull String member); /** * The boolean[] value for the given member. * * @return An array of {@code boolean} * @since 3.0.0 */ default @NonNull boolean[] booleanValues() { return booleanValues(AnnotationMetadata.VALUE_MEMBER); } /** * The byte[] value for the given member. * * @param member The annotation member * @return An array of {@code byte} * @since 3.0.0 */ @NonNull byte[] byteValues(@NonNull String member); /** * The byte[] value for the given member. * * @return An array of {@code byte} * @since 3.0.0 */ default @NonNull byte[] byteValues() { return byteValues(AnnotationMetadata.VALUE_MEMBER); } /** * The char[] value for the given member. * * @param member The annotation member * @return An array of {@code char} * @since 3.0.0 */ @NonNull char[] charValues(@NonNull String member); /** * The char[] value for the given member. * * @return An array of {@code char} * @since 3.0.0 */ default @NonNull char[] charValues() { return charValues(AnnotationMetadata.VALUE_MEMBER); } /** * The int[] value for the given member. * * @param member The annotation member * @return An array of {@code int} * @since 3.0.0 */ @NonNull int[] intValues(@NonNull String member); /** * The int[] value for the given member. * * @return An array of {@code int} * @since 3.0.0 */ default @NonNull int[] intValues() { return intValues(AnnotationMetadata.VALUE_MEMBER); } /** * The double[] value for the given member. * * @param member The annotation member * @return An array of {@code double} * @since 3.0.0 */ @NonNull double[] doubleValues(@NonNull String member); /** * The double[] value for the given member. * * @return An array of {@code double} * @since 3.0.0 */ default @NonNull double[] doubleValues() { return doubleValues(AnnotationMetadata.VALUE_MEMBER); } /** * The long[] value for the given member. * * @param member The annotation member * @return An array of {@code long} * @since 3.0.0 */ @NonNull long[] longValues(@NonNull String member); /** * The long[] value for the given member. * * @return An array of {@code long} * @since 3.0.0 */ default @NonNull long[] longValues() { return longValues(AnnotationMetadata.VALUE_MEMBER); } /** * The float[] value for the given member. * * @param member The annotation member * @return An array of {@code float} * @since 3.0.0 */ @NonNull float[] floatValues(@NonNull String member); /** * The float[] value for the given member. * * @return An array of {@code float} * @since 3.0.0 */ default @NonNull float[] floatValues() { return floatValues(AnnotationMetadata.VALUE_MEMBER); } /** * The short[] value for the given member. * * @param member The annotation member * @return An array of {@code short} * @since 3.0.0 */ @NonNull short[] shortValues(@NonNull String member); /** * The short[] value for the given member. * * @return An array of {@code short} * @since 3.0.0 */ default @NonNull short[] shortValues() { return shortValues(AnnotationMetadata.VALUE_MEMBER); } /** * Is the given member present. * @param member The member * @return True if it is */ boolean isPresent(CharSequence member); /** * @return Is the value of the annotation true. */ default boolean isTrue() { return isTrue(AnnotationMetadata.VALUE_MEMBER); } /** * @param member The member * * @return Is the value of the annotation true. */ boolean isTrue(String member); /** * @return Is the value of the annotation true. */ default boolean isFalse() { return isFalse(AnnotationMetadata.VALUE_MEMBER); } /** * @param member The member * * @return Is the value of the annotation true. */ boolean isFalse(String member); /** * The value of the given annotation member as a Class. * * @param member The annotation member * @param requiredType The required type * @return An {@link Optional} class * @param <T> The required type */ <T> Optional<Class<? extends T>> classValue(@NonNull String member, @NonNull Class<T> requiredType); /** * @return The attribute values */ @NonNull Map<CharSequence, Object> getValues(); }
value
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/offlineEditsViewer/OfflineEditsViewer.java
{ "start": 1521, "end": 1674 }
class ____ an offline edits viewer, tool that * can be used to view edit logs. */ @InterfaceAudience.Private @InterfaceStability.Unstable public
implements
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/filters/AfterFilterClassLevelTest_private.java
{ "start": 260, "end": 1422 }
class ____ extends TestCase { public void test_0() throws Exception { Object[] array = { new ModelA(), new ModelB() }; SerializeConfig config = new SerializeConfig(); config.addFilter(ModelA.class, // new AfterFilter() { @Override public void writeAfter(Object object) { this.writeKeyValue("type", "A"); } }); config.addFilter(ModelB.class, // new AfterFilter() { @Override public void writeAfter(Object object) { this.writeKeyValue("type", "B"); } }); String text2 = JSON.toJSONString(array, config); Assert.assertEquals("[{\"id\":1001,\"type\":\"A\"},{\"id\":1002,\"type\":\"B\"}]", text2); String text = JSON.toJSONString(array); Assert.assertEquals("[{\"id\":1001},{\"id\":1002}]", text); } private static
AfterFilterClassLevelTest_private
java
spring-projects__spring-framework
spring-jms/src/main/java/org/springframework/jms/MessageNotReadableException.java
{ "start": 860, "end": 1025 }
class ____ extends JmsException { public MessageNotReadableException(jakarta.jms.MessageNotReadableException cause) { super(cause); } }
MessageNotReadableException
java
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/mediatype/InvalidAcceptTest.java
{ "start": 676, "end": 1394 }
class ____ { @RegisterExtension static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest() .setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(HelloResource.class); } }); @Test public void test() { given().config(config().encoderConfig(encoderConfig().encodeContentTypeAs("invalid", ContentType.TEXT))).body("dummy") .accept("invalid").get("/hello") .then() .statusCode(406); } @Path("hello") public static
InvalidAcceptTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/MissingFailTest.java
{ "start": 23008, "end": 24077 }
class ____ { @Test public void f() throws Exception { Path p = Paths.get("NOSUCH"); try { Files.readAllBytes(p); Files.readAllBytes(p); } catch (IOException e) { assertThat(e).hasMessageThat().contains("NOSUCH"); } } @Test public void g() throws Exception { Path p = Paths.get("NOSUCH"); try { Files.readAllBytes(p); } catch (IOException e) { assertThat(e).hasMessageThat().contains("NOSUCH"); } } } """) .addOutputLines( "out/ExceptionTest.java", """ import static com.google.common.truth.Truth.assertThat; import static org.junit.Assert.assertThrows; import java.io.IOException; import java.nio.file.*; import org.junit.Test;
ExceptionTest
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/RecordQueue.java
{ "start": 1899, "end": 9446 }
class ____ { public static final long UNKNOWN = ConsumerRecord.NO_TIMESTAMP; private final Logger log; private final SourceNode<?, ?> source; private final TopicPartition partition; private final ProcessorContext<?, ?> processorContext; private final TimestampExtractor timestampExtractor; private final RecordDeserializer recordDeserializer; private final ArrayDeque<ConsumerRecord<byte[], byte[]>> fifoQueue; private StampedRecord headRecord = null; private long partitionTime = UNKNOWN; private final Sensor droppedRecordsSensor; private final Sensor consumedSensor; private long headRecordSizeInBytes; RecordQueue(final TopicPartition partition, final SourceNode<?, ?> source, final TimestampExtractor timestampExtractor, final DeserializationExceptionHandler deserializationExceptionHandler, final InternalProcessorContext<?, ?> processorContext, final LogContext logContext) { this.source = source; this.partition = partition; this.fifoQueue = new ArrayDeque<>(); this.timestampExtractor = timestampExtractor; this.processorContext = processorContext; final String threadName = Thread.currentThread().getName(); droppedRecordsSensor = TaskMetrics.droppedRecordsSensor( threadName, processorContext.taskId().toString(), processorContext.metrics() ); consumedSensor = TopicMetrics.consumedSensor( threadName, processorContext.taskId().toString(), source.name(), partition.topic(), processorContext.metrics() ); recordDeserializer = new RecordDeserializer( source, deserializationExceptionHandler, logContext, droppedRecordsSensor ); this.log = logContext.logger(RecordQueue.class); this.headRecordSizeInBytes = 0L; } void setPartitionTime(final long partitionTime) { this.partitionTime = partitionTime; } /** * Returns the corresponding source node in the topology * * @return SourceNode */ public SourceNode<?, ?> source() { return source; } /** * Returns the partition with which this queue is associated * * @return TopicPartition */ public TopicPartition partition() { return partition; } /** * Add a batch of {@link ConsumerRecord} into the queue * * @param rawRecords the raw records * @return the size of this queue */ int addRawRecords(final Iterable<ConsumerRecord<byte[], byte[]>> rawRecords) { for (final ConsumerRecord<byte[], byte[]> rawRecord : rawRecords) { fifoQueue.addLast(rawRecord); } updateHead(); return size(); } /** * Get the next {@link StampedRecord} from the queue * * @return StampedRecord */ public StampedRecord poll(final long wallClockTime) { final StampedRecord recordToReturn = headRecord; consumedSensor.record(headRecordSizeInBytes, wallClockTime); headRecord = null; headRecordSizeInBytes = 0L; partitionTime = Math.max(partitionTime, recordToReturn.timestamp); updateHead(); return recordToReturn; } /** * Returns the number of records in the queue * * @return the number of records */ public int size() { // plus one deserialized head record for timestamp tracking return fifoQueue.size() + (headRecord == null ? 0 : 1); } /** * Tests if the queue is empty * * @return true if the queue is empty, otherwise false */ public boolean isEmpty() { return fifoQueue.isEmpty() && headRecord == null; } /** * Returns the head record's timestamp * * @return timestamp */ public long headRecordTimestamp() { return headRecord == null ? UNKNOWN : headRecord.timestamp; } public Long headRecordOffset() { return headRecord == null ? null : headRecord.offset(); } /** * Returns the leader epoch of the head record if it exists * * @return An Optional containing the leader epoch of the head record, or null if the queue is empty. The Optional.empty() * is reserved for the case when the leader epoch is not set for head record of the queue. */ @SuppressWarnings("OptionalAssignedToNull") public Optional<Integer> headRecordLeaderEpoch() { return headRecord == null ? null : headRecord.leaderEpoch(); } /** * Clear the fifo queue of its elements */ public void clear() { fifoQueue.clear(); headRecord = null; headRecordSizeInBytes = 0L; partitionTime = UNKNOWN; } public void close() { processorContext.metrics().removeSensor(consumedSensor); } private void updateHead() { ConsumerRecord<byte[], byte[]> lastCorruptedRecord = null; while (headRecord == null && !fifoQueue.isEmpty()) { final ConsumerRecord<byte[], byte[]> raw = fifoQueue.pollFirst(); final ConsumerRecord<Object, Object> deserialized = recordDeserializer.deserialize(processorContext, raw); if (deserialized == null) { // this only happens if the deserializer decides to skip. It has already logged the reason. lastCorruptedRecord = raw; continue; } final long timestamp; try { timestamp = timestampExtractor.extract(deserialized, partitionTime); } catch (final StreamsException internalFatalExtractorException) { throw internalFatalExtractorException; } catch (final Exception fatalUserException) { throw new StreamsException( String.format("Fatal user code error in TimestampExtractor callback for record %s.", deserialized), fatalUserException); } log.trace("Source node {} extracted timestamp {} for record {}", source.name(), timestamp, deserialized); // drop message if TS is invalid, i.e., negative if (timestamp < 0) { log.warn( "Skipping record due to negative extracted timestamp. topic=[{}] partition=[{}] offset=[{}] extractedTimestamp=[{}] extractor=[{}]", deserialized.topic(), deserialized.partition(), deserialized.offset(), timestamp, timestampExtractor.getClass().getCanonicalName() ); droppedRecordsSensor.record(); lastCorruptedRecord = raw; continue; } headRecord = new StampedRecord(deserialized, timestamp, raw.key(), raw.value()); headRecordSizeInBytes = consumerRecordSizeInBytes(raw); } // if all records in the FIFO queue are corrupted, make the last one the headRecord // This record is used to update the offsets. See KAFKA-6502 for more details. if (headRecord == null && lastCorruptedRecord != null) { headRecord = new CorruptedRecord(lastCorruptedRecord); } } /** * @return the local partitionTime for this particular RecordQueue */ long partitionTime() { return partitionTime; } }
RecordQueue
java
quarkusio__quarkus
integration-tests/smallrye-graphql/src/main/java/io/quarkus/it/smallrye/graphql/Morning.java
{ "start": 77, "end": 410 }
class ____ extends Greeting { private TimeOfDay timeOfDay = TimeOfDay.MORNING; public Morning() { super("Good Morning", LocalTime.now()); } public TimeOfDay getTimeOfDay() { return timeOfDay; } public void setTimeOfDay(TimeOfDay timeOfDay) { this.timeOfDay = timeOfDay; } }
Morning
java
apache__camel
components/camel-jcache/src/test/java/org/apache/camel/component/jcache/policy/SpringJCachePolicyTest.java
{ "start": 1567, "end": 6497 }
class ____ extends CamelSpringTestSupport { @Override protected AbstractApplicationContext createApplicationContext() { return newAppContext("/org/apache/camel/component/jcache/policy/SpringJCachePolicyTest.xml"); } @BeforeEach public void before() { //reset mock MockEndpoint mock = getMockEndpoint("mock:spring"); mock.reset(); mock.whenAnyExchangeReceived(e -> e.getMessage().setBody(generateValue(e.getMessage().getBody(String.class)))); } //Verify value gets cached and route is not executed for the second time @Test public void testXmlDslValueGetsCached() { final String key = randomString(); MockEndpoint mock = getMockEndpoint("mock:spring"); //Send first, key is not in cache Object responseBody = this.template().requestBody("direct:spring", key); //We got back the value, mock was called once, value got cached. Cache cache = lookupCache("spring"); assertEquals(generateValue(key), cache.get(key)); assertEquals(generateValue(key), responseBody); assertEquals(1, mock.getExchanges().size()); //Send again, key is already in cache responseBody = this.template().requestBody("direct:spring", key); //We got back the stored value, but the mock was not called again assertEquals(generateValue(key), cache.get(key)); assertEquals(generateValue(key), responseBody); assertEquals(1, mock.getExchanges().size()); } //Verify if we call the route with different keys, both gets cached @Test public void testXmlDslDifferent() { final String key1 = randomString(); MockEndpoint mock = getMockEndpoint("mock:spring"); //Send first, key is not in cache Object responseBody = this.template().requestBody("direct:spring", key1); //We got back the value, mock was called once, value got cached. Cache cache = lookupCache("spring"); assertEquals(generateValue(key1), cache.get(key1)); assertEquals(generateValue(key1), responseBody); assertEquals(1, mock.getExchanges().size()); //Send again, different key final String key2 = randomString(); responseBody = this.template().requestBody("direct:spring", key2); //We got back the stored value, mock was called again, value got cached. assertEquals(generateValue(key2), cache.get(key2)); assertEquals(generateValue(key2), responseBody); assertEquals(2, mock.getExchanges().size()); } //Verify policy applies only on the section of the route wrapped @Test public void testXmlDslPartial() { final String key = randomString(); MockEndpoint mock = getMockEndpoint("mock:spring"); MockEndpoint mockUnwrapped = getMockEndpoint("mock:unwrapped"); //Send first, key is not in cache Object responseBody = this.template().requestBody("direct:spring-partial", key); //We got back the value, mock was called once, value got cached. Cache cache = lookupCache("spring"); assertEquals(generateValue(key), cache.get(key)); assertEquals(generateValue(key), responseBody); assertEquals(1, mock.getExchanges().size()); assertEquals(1, mockUnwrapped.getExchanges().size()); //Send again, key is already in cache responseBody = this.template().requestBody("direct:spring-partial", key); //We got back the stored value, but the mock was not called again assertEquals(generateValue(key), cache.get(key)); assertEquals(generateValue(key), responseBody); assertEquals(1, mock.getExchanges().size()); assertEquals(2, mockUnwrapped.getExchanges().size()); } //Use a key expression ${header.mykey} @Test public void testXmlDslKeyExpression() { final String key = randomString(); final String body = randomString(); MockEndpoint mock = getMockEndpoint("mock:spring"); //Send first, key is not in cache Object responseBody = this.template().requestBodyAndHeader("direct:spring-byheader", body, "mykey", key); //We got back the value, mock was called once, value got cached. Cache cache = lookupCache("spring"); assertEquals(generateValue(body), cache.get(key)); assertEquals(generateValue(body), responseBody); assertEquals(1, mock.getExchanges().size()); //Send again, use another body, but the same key responseBody = this.template().requestBodyAndHeader("direct:spring-byheader", randomString(), "mykey", key); //We got back the stored value, and the mock was not called again assertEquals(generateValue(body), cache.get(key)); assertEquals(generateValue(body), responseBody); assertEquals(1, mock.getExchanges().size()); } }
SpringJCachePolicyTest
java
quarkusio__quarkus
integration-tests/hibernate-orm-panache/src/main/java/io/quarkus/it/panache/defaultpu/Bug5885AbstractRepository.java
{ "start": 118, "end": 190 }
class ____<T> implements PanacheRepository<T> { }
Bug5885AbstractRepository
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/validation/BindingElementValidator.java
{ "start": 16758, "end": 17014 }
enum ____ { /** This element disallows scoping, so check that no scope annotations are present. */ NO_SCOPING, /** This element allows scoping, so validate that there's at most one scope annotation. */ ALLOWS_SCOPING, ; } }
AllowsScoping
java
google__gson
gson/src/test/java/com/google/gson/reflect/TypeTokenTest.java
{ "start": 12670, "end": 13148 }
class ____ extends TypeToken<String> {} @Test public void testTypeTokenNonAnonymousSubclass() { TypeToken<?> typeToken = new CustomTypeToken(); assertThat(typeToken.getRawType()).isEqualTo(String.class); assertThat(typeToken.getType()).isEqualTo(String.class); } /** * User must only create direct subclasses of TypeToken, but not subclasses of subclasses (...) of * TypeToken. */ @Test public void testTypeTokenSubSubClass() {
CustomTypeToken
java
FasterXML__jackson-core
src/main/java/tools/jackson/core/json/JsonReadContext.java
{ "start": 334, "end": 8136 }
class ____ extends TokenStreamContext { // // // Configuration /** * Parent context for this context; null for root context. */ protected final JsonReadContext _parent; // // // Optional duplicate detection protected DupDetector _dups; /* /********************************************************************** /* Simple instance reuse slots; speeds up things a bit (10-15%) /* for docs with lots of small arrays/objects (for which /* allocation was visible in profile stack frames) /********************************************************************** */ protected JsonReadContext _child; /* /********************************************************************** /* Location/state information (minus source reference) /********************************************************************** */ protected String _currentName; protected Object _currentValue; protected int _lineNr; protected int _columnNr; /* /********************************************************************** /* Instance construction, config, reuse /********************************************************************** */ /** * @param parent Parent context, if any ({@code null} for Root context) * @param nestingDepth Number of parents this context has (0 for Root context) * @param dups Detector used for checking duplicate names, if any ({@code null} if none) * @param type Type to assign to this context node * @param lineNr Line of the starting position of this context * @param colNr Column of the starting position of this context * * @since 2.15 */ public JsonReadContext(JsonReadContext parent, int nestingDepth, DupDetector dups, int type, int lineNr, int colNr) { super(); _parent = parent; _dups = dups; _type = type; _lineNr = lineNr; _columnNr = colNr; _index = -1; _nestingDepth = nestingDepth; } /** * Internal method to allow instance reuse: DO NOT USE unless you absolutely * know what you are doing. * Clears up state (including "current value"), changes type to one specified; * resets current duplicate-detection state (if any). * Parent link left as-is since it is {@code final}. * * @param type Type to assign to this context node * @param lineNr Line of the starting position of this context * @param colNr Column of the starting position of this context * * @return This context instance (to allow call-chaining) */ public JsonReadContext reset(int type, int lineNr, int colNr) { _type = type; _index = -1; _lineNr = lineNr; _columnNr = colNr; _currentName = null; _currentValue = null; if (_dups != null) { _dups.reset(); } return this; } /* public void trackDups(JsonParser p) { _dups = DupDetector.rootDetector(p); } */ public JsonReadContext withDupDetector(DupDetector dups) { _dups = dups; return this; } @Override public Object currentValue() { return _currentValue; } @Override public void assignCurrentValue(Object v) { _currentValue = v; } /* /********************************************************************** /* Factory methods /********************************************************************** */ public static JsonReadContext createRootContext(int lineNr, int colNr, DupDetector dups) { return new JsonReadContext(null, 0, dups, TYPE_ROOT, lineNr, colNr); } public static JsonReadContext createRootContext(DupDetector dups) { return new JsonReadContext(null, 0, dups, TYPE_ROOT, 1, 0); } public JsonReadContext createChildArrayContext(int lineNr, int colNr) { JsonReadContext ctxt = _child; if (ctxt == null) { _child = ctxt = new JsonReadContext(this, _nestingDepth+1, (_dups == null) ? null : _dups.child(), TYPE_ARRAY, lineNr, colNr); } else { ctxt.reset(TYPE_ARRAY, lineNr, colNr); } return ctxt; } public JsonReadContext createChildObjectContext(int lineNr, int colNr) { JsonReadContext ctxt = _child; if (ctxt == null) { _child = ctxt = new JsonReadContext(this, _nestingDepth+1, (_dups == null) ? null : _dups.child(), TYPE_OBJECT, lineNr, colNr); return ctxt; } ctxt.reset(TYPE_OBJECT, lineNr, colNr); return ctxt; } /* /********************************************************************** /* Abstract method implementations, overrides /********************************************************************** */ /** * @since 3.0 */ @Override public String currentName() { return _currentName; } @Override public boolean hasCurrentName() { return _currentName != null; } @Override public JsonReadContext getParent() { return _parent; } @Override public TokenStreamLocation startLocation(ContentReference srcRef) { // We don't keep track of offsets at this level (only reader does) long totalChars = -1L; return new TokenStreamLocation(ContentReference.rawReference(srcRef), totalChars, _lineNr, _columnNr); } /* /********************************************************************** /* Extended API /********************************************************************** */ /** * Method that can be used to both clear the accumulated references * (specifically value set with {@link #assignCurrentValue(Object)}) * that should not be retained, and returns parent (as would * {@link #getParent()} do). Typically called when closing the active * context when encountering {@link JsonToken#END_ARRAY} or * {@link JsonToken#END_OBJECT}. * * @return Parent context of this context node, if any; {@code null} for root context */ public JsonReadContext clearAndGetParent() { _currentValue = null; // could also clear the current name, but seems cheap enough to leave? return _parent; } public DupDetector getDupDetector() { return _dups; } /* /********************************************************************** /* State changes /********************************************************************** */ public boolean expectComma() { /* Assumption here is that we will be getting a value (at least * before calling this method again), and * so will auto-increment index to avoid having to do another call */ int ix = ++_index; // starts from -1 return (_type != TYPE_ROOT && ix > 0); } /** * Method that parser is to call when it reads a name of Object property. * * @param name Property name that has been read * * @throws StreamReadException if duplicate check restriction is violated (which * assumes that duplicate-detection is enabled) */ public void setCurrentName(String name) throws StreamReadException { _currentName = name; if (_dups != null) { _checkDup(_dups, name); } } private void _checkDup(DupDetector dd, String name) throws StreamReadException { if (dd.isDup(name)) { Object src = dd.getSource(); throw new StreamReadException(((src instanceof JsonParser) ? ((JsonParser) src) : null), "Duplicate Object property \""+name+"\""); } } }
JsonReadContext
java
apache__camel
tooling/maven/camel-eip-documentation-enricher-maven-plugin/src/test/java/org/apache/camel/maven/integration/EIPDocumentationMojoTest.java
{ "start": 1711, "end": 5244 }
class ____ { EipDocumentationEnricherMojo eipDocumentationEnricherMojo = new EipDocumentationEnricherMojo(); XPath xPath = XPathFactory.newInstance().newXPath(); File tempFile; @BeforeEach public void setUp() throws Exception { eipDocumentationEnricherMojo.camelCoreModelDir = ResourceUtils.getResourceAsFile("integration/camel-core-integration"); eipDocumentationEnricherMojo.camelCoreXmlDir = ResourceUtils.getResourceAsFile("integration/camel-core-integration"); eipDocumentationEnricherMojo.camelSpringDir = ResourceUtils.getResourceAsFile("integration/camel-core-integration"); eipDocumentationEnricherMojo.inputCamelSchemaFile = ResourceUtils.getResourceAsFile("integration/camel-spring.xsd"); eipDocumentationEnricherMojo.pathToModelDir = "trgt/classes/org/apache/camel/model"; eipDocumentationEnricherMojo.pathToCoreXmlModelDir = "trgt/classes/org/apache/camel/model"; eipDocumentationEnricherMojo.pathToSpringModelDir = "trgt/classes/org/apache/camel/model"; xPath.setNamespaceContext(new CamelSpringNamespace()); tempFile = File.createTempFile("outputXml", ".xml"); tempFile.deleteOnExit(); eipDocumentationEnricherMojo.outputCamelSchemaFile = tempFile; } @Test public void testExecuteMojo() throws Exception { eipDocumentationEnricherMojo.execute(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); documentBuilderFactory.setCoalescing(true); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document doc = documentBuilder.parse(tempFile); validateElement(doc); validateAttributes(doc); validateParentAttribute(doc); } private void validateParentAttribute(Document doc) throws Exception { Element e = (Element) xPath.compile("//xs:attribute[@name='id']").evaluate(doc, XPathConstants.NODE); assertEquals("id", e.getAttribute(Constants.NAME_ATTRIBUTE_NAME)); validateDocumentation(e, "id documentation"); } private void validateAttributes(Document doc) throws Exception { Element e = (Element) xPath.compile("//xs:attribute[@name='beforeUri']").evaluate(doc, XPathConstants.NODE); assertEquals("beforeUri", e.getAttribute(Constants.NAME_ATTRIBUTE_NAME)); validateDocumentation(e, "beforeUri documentation"); } private void validateElement(Document doc) { NodeList element = doc.getElementsByTagName("xs:element"); Element e = (Element) element.item(0); assertEquals("aop", e.getAttribute(Constants.NAME_ATTRIBUTE_NAME)); validateDocumentation(e, "element documentation"); } private void validateDocumentation(Element element, String expectedText) { Element annotation = getFirsElement(element.getChildNodes()); Element documentation = getFirsElement(annotation.getChildNodes()); assertEquals("xs:annotation", annotation.getTagName()); assertEquals("xs:documentation", documentation.getTagName()); Node cdata = documentation.getFirstChild(); assertThat(cdata, instanceOf(CharacterData.class)); CharacterData cd = (CharacterData) cdata; assertThat(cd.getData(), containsString(expectedText)); } private Element getFirsElement(NodeList nodeList) { return (Element) nodeList.item(1); } }
EIPDocumentationMojoTest
java
apache__rocketmq
proxy/src/main/java/org/apache/rocketmq/proxy/processor/BatchAckResult.java
{ "start": 1038, "end": 1884 }
class ____ { private final ReceiptHandleMessage receiptHandleMessage; private AckResult ackResult; private ProxyException proxyException; public BatchAckResult(ReceiptHandleMessage receiptHandleMessage, AckResult ackResult) { this.receiptHandleMessage = receiptHandleMessage; this.ackResult = ackResult; } public BatchAckResult(ReceiptHandleMessage receiptHandleMessage, ProxyException proxyException) { this.receiptHandleMessage = receiptHandleMessage; this.proxyException = proxyException; } public ReceiptHandleMessage getReceiptHandleMessage() { return receiptHandleMessage; } public AckResult getAckResult() { return ackResult; } public ProxyException getProxyException() { return proxyException; } }
BatchAckResult
java
elastic__elasticsearch
modules/ingest-common/src/main/java/org/elasticsearch/ingest/common/DateIndexNameProcessor.java
{ "start": 5174, "end": 8508 }
class ____ implements Processor.Factory { private final ScriptService scriptService; public Factory(ScriptService scriptService) { this.scriptService = scriptService; } @Override public DateIndexNameProcessor create( Map<String, Processor.Factory> registry, String tag, String description, Map<String, Object> config, ProjectId projectId ) throws Exception { String localeString = ConfigurationUtils.readOptionalStringProperty(TYPE, tag, config, "locale"); String timezoneString = ConfigurationUtils.readOptionalStringProperty(TYPE, tag, config, "timezone"); ZoneId timezone = timezoneString == null ? ZoneOffset.UTC : ZoneId.of(timezoneString); Locale locale = Locale.ENGLISH; if (localeString != null) { try { locale = (new Locale.Builder()).setLanguageTag(localeString).build(); } catch (IllformedLocaleException e) { throw new IllegalArgumentException("Invalid language tag specified: " + localeString); } } List<String> dateFormatStrings = ConfigurationUtils.readOptionalList(TYPE, tag, config, "date_formats"); if (dateFormatStrings == null) { dateFormatStrings = Collections.singletonList("yyyy-MM-dd'T'HH:mm:ss.SSSXX"); } List<Function<String, ZonedDateTime>> dateFormats = new ArrayList<>(dateFormatStrings.size()); for (String format : dateFormatStrings) { DateFormat dateFormat = DateFormat.fromString(format); dateFormats.add(dateFormat.getFunction(format, timezone, locale)); } String field = ConfigurationUtils.readStringProperty(TYPE, tag, config, "field"); String indexNamePrefix = ConfigurationUtils.readStringProperty(TYPE, tag, config, "index_name_prefix", ""); TemplateScript.Factory indexNamePrefixTemplate = ConfigurationUtils.compileTemplate( TYPE, tag, "index_name_prefix", indexNamePrefix, scriptService ); String dateRounding = ConfigurationUtils.readStringProperty(TYPE, tag, config, "date_rounding"); TemplateScript.Factory dateRoundingTemplate = ConfigurationUtils.compileTemplate( TYPE, tag, "date_rounding", dateRounding, scriptService ); String indexNameFormat = ConfigurationUtils.readStringProperty(TYPE, tag, config, "index_name_format", "yyyy-MM-dd"); TemplateScript.Factory indexNameFormatTemplate = ConfigurationUtils.compileTemplate( TYPE, tag, "index_name_format", indexNameFormat, scriptService ); return new DateIndexNameProcessor( tag, description, field, dateFormats, timezone, indexNamePrefixTemplate, dateRoundingTemplate, indexNameFormatTemplate ); } } }
Factory
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/IdClassRepresentationStrategy.java
{ "start": 940, "end": 2708 }
class ____ implements EmbeddableRepresentationStrategy { private final JavaType<?> idClassType; private final EmbeddableInstantiator instantiator; public IdClassRepresentationStrategy( IdClassEmbeddable idClassEmbeddable, boolean simplePropertyOrder, Supplier<String[]> attributeNamesAccess) { idClassType = idClassEmbeddable.getMappedJavaType(); final var javaTypeClass = idClassType.getJavaTypeClass(); if ( javaTypeClass.isRecord() ) { instantiator = simplePropertyOrder ? new EmbeddableInstantiatorRecordStandard( javaTypeClass ) : EmbeddableInstantiatorRecordIndirecting.of( javaTypeClass, attributeNamesAccess.get() ); } else { instantiator = new EmbeddableInstantiatorPojoStandard( idClassType.getJavaTypeClass(), () -> idClassEmbeddable ); } } @Override public EmbeddableInstantiator getInstantiator() { return instantiator; } @Override public RepresentationMode getMode() { return RepresentationMode.POJO; } @Override public ReflectionOptimizer getReflectionOptimizer() { return null; } @Override public JavaType<?> getMappedJavaType() { return idClassType; } @Override public PropertyAccess resolvePropertyAccess(Property bootAttributeDescriptor) { final var strategy = bootAttributeDescriptor.getPropertyAccessStrategy( idClassType.getJavaTypeClass() ); if ( strategy == null ) { throw new HibernateException( String.format( Locale.ROOT, "Could not resolve PropertyAccess for attribute `%s#%s`", idClassType.getTypeName(), bootAttributeDescriptor.getName() ) ); } return strategy.buildPropertyAccess( idClassType.getJavaTypeClass(), bootAttributeDescriptor.getName(), false ); } }
IdClassRepresentationStrategy
java
google__dagger
javatests/dagger/internal/codegen/MissingBindingValidationTest.java
{ "start": 28860, "end": 30201 }
interface ____ {", " UsesTest usesTest();", "}"); CompilerTests.daggerCompiler(generic, testClass, usesTest, component) .withProcessingOptions(compilerMode.processorOptions()) .compile( subject -> { subject.hasErrorCount(1); subject.hasErrorContaining( String.join( "\n", "List cannot be provided without an @Provides-annotated method.", "", " List is injected at", " [TestComponent] TestClass(list)", " TestClass is injected at", " [TestComponent] Generic(t)", " Generic<TestClass> is injected at", " [TestComponent] UsesTest(genericTestClass)", " UsesTest is requested at", " [TestComponent] TestComponent.usesTest()")); }); } @Test public void resolvedVariablesInDependencyTrace() { Source generic = CompilerTests.javaSource( "test.Generic", "package test;", "", "import javax.inject.Inject;", "import javax.inject.Provider;", "", "final
TestComponent
java
elastic__elasticsearch
x-pack/plugin/ccr/src/test/java/org/elasticsearch/xpack/ccr/action/ActivateAutoFollowPatternActionRequestTests.java
{ "start": 718, "end": 2275 }
class ____ extends AbstractWireSerializingTestCase<ActivateAutoFollowPatternAction.Request> { @Override protected ActivateAutoFollowPatternAction.Request createTestInstance() { return new ActivateAutoFollowPatternAction.Request( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, randomAlphaOfLength(5), randomBoolean() ); } @Override protected ActivateAutoFollowPatternAction.Request mutateInstance(ActivateAutoFollowPatternAction.Request instance) { return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929 } @Override protected Writeable.Reader<ActivateAutoFollowPatternAction.Request> instanceReader() { return ActivateAutoFollowPatternAction.Request::new; } public void testValidate() { ActivateAutoFollowPatternAction.Request request = new ActivateAutoFollowPatternAction.Request( TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, null, true ); ActionRequestValidationException validationException = request.validate(); assertThat(validationException, notNullValue()); assertThat(validationException.getMessage(), containsString("[name] is missing")); request = new ActivateAutoFollowPatternAction.Request(TEST_REQUEST_TIMEOUT, TEST_REQUEST_TIMEOUT, "name", true); validationException = request.validate(); assertThat(validationException, nullValue()); } }
ActivateAutoFollowPatternActionRequestTests
java
quarkusio__quarkus
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/config/ConfigSource.java
{ "start": 1451, "end": 1861 }
class ____ implements ConfigSource { final Path configFile; public FileConfigSource(Path configFile) { this.configFile = configFile; } @Override public Path getFilePath() { return configFile; } @Override public String describe() { return String.format("file: %s", configFile); } } }
FileConfigSource
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/builder/nestedprop/flattening/ImmutableFlattenedStock.java
{ "start": 217, "end": 893 }
class ____ { private final String article1; private final String article2; private final int articleCount; public ImmutableFlattenedStock(String article1, String article2, int count) { this.article1 = article1; this.article2 = article2; this.articleCount = count; } public String getArticle1() { return article1; } public String getArticle2() { return article2; } public int getArticleCount() { return articleCount; } public static ImmutableFlattenedStock.Builder builder() { return new ImmutableFlattenedStock.Builder(); } public static
ImmutableFlattenedStock
java
elastic__elasticsearch
libs/plugin-api/src/main/java/org/elasticsearch/plugin/Nameable.java
{ "start": 857, "end": 1159 }
interface ____ not annotated */ default String name() { NamedComponent[] annotationsByType = this.getClass().getAnnotationsByType(NamedComponent.class); if (annotationsByType.length == 1) { return annotationsByType[0].value(); } return null; } }
is
java
quarkusio__quarkus
extensions/vertx/deployment/src/test/java/io/quarkus/vertx/VertxContextSupportTest.java
{ "start": 1659, "end": 3900 }
class ____ { @Inject Bravo bravo; String val; final List<Integer> vals = new CopyOnWriteArrayList<>(); final CountDownLatch latch = new CountDownLatch(1); void onStart(@Observes StartupEvent event) { // Request context is active but duplicated context is not used String bravoId = bravo.getId(); Supplier<Uni<String>> uniSupplier = new Supplier<Uni<String>>() { @Override public Uni<String> get() { assertTrue(VertxContext.isOnDuplicatedContext()); VertxContextSafetyToggle.validateContextIfExists("Error", "Error"); assertTrue(Arc.container().requestContext().isActive()); // New duplicated contex -> new request context String asyncBravoId = bravo.getId(); assertNotEquals(bravoId, asyncBravoId); return VertxContextSupport.executeBlocking(() -> { assertTrue(BlockingOperationControl.isBlockingAllowed()); assertTrue(VertxContext.isOnDuplicatedContext()); assertTrue(Arc.container().requestContext().isActive()); // Duplicated context is propagated -> the same request context assertEquals(asyncBravoId, bravo.getId()); return "foo"; }); } }; try { val = VertxContextSupport.subscribeAndAwait(uniSupplier); } catch (Throwable e) { fail(e); } Supplier<Multi<Integer>> multiSupplier = new Supplier<Multi<Integer>>() { @Override public Multi<Integer> get() { assertTrue(VertxContext.isOnDuplicatedContext()); VertxContextSafetyToggle.validateContextIfExists("Error", "Error"); return Multi.createFrom().items(1, 2, 3, 4, 5); } }; VertxContextSupport.subscribe(multiSupplier, ms -> ms.with(vals::add, latch::countDown)); } } @RequestScoped public static
Alpha
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/any/discriminator/mixed/Order.java
{ "start": 1006, "end": 2159 }
class ____ { @Id public Integer id; @Basic public String name; //tag::associations-any-mixed-discriminator-full-example[] @Any @AnyKeyJavaClass( Integer.class ) @JoinColumn(name = "full_mixed_fk") @Column(name = "full_mixed_type") @AnyDiscriminatorImplicitValues(FULL_NAME) @AnyDiscriminatorValue( discriminator = "CARD", entity = CardPayment.class ) @AnyDiscriminatorValue( discriminator = "CHECK", entity = CheckPayment.class ) public Payment paymentMixedFullName; //end::associations-any-mixed-discriminator-full-example[] //tag::associations-any-mixed-discriminator-short-example[] @Any @AnyKeyJavaClass( Integer.class ) @JoinColumn(name = "short_mixed_fk") @Column(name = "short_mixed_type") @AnyDiscriminatorImplicitValues(SHORT_NAME) @AnyDiscriminatorValue( discriminator = "CARD", entity = CardPayment.class ) @AnyDiscriminatorValue( discriminator = "CHECK", entity = CheckPayment.class ) public Payment paymentMixedShortName; //end::associations-any-mixed-discriminator-short-example[] protected Order() { // for Hibernate use } public Order(Integer id, String name) { this.id = id; this.name = name; } }
Order
java
spring-projects__spring-boot
module/spring-boot-session-data-redis/src/dockerTest/java/org/springframework/boot/session/data/redis/autoconfigure/SessionDataRedisAutoConfigurationTests.java
{ "start": 2781, "end": 10903 }
class ____ extends AbstractSessionAutoConfigurationTests { @Container public static RedisContainer redis = TestImage.container(RedisContainer.class); @BeforeEach void prepareContextRunner() { this.contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(SessionAutoConfiguration.class, SessionDataRedisAutoConfiguration.class, DataRedisAutoConfiguration.class)); } @Test void defaultConfig() { this.contextRunner .withPropertyValues("spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) .withConfiguration(AutoConfigurations.of(DataRedisAutoConfiguration.class)) .run(validateSpringSessionUsesDefaultRedis("spring:session:", FlushMode.ON_SAVE, SaveMode.ON_SET_ATTRIBUTE)); } @Test void invalidConfigurationPropertyValueWhenDefaultConfigIsUsedWithCustomCronCleanup() { this.contextRunner .withPropertyValues("spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort(), "spring.session.data.redis.cleanup-cron=0 0 * * * *") .withConfiguration(AutoConfigurations.of(DataRedisAutoConfiguration.class)) .run((context) -> { assertThat(context).hasFailed(); assertThat(context.getStartupFailure()) .hasRootCauseExactlyInstanceOf(InvalidConfigurationPropertyValueException.class); }); } @Test void defaultConfigWithCustomTimeout() { this.contextRunner .withPropertyValues("spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort(), "spring.session.timeout=1m") .run((context) -> { RedisSessionRepository repository = validateSessionRepository(context, RedisSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", Duration.ofMinutes(1)); }); } @Test void defaultRedisSessionStoreWithCustomizations() { this.contextRunner .withPropertyValues("spring.session.data.redis.namespace=foo", "spring.session.data.redis.flush-mode=immediate", "spring.session.data.redis.save-mode=on-get-attribute", "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) .run(validateSpringSessionUsesDefaultRedis("foo:", FlushMode.IMMEDIATE, SaveMode.ON_GET_ATTRIBUTE)); } @Test void indexedRedisSessionDefaultConfig() { this.contextRunner .withPropertyValues("spring.session.data.redis.repository-type=indexed", "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) .withConfiguration(AutoConfigurations.of(DataRedisAutoConfiguration.class)) .run(validateSpringSessionUsesIndexedRedis("spring:session:", FlushMode.ON_SAVE, SaveMode.ON_SET_ATTRIBUTE, "0 * * * * *")); } @Test void indexedRedisSessionStoreWithCustomizations() { this.contextRunner .withPropertyValues("spring.session.data.redis.repository-type=indexed", "spring.session.data.redis.namespace=foo", "spring.session.data.redis.flush-mode=immediate", "spring.session.data.redis.save-mode=on-get-attribute", "spring.session.data.redis.cleanup-cron=0 0 12 * * *", "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) .run(validateSpringSessionUsesIndexedRedis("foo:", FlushMode.IMMEDIATE, SaveMode.ON_GET_ATTRIBUTE, "0 0 12 * * *")); } @Test void indexedRedisSessionWithConfigureActionNone() { this.contextRunner .withPropertyValues("spring.session.data.redis.repository-type=indexed", "spring.session.data.redis.configure-action=none", "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) .run(validateStrategy(ConfigureRedisAction.NO_OP.getClass())); } @Test void indexedRedisSessionWithDefaultConfigureActionNone() { this.contextRunner .withPropertyValues("spring.session.data.redis.repository-type=indexed", "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) .run(validateStrategy(ConfigureNotifyKeyspaceEventsAction.class, entry("notify-keyspace-events", "gxE"))); } @Test void indexedRedisSessionWithCustomConfigureRedisActionBean() { this.contextRunner.withUserConfiguration(MaxEntriesRedisAction.class) .withPropertyValues("spring.session.data.redis.repository-type=indexed", "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) .run(validateStrategy(MaxEntriesRedisAction.class, entry("set-max-intset-entries", "1024"))); } @Test void whenTheUserDefinesTheirOwnSessionRepositoryCustomizerThenDefaultConfigurationIsOverwritten() { this.contextRunner.withUserConfiguration(CustomizerConfiguration.class) .withPropertyValues("spring.session.data.redis.flush-mode=immediate", "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) .run((context) -> { RedisSessionRepository repository = validateSessionRepository(context, RedisSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("flushMode", FlushMode.ON_SAVE); }); } @Test void whenIndexedAndTheUserDefinesTheirOwnSessionRepositoryCustomizerThenDefaultConfigurationIsOverwritten() { this.contextRunner.withUserConfiguration(IndexedCustomizerConfiguration.class) .withPropertyValues("spring.session.data.redis.repository-type=indexed", "spring.session.data.redis.flush-mode=immediate", "spring.data.redis.host=" + redis.getHost(), "spring.data.redis.port=" + redis.getFirstMappedPort()) .run((context) -> { RedisIndexedSessionRepository repository = validateSessionRepository(context, RedisIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("flushMode", FlushMode.ON_SAVE); }); } private ContextConsumer<AssertableWebApplicationContext> validateSpringSessionUsesDefaultRedis(String keyNamespace, FlushMode flushMode, SaveMode saveMode) { return (context) -> { RedisSessionRepository repository = validateSessionRepository(context, RedisSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", new ServerProperties().getServlet().getSession().getTimeout()); assertThat(repository).hasFieldOrPropertyWithValue("keyNamespace", keyNamespace); assertThat(repository).hasFieldOrPropertyWithValue("flushMode", flushMode); assertThat(repository).hasFieldOrPropertyWithValue("saveMode", saveMode); }; } private ContextConsumer<AssertableWebApplicationContext> validateSpringSessionUsesIndexedRedis(String keyNamespace, FlushMode flushMode, SaveMode saveMode, String cleanupCron) { return (context) -> { RedisIndexedSessionRepository repository = validateSessionRepository(context, RedisIndexedSessionRepository.class); assertThat(repository).hasFieldOrPropertyWithValue("defaultMaxInactiveInterval", new ServerProperties().getServlet().getSession().getTimeout()); assertThat(repository).hasFieldOrPropertyWithValue("namespace", keyNamespace); assertThat(repository).hasFieldOrPropertyWithValue("flushMode", flushMode); assertThat(repository).hasFieldOrPropertyWithValue("saveMode", saveMode); assertThat(repository).hasFieldOrPropertyWithValue("cleanupCron", cleanupCron); }; } private ContextConsumer<AssertableWebApplicationContext> validateStrategy( Class<? extends ConfigureRedisAction> expectedConfigureRedisActionType, Map.Entry<?, ?>... expectedConfig) { return (context) -> { assertThat(context).hasSingleBean(ConfigureRedisAction.class); assertThat(context).hasSingleBean(RedisConnectionFactory.class); assertThat(context.getBean(ConfigureRedisAction.class)).isInstanceOf(expectedConfigureRedisActionType); RedisConnection connection = context.getBean(RedisConnectionFactory.class).getConnection(); if (expectedConfig.length > 0) { assertThat(connection.serverCommands().getConfig("*")).contains(expectedConfig); } }; } static
SessionDataRedisAutoConfigurationTests
java
apache__camel
components/camel-jackson/src/test/java/org/apache/camel/component/jackson/JacksonJsonDataFormatTest.java
{ "start": 956, "end": 1821 }
class ____ extends JacksonMarshalTest { @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { // jackson is default for json from("direct:in").marshal().json(); from("direct:back").unmarshal().json().to("mock:reverse"); from("direct:inPretty").marshal().json(true); from("direct:backPretty").unmarshal().json().to("mock:reverse"); from("direct:inPojo").marshal().json(JsonLibrary.Jackson); from("direct:backPojo").unmarshal().json(JsonLibrary.Jackson, TestPojo.class).to("mock:reversePojo"); from("direct:nullBody").unmarshal().allowNullBody().json().to("mock:nullBody"); } }; } }
JacksonJsonDataFormatTest
java
bumptech__glide
instrumentation/src/androidTest/java/com/bumptech/glide/AsBytesTest.java
{ "start": 875, "end": 5987 }
class ____ { @Rule public final TearDownGlide tearDownGlide = new TearDownGlide(); @Rule public final ModelGeneratorRule modelGeneratorRule = new ModelGeneratorRule(); private final ConcurrencyHelper concurrency = new ConcurrencyHelper(); private Context context; @Before public void setUp() throws IOException { MockitoAnnotations.initMocks(this); context = ApplicationProvider.getApplicationContext(); } @Test public void loadImageResourceId_asBytes_providesBytesOfBitmap() { byte[] data = concurrency.get( Glide.with(context).as(byte[].class).load(ResourceIds.raw.canonical).submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadBitmap_asBytes_providesBytesOfBitmap() { Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), ResourceIds.raw.canonical); byte[] data = concurrency.get(Glide.with(context).as(byte[].class).load(bitmap).submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadBitmapDrawable_asBytes_providesBytesOfBitmap() { Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), ResourceIds.raw.canonical); byte[] data = concurrency.get( Glide.with(context) .as(byte[].class) .load(new BitmapDrawable(context.getResources(), bitmap)) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoResourceId_asBytes_providesBytesOfFrame() { byte[] data = concurrency.get(Glide.with(context).as(byte[].class).load(ResourceIds.raw.video).submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoResourceId_asBytes_withFrameTime_providesBytesOfFrame() { byte[] data = concurrency.get( GlideApp.with(context) .as(byte[].class) .load(ResourceIds.raw.video) .frame(TimeUnit.SECONDS.toMicros(1)) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFile_asBytes_providesByteOfFrame() throws IOException { byte[] data = concurrency.get(Glide.with(context).as(byte[].class).load(writeVideoToFile()).submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFile_asBytes_withFrameTime_providesByteOfFrame() throws IOException { byte[] data = concurrency.get( GlideApp.with(context) .as(byte[].class) .load(writeVideoToFile()) .frame(TimeUnit.SECONDS.toMicros(1)) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFilePath_asBytes_providesByteOfFrame() throws IOException { byte[] data = concurrency.get( Glide.with(context) .as(byte[].class) .load(writeVideoToFile().getAbsolutePath()) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFilePath_asBytes_withFrameTime_providesByteOfFrame() throws IOException { byte[] data = concurrency.get( GlideApp.with(context) .as(byte[].class) .load(writeVideoToFile().getAbsolutePath()) .frame(TimeUnit.SECONDS.toMicros(1)) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFileUri_asBytes_providesByteOfFrame() throws IOException { byte[] data = concurrency.get(Glide.with(context).as(byte[].class).load(writeVideoToFileUri()).submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } @Test public void loadVideoFileUri_asBytes_withFrameTime_providesByteOfFrame() throws IOException { byte[] data = concurrency.get( GlideApp.with(context) .as(byte[].class) .load(writeVideoToFileUri()) .frame(TimeUnit.SECONDS.toMicros(1)) .submit()); assertThat(data).isNotNull(); assertThat(BitmapFactory.decodeByteArray(data, 0, data.length)).isNotNull(); } private File writeVideoToFile() throws IOException { return modelGeneratorRule.asFile(ResourceIds.raw.video); } private Uri writeVideoToFileUri() throws IOException { return Uri.fromFile(writeVideoToFile()); } }
AsBytesTest
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/state/filesystem/CheckpointStateOutputStreamTest.java
{ "start": 2464, "end": 10693 }
enum ____ { FileBasedState, FsCheckpointMetaData } @Parameters public static Collection<CheckpointStateOutputStreamType> getCheckpointStateOutputStreamType() { return Arrays.asList(CheckpointStateOutputStreamType.values()); } @Parameter public CheckpointStateOutputStreamType stateOutputStreamType; // ------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------ /** Validates that even empty streams create a file and a file state handle. */ @TestTemplate void testEmptyState() throws Exception { final FileSystem fs = FileSystem.getLocalFileSystem(); final Path folder = baseFolder(); final String fileName = "myFileName"; final Path filePath = new Path(folder, fileName); final FileStateHandle handle; try (FSDataOutputStream stream = createTestStream(fs, folder, fileName)) { handle = closeAndGetResult(stream); } // must have created a handle assertThat(handle).isNotNull(); assertThat(handle.getFilePath()).isEqualTo(filePath); // the pointer path should exist as a directory assertThat(fs.exists(handle.getFilePath())).isTrue(); assertThat(fs.getFileStatus(filePath).isDir()).isFalse(); // the contents should be empty try (FSDataInputStream in = handle.openInputStream()) { assertThat(in.read()).isEqualTo(-1); } } /** Simple write and read test. */ @TestTemplate void testWriteAndRead() throws Exception { final FileSystem fs = FileSystem.getLocalFileSystem(); final Path folder = baseFolder(); final String fileName = "fooBarName"; final Random rnd = new Random(); final byte[] data = new byte[1694523]; // write the data (mixed single byte writes and array writes) final FileStateHandle handle; try (FSDataOutputStream stream = createTestStream(fs, folder, fileName)) { for (int i = 0; i < data.length; ) { if (rnd.nextBoolean()) { stream.write(data[i++]); } else { int len = rnd.nextInt(Math.min(data.length - i, 32)); stream.write(data, i, len); i += len; } } handle = closeAndGetResult(stream); } // (1) stream from handle must hold the contents try (FSDataInputStream in = handle.openInputStream()) { byte[] buffer = new byte[data.length]; readFully(in, buffer); assertThat(buffer).isEqualTo(data); } // (2) the pointer must point to a file with that contents try (FSDataInputStream in = fs.open(handle.getFilePath())) { byte[] buffer = new byte[data.length]; readFully(in, buffer); assertThat(buffer).isEqualTo(data); } } /** Tests that the underlying stream file is deleted upon calling close. */ @TestTemplate void testCleanupWhenClosingStream() throws IOException { final FileSystem fs = FileSystem.getLocalFileSystem(); final Path folder = new Path(TempDirUtils.newFolder(tmp).toURI()); final String fileName = "nonCreativeTestFileName"; final Path path = new Path(folder, fileName); // write some test data and close the stream try (FSDataOutputStream stream = createTestStream(fs, folder, fileName)) { Random rnd = new Random(); for (int i = 0; i < rnd.nextInt(1000); i++) { stream.write(rnd.nextInt(100)); } } assertThat(fs.exists(path)).isFalse(); } /** Tests that the underlying stream file is deleted if the closeAndGetHandle method fails. */ @TestTemplate void testCleanupWhenFailingCloseAndGetHandle() throws IOException { final Path folder = new Path(TempDirUtils.newFolder(tmp).toURI()); final String fileName = "test_name"; final Path filePath = new Path(folder, fileName); final FileSystem fs = spy( new FsWithoutRecoverableWriter( (path) -> new FailingCloseStream(new File(path.getPath())))); FSDataOutputStream stream = createTestStream(fs, folder, fileName); stream.write(new byte[] {1, 2, 3, 4, 5}); assertThatThrownBy(() -> closeAndGetResult(stream)).isInstanceOf(IOException.class); verify(fs).delete(filePath, false); } /** * This test validates that a close operation can happen even while a 'closeAndGetHandle()' call * is in progress. * * <p>That behavior is essential for fast cancellation (concurrent cleanup). */ @TestTemplate void testCloseDoesNotLock() throws Exception { final Path folder = new Path(TempDirUtils.newFolder(tmp).toURI()); final String fileName = "this-is-ignored-anyways.file"; final FileSystem fileSystem = spy(new FsWithoutRecoverableWriter((path) -> new BlockerStream())); final FSDataOutputStream checkpointStream = createTestStream(fileSystem, folder, fileName); final OneShotLatch sync = new OneShotLatch(); final CheckedThread thread = new CheckedThread() { @Override public void go() throws Exception { sync.trigger(); // that call should now block, because it accesses the position closeAndGetResult(checkpointStream); } }; thread.start(); sync.await(); checkpointStream.close(); // the thread may or may not fail, that depends on the thread race // it is not important for this test, important is that the thread does not freeze/lock up try { thread.sync(); } catch (IOException ignored) { } } /** Creates a new test stream instance. */ private FSDataOutputStream createTestStream(FileSystem fs, Path dir, String fileName) throws IOException { switch (stateOutputStreamType) { case FileBasedState: return new FileBasedStateOutputStream(fs, new Path(dir, fileName)); case FsCheckpointMetaData: Path fullPath = new Path(dir, fileName); return new FsCheckpointMetadataOutputStream(fs, fullPath, dir); default: throw new IllegalStateException("Unsupported checkpoint stream output type."); } } /** Closes the stream successfully and returns a FileStateHandle to the result. */ private FileStateHandle closeAndGetResult(FSDataOutputStream stream) throws IOException { switch (stateOutputStreamType) { case FileBasedState: return ((FileBasedStateOutputStream) stream).closeAndGetHandle(); case FsCheckpointMetaData: return ((FsCheckpointMetadataOutputStream) stream) .closeAndFinalizeCheckpoint() .getMetadataHandle(); default: throw new IllegalStateException("Unsupported checkpoint stream output type."); } } // ------------------------------------------------------------------------ // utilities // ------------------------------------------------------------------------ private Path baseFolder() throws Exception { return new Path( new File(TempDirUtils.newFolder(tmp), UUID.randomUUID().toString()).toURI()); } private static void readFully(InputStream in, byte[] buffer) throws IOException { int pos = 0; int remaining = buffer.length; while (remaining > 0) { int read = in.read(buffer, pos, remaining); if (read == -1) { throw new EOFException(); } pos += read; remaining -= read; } } private static
CheckpointStateOutputStreamType
java
spring-projects__spring-security
webauthn/src/main/java/org/springframework/security/web/webauthn/jackson/PublicKeyCredentialCreationOptionsJackson2Mixin.java
{ "start": 1346, "end": 1501 }
class ____ { @JsonSerialize(using = DurationJackson2Serializer.class) private @Nullable Duration timeout; }
PublicKeyCredentialCreationOptionsJackson2Mixin
java
apache__thrift
lib/java/src/test/java/org/apache/thrift/TestOptionals.java
{ "start": 1231, "end": 3003 }
class ____ { @Test public void testEncodingUtils() throws Exception { assertEquals((short) 0x8, EncodingUtils.setBit((short) 0, 3, true)); assertEquals((short) 0, EncodingUtils.setBit((short) 0x8, 3, false)); assertTrue(EncodingUtils.testBit((short) 0x8, 3)); assertFalse(EncodingUtils.testBit((short) 0x8, 4)); assertEquals(Short.MIN_VALUE, EncodingUtils.setBit((short) 0, 15, true)); assertEquals((short) 0, EncodingUtils.setBit(Short.MIN_VALUE, 15, false)); assertTrue(EncodingUtils.testBit(Short.MIN_VALUE, 15)); assertFalse(EncodingUtils.testBit(Short.MIN_VALUE, 14)); } @Test public void testOpt4() throws Exception { Opt4 x = new Opt4(); assertFalse(x.isSetDef1()); x.setDef1(3); assertTrue(x.isSetDef1()); assertFalse(x.isSetDef2()); Opt4 copy = new Opt4(x); assertTrue(copy.isSetDef1()); copy.unsetDef1(); assertFalse(copy.isSetDef1()); assertTrue(x.isSetDef1()); } @Test public void testOpt30() throws Exception { Opt30 x = new Opt30(); assertFalse(x.isSetDef1()); x.setDef1(3); assertTrue(x.isSetDef1()); assertFalse(x.isSetDef2()); } @Test public void testOpt64() throws Exception { Opt64 x = new Opt64(); assertFalse(x.isSetDef1()); x.setDef1(3); assertTrue(x.isSetDef1()); assertFalse(x.isSetDef2()); x.setDef64(22); assertTrue(x.isSetDef64()); assertFalse(x.isSetDef63()); } @Test public void testOpt80() throws Exception { Opt80 x = new Opt80(); assertFalse(x.isSetDef1()); x.setDef1(3); assertTrue(x.isSetDef1()); assertFalse(x.isSetDef2()); Opt80 copy = new Opt80(x); copy.unsetDef1(); assertFalse(copy.isSetDef1()); assertTrue(x.isSetDef1()); } }
TestOptionals
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/collectionelement/ElementCollectionOfEmbeddableWithEntityWithEntityCollectionTest.java
{ "start": 5773, "end": 5951 }
class ____ { @Id public Integer id; public String name; public Event() { } public Event(Integer id, String name) { this.id = id; this.name = name; } } }
Event
java
lettuce-io__lettuce-core
src/test/java/io/lettuce/examples/ConnectToMasterSlaveUsingElastiCacheCluster.java
{ "start": 389, "end": 1110 }
class ____ { public static void main(String[] args) { // Syntax: redis://[password@]host[:port][/databaseNumber] RedisClient redisClient = RedisClient.create(); List<RedisURI> nodes = Arrays.asList(RedisURI.create("redis://host1"), RedisURI.create("redis://host2"), RedisURI.create("redis://host3")); StatefulRedisMasterReplicaConnection<String, String> connection = MasterReplica.connect(redisClient, StringCodec.UTF8, nodes); connection.setReadFrom(ReadFrom.UPSTREAM_PREFERRED); System.out.println("Connected to Redis"); connection.close(); redisClient.shutdown(); } }
ConnectToMasterSlaveUsingElastiCacheCluster
java
square__retrofit
retrofit-converters/simplexml/src/main/java/retrofit2/converter/simplexml/SimpleXmlRequestBodyConverter.java
{ "start": 856, "end": 1681 }
class ____<T> implements Converter<T, RequestBody> { private static final MediaType MEDIA_TYPE = MediaType.get("application/xml; charset=UTF-8"); private static final String CHARSET = "UTF-8"; private final Serializer serializer; SimpleXmlRequestBodyConverter(Serializer serializer) { this.serializer = serializer; } @Override public RequestBody convert(T value) throws IOException { Buffer buffer = new Buffer(); try { OutputStreamWriter osw = new OutputStreamWriter(buffer.outputStream(), CHARSET); serializer.write(value, osw); osw.flush(); } catch (RuntimeException | IOException e) { throw e; } catch (Exception e) { throw new RuntimeException(e); } return RequestBody.create(MEDIA_TYPE, buffer.readByteString()); } }
SimpleXmlRequestBodyConverter
java
apache__camel
components/camel-paho/src/generated/java/org/apache/camel/component/paho/PahoEndpointUriFactory.java
{ "start": 514, "end": 3388 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":topic"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(33); props.add("automaticReconnect"); props.add("bridgeErrorHandler"); props.add("brokerUrl"); props.add("cleanSession"); props.add("client"); props.add("clientId"); props.add("connectionTimeout"); props.add("customWebSocketHeaders"); props.add("exceptionHandler"); props.add("exchangePattern"); props.add("executorServiceTimeout"); props.add("filePersistenceDirectory"); props.add("httpsHostnameVerificationEnabled"); props.add("keepAliveInterval"); props.add("lazyStartProducer"); props.add("manualAcksEnabled"); props.add("maxInflight"); props.add("maxReconnectDelay"); props.add("mqttVersion"); props.add("password"); props.add("persistence"); props.add("qos"); props.add("retained"); props.add("serverURIs"); props.add("socketFactory"); props.add("sslClientProps"); props.add("sslHostnameVerifier"); props.add("topic"); props.add("userName"); props.add("willPayload"); props.add("willQos"); props.add("willRetained"); props.add("willTopic"); PROPERTY_NAMES = Collections.unmodifiableSet(props); Set<String> secretProps = new HashSet<>(2); secretProps.add("password"); secretProps.add("userName"); SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps); MULTI_VALUE_PREFIXES = Collections.emptyMap(); } @Override public boolean isEnabled(String scheme) { return "paho".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "topic", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
PahoEndpointUriFactory
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/batch/EmbeddableAndFetchModeSelectTest.java
{ "start": 8743, "end": 8941 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ID") Integer id; String name; } @Entity(name = "EntityD") @Table(name = "ENTITY_D") public static
EntityC
java
apache__camel
components/camel-nitrite/src/main/java/org/apache/camel/component/nitrite/operation/common/CreateIndexOperation.java
{ "start": 1192, "end": 1686 }
class ____ extends AbstractNitriteOperation implements CommonOperation { private String field; private IndexOptions indexOptions; public CreateIndexOperation(String field, IndexOptions indexOptions) { this.field = field; this.indexOptions = indexOptions; } @Override protected void execute(Exchange exchange, NitriteEndpoint endpoint) throws Exception { endpoint.getNitriteCollection().createIndex(field, indexOptions); } }
CreateIndexOperation
java
apache__dubbo
dubbo-config/dubbo-config-api/src/main/java/org/apache/dubbo/config/ReferenceConfig.java
{ "start": 9479, "end": 9748 }
interface ____ * @since 2.7.8 */ @Deprecated @Parameter(excluded = true) public Set<String> getSubscribedServices() { return splitToSet(getServices(), COMMA_SEPARATOR_CHAR); } /** * Set the service names that the Dubbo
subscribed
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/cluster/event/JfrMovedRedirectionEvent.java
{ "start": 342, "end": 756 }
class ____ extends Event { private final String command; private final String key; private final int slot; private final String message; public JfrMovedRedirectionEvent(RedirectionEventSupport event) { this.command = event.getCommand(); this.key = event.getKey(); this.slot = event.getSlot(); this.message = event.getMessage(); } }
JfrMovedRedirectionEvent
java
quarkusio__quarkus
core/runtime/src/main/java/io/quarkus/runtime/ExecutorRecorder.java
{ "start": 11034, "end": 11327 }
class ____ { private static final int DEFAULT_MAX_THREADS = 200; private static final int CALCULATION = Math.max(8 * ProcessorInfo.availableProcessors(), DEFAULT_MAX_THREADS); } } public static Executor getCurrent() { return current; } }
Holder
java
apache__maven
impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultMessageBuilderFactory.java
{ "start": 1270, "end": 1820 }
class ____ implements MessageBuilderFactory { @Inject public DefaultMessageBuilderFactory() {} @Override public boolean isColorEnabled() { return false; } @Override public int getTerminalWidth() { return -1; } @Override @Nonnull public MessageBuilder builder() { return new DefaultMessageBuilder(); } @Override @Nonnull public MessageBuilder builder(int size) { return new DefaultMessageBuilder(new StringBuilder(size)); } }
DefaultMessageBuilderFactory