language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__kafka | streams/examples/src/main/java/org/apache/kafka/streams/examples/pageview/PageViewTypedDemo.java | {
"start": 6956,
"end": 10480
} | class ____ implements JSONSerdeCompatible {
public long count;
public String region;
}
public static void main(final String[] args) {
final Properties props = new Properties();
props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-pageview-typed");
props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
props.put(StreamsConfig.DEFAULT_TIMESTAMP_EXTRACTOR_CLASS_CONFIG, JsonTimestampExtractor.class);
props.put(StreamsConfig.DEFAULT_KEY_SERDE_CLASS_CONFIG, JSONSerde.class);
props.put(StreamsConfig.DEFAULT_VALUE_SERDE_CLASS_CONFIG, JSONSerde.class);
props.put(StreamsConfig.STATESTORE_CACHE_MAX_BYTES_CONFIG, 0);
props.put(StreamsConfig.COMMIT_INTERVAL_MS_CONFIG, 1000L);
// setting offset reset to earliest so that we can re-run the demo code with the same pre-loaded data
props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
final StreamsBuilder builder = new StreamsBuilder();
final KStream<String, PageView> views = builder.stream("streams-pageview-input", Consumed.with(Serdes.String(), new JSONSerde<>()));
final KTable<String, UserProfile> users = builder.table("streams-userprofile-input", Consumed.with(Serdes.String(), new JSONSerde<>()));
final Duration duration24Hours = Duration.ofHours(24);
final KStream<WindowedPageViewByRegion, RegionCount> regionCount = views
.leftJoin(users, (view, profile) -> {
final PageViewByRegion viewByRegion = new PageViewByRegion();
viewByRegion.user = view.user;
viewByRegion.page = view.page;
if (profile != null) {
viewByRegion.region = profile.region;
} else {
viewByRegion.region = "UNKNOWN";
}
return viewByRegion;
})
.map((user, viewRegion) -> new KeyValue<>(viewRegion.region, viewRegion))
.groupByKey(Grouped.with(Serdes.String(), new JSONSerde<>()))
.windowedBy(TimeWindows.ofSizeAndGrace(Duration.ofDays(7), duration24Hours).advanceBy(Duration.ofSeconds(1)))
.count()
.toStream()
.map((key, value) -> {
final WindowedPageViewByRegion wViewByRegion = new WindowedPageViewByRegion();
wViewByRegion.windowStart = key.window().start();
wViewByRegion.region = key.key();
final RegionCount rCount = new RegionCount();
rCount.region = key.key();
rCount.count = value;
return new KeyValue<>(wViewByRegion, rCount);
});
// write to the result topic
regionCount.to("streams-pageviewstats-typed-output", Produced.with(new JSONSerde<>(), new JSONSerde<>()));
final KafkaStreams streams = new KafkaStreams(builder.build(), props);
final CountDownLatch latch = new CountDownLatch(1);
// attach shutdown handler to catch control-c
Runtime.getRuntime().addShutdownHook(new Thread("streams-pipe-shutdown-hook") {
@Override
public void run() {
streams.close();
latch.countDown();
}
});
try {
streams.start();
latch.await();
} catch (final Throwable e) {
e.printStackTrace();
System.exit(1);
}
System.exit(0);
}
}
| RegionCount |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/NativeQueryAndDiscriminatorTest.java | {
"start": 2812,
"end": 2849
} | enum ____ {
T;
}
}
| EntityDiscriminator |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/state/ttl/TtlMergingStateTestContext.java | {
"start": 1052,
"end": 3413
} | class ____<
S extends InternalMergingState<?, String, ?, ?, GV>, UV, GV>
extends TtlStateTestContextBase<S, UV, GV> {
static final Random RANDOM = new Random();
static final List<String> NAMESPACES =
Arrays.asList(
"unsetNamespace1",
"unsetNamespace2",
"expiredNamespace",
"expiredAndUpdatedNamespace",
"unexpiredNamespace",
"finalNamespace");
List<Tuple2<String, UV>> generateExpiredUpdatesToMerge() {
return Arrays.asList(
Tuple2.of("expiredNamespace", generateRandomUpdate()),
Tuple2.of("expiredNamespace", generateRandomUpdate()),
Tuple2.of("expiredAndUpdatedNamespace", generateRandomUpdate()),
Tuple2.of("expiredAndUpdatedNamespace", generateRandomUpdate()));
}
List<Tuple2<String, UV>> generateUnexpiredUpdatesToMerge() {
return Arrays.asList(
Tuple2.of("expiredAndUpdatedNamespace", generateRandomUpdate()),
Tuple2.of("expiredAndUpdatedNamespace", generateRandomUpdate()),
Tuple2.of("unexpiredNamespace", generateRandomUpdate()),
Tuple2.of("unexpiredNamespace", generateRandomUpdate()));
}
List<Tuple2<String, UV>> generateFinalUpdatesToMerge() {
return Arrays.asList(
Tuple2.of("expiredAndUpdatedNamespace", generateRandomUpdate()),
Tuple2.of("expiredAndUpdatedNamespace", generateRandomUpdate()),
Tuple2.of("unexpiredNamespace", generateRandomUpdate()),
Tuple2.of("unexpiredNamespace", generateRandomUpdate()),
Tuple2.of("finalNamespace", generateRandomUpdate()),
Tuple2.of("finalNamespace", generateRandomUpdate()));
}
abstract UV generateRandomUpdate();
void applyStateUpdates(List<Tuple2<String, UV>> updates) throws Exception {
for (Tuple2<String, UV> t : updates) {
ttlState.setCurrentNamespace(t.f0);
update(t.f1);
}
}
abstract GV getMergeResult(
List<Tuple2<String, UV>> unexpiredUpdatesToMerge,
List<Tuple2<String, UV>> finalUpdatesToMerge);
@SuppressWarnings("unchecked")
abstract static | TtlMergingStateTestContext |
java | grpc__grpc-java | examples/src/main/java/io/grpc/examples/customloadbalance/ShufflingPickFirstLoadBalancer.java | {
"start": 1696,
"end": 1926
} | class ____ the configuration used by this {@link LoadBalancer}. Note that no part of
* the gRPC library is aware of this class, it will be populated by the
* {@link ShufflingPickFirstLoadBalancerProvider}.
*/
static | defines |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/JavaDurationWithNanosTest.java | {
"start": 1676,
"end": 2201
} | class ____ {
private static final Duration DURATION1 = Duration.ZERO;
// BUG: Diagnostic contains: Duration.ofSeconds(DURATION1.getSeconds(), 44);
private static final Duration DURATION2 = DURATION1.withNanos(44);
}
""")
.doTest();
}
@Test
public void durationWithNanosPrimitiveImportClash() {
helper
.addSourceLines(
"TestClass.java",
"""
import org.joda.time.Duration;
public | TestClass |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/offsetdatetime/OffsetDateTimeAssert_isNotEqualTo_Test.java | {
"start": 1627,
"end": 3918
} | class ____ extends AbstractOffsetDateTimeAssertBaseTest {
private final Object otherType = new Object();
@Override
protected OffsetDateTimeAssert invoke_api_method() {
return assertions.isNotEqualTo(REFERENCE)
.isNotEqualTo(BEFORE.toString())
.isNotEqualTo((OffsetDateTime) null)
.isNotEqualTo(otherType);
}
@Override
protected void verify_internal_effects() {
verify(comparables).assertNotEqual(getInfo(assertions), getActual(assertions), REFERENCE);
verify(comparables).assertNotEqual(getInfo(assertions), getActual(assertions), BEFORE);
verify(objects).assertNotEqual(getInfo(assertions), getActual(assertions), null);
verify(comparables).assertNotEqual(getInfo(assertions), getActual(assertions), otherType);
}
@Test
void should_fail_if_actual_is_at_same_instant_as_offsetDateTime_with_different_offset() {
// WHEN
var assertionError = expectAssertionError(() -> assertThat(REFERENCE).isNotEqualTo(REFERENCE_WITH_DIFFERENT_OFFSET));
// THEN
String errorMesssage = shouldNotBeEqual(REFERENCE, REFERENCE_WITH_DIFFERENT_OFFSET, COMPARISON_STRATEGY).create();
assertThat(assertionError).hasMessage(errorMesssage);
}
@Test
void should_fail_if_both_are_null() {
// GIVEN
OffsetDateTime nullActual = null;
OffsetDateTime nullExpected = null;
// WHEN
var assertionError = expectAssertionError(() -> assertThat(nullActual).isNotEqualTo(nullExpected));
// THEN
then(assertionError).hasMessage(shouldNotBeEqual(nullActual, nullExpected).create());
}
@Test
void should_fail_if_offsetDateTime_as_string_parameter_is_null() {
// GIVEN
String otherOffsetDateTimeAsString = null;
// WHEN
ThrowingCallable code = () -> assertThat(now()).isNotEqualTo(otherOffsetDateTimeAsString);
// THEN
thenIllegalArgumentException().isThrownBy(code)
.withMessage("The String representing the OffsetDateTime to compare actual with should not be null");
}
@Test
void should_fail_if_given_string_parameter_cant_be_parsed() {
assertThatThrownBy(() -> assertions.isNotEqualTo("not an OffsetDateTime")).isInstanceOf(DateTimeParseException.class);
}
}
| OffsetDateTimeAssert_isNotEqualTo_Test |
java | apache__camel | components/camel-kudu/src/test/java/org/apache/camel/component/kudu/KuduScanTest.java | {
"start": 1431,
"end": 8851
} | class ____ extends AbstractKuduTest {
public static final String TABLE = "ScanTableTest";
@EndpointInject(value = "mock:result")
public MockEndpoint successEndpoint;
@EndpointInject(value = "mock:error")
public MockEndpoint errorEndpoint;
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
errorHandler(deadLetterChannel("mock:error").redeliveryDelay(0).maximumRedeliveries(0));
//integration test route
from("direct:scan").to("kudu:localhost:7051/" + TABLE + "?operation=scan")
.to("mock:result");
from("direct:scan2")
.to("kudu:localhost:7051/TestTable?operation=scan")
.to("mock:result");
}
};
}
@BeforeEach
public void setup() {
deleteTestTable(TABLE);
createTestTable(TABLE);
insertRowInTestTable(TABLE);
insertRowInTestTable(TABLE);
}
@Test
public void scan() throws InterruptedException {
errorEndpoint.expectedMessageCount(0);
successEndpoint.expectedMessageCount(1);
sendBody("direct:scan", null);
errorEndpoint.assertIsSatisfied();
successEndpoint.assertIsSatisfied();
List<Exchange> exchanges = successEndpoint.getReceivedExchanges();
assertEquals(1, exchanges.size());
List<Map<String, Object>> results = exchanges.get(0).getIn().getBody(List.class);
assertEquals(2, results.size(), "Wrong number of results.");
Map<String, Object> row = results.get(0);
// INT32 id=??, STRING title=Mr.,
// STRING name=Samuel, STRING lastname=Smith,
// STRING address=4359 Plainfield Avenue
assertTrue(row.containsKey("id"));
assertEquals("Mr.", row.get("title"));
assertEquals("Samuel", row.get("name"));
assertEquals("Smith", row.get("lastname"));
assertEquals("4359 Plainfield Avenue", row.get("address"));
row = results.get(1);
// INT32 id=??, STRING title=Mr.,
// STRING name=Samuel, STRING lastname=Smith,
// STRING address=4359 Plainfield Avenue
assertTrue(row.containsKey("id"));
assertEquals("Mr.", row.get("title"));
assertEquals("Samuel", row.get("name"));
assertEquals("Smith", row.get("lastname"));
assertEquals("4359 Plainfield Avenue", row.get("address"));
}
@Test
public void scanWithPredicate() throws InterruptedException {
errorEndpoint.expectedMessageCount(0);
successEndpoint.expectedMessageCount(2);
// without predicate
Map<String, Object> headers = new HashMap<>();
headers.put(KuduConstants.CAMEL_KUDU_SCAN_PREDICATE, null);
sendBody("direct:scan", null, headers);
List<Map<String, Object>> results = (List<Map<String, Object>>) successEndpoint.getReceivedExchanges()
.get(0).getIn().getBody(List.class);
assertEquals(2, results.size(), "two records with id=1 and id=2 are expected to be returned");
// with predicate
ColumnSchema schema = new ColumnSchema.ColumnSchemaBuilder("id", Type.INT32).build();
KuduPredicate predicate = KuduPredicate.newComparisonPredicate(schema, KuduPredicate.ComparisonOp.EQUAL, 2);
headers.put(KuduConstants.CAMEL_KUDU_SCAN_PREDICATE, predicate);
sendBody("direct:scan", null, headers);
results = (List<Map<String, Object>>) successEndpoint.getReceivedExchanges()
.get(1).getIn().getBody(List.class);
assertEquals(1, results.size(), "only one record with id=2 is expected to be returned");
errorEndpoint.assertIsSatisfied();
successEndpoint.assertIsSatisfied();
}
@Test
public void scanWithColumnNames() throws InterruptedException {
errorEndpoint.expectedMessageCount(0);
successEndpoint.expectedMessageCount(2);
// without column names
Map<String, Object> headers = new HashMap<>();
headers.put(KuduConstants.CAMEL_KUDU_SCAN_COLUMN_NAMES, null);
sendBody("direct:scan", null, headers);
List<Map<String, Object>> results = (List<Map<String, Object>>) successEndpoint.getReceivedExchanges()
.get(0).getIn().getBody(List.class);
assertEquals(5, results.get(0).size(), "returned rows are expected to have 5 columns");
// with column names
List<String> columnNames = Arrays.asList("id", "name");
headers.put(KuduConstants.CAMEL_KUDU_SCAN_COLUMN_NAMES, columnNames);
sendBody("direct:scan", null, headers);
results = (List<Map<String, Object>>) successEndpoint.getReceivedExchanges().get(1).getIn().getBody(List.class);
Map<String, Object> result = results.get(0);
assertEquals(2, result.size(), "returned rows are expected to have only 2 columns");
for (String name : columnNames) {
assertTrue(result.containsKey(name), "returned columns are expected to be identical to the specified ones");
}
errorEndpoint.assertIsSatisfied();
successEndpoint.assertIsSatisfied();
}
@Test
public void scanWithLimit() throws InterruptedException {
errorEndpoint.expectedMessageCount(0);
successEndpoint.expectedMessageCount(2);
// without limit
Map<String, Object> headers = new HashMap<>();
headers.put(KuduConstants.CAMEL_KUDU_SCAN_LIMIT, null);
sendBody("direct:scan", null, headers);
List<Map<String, Object>> results = (List<Map<String, Object>>) successEndpoint.getReceivedExchanges()
.get(0).getIn().getBody(List.class);
assertEquals(2, results.size(), "returned result is expected to have 2 rows");
// with limit
headers.put(KuduConstants.CAMEL_KUDU_SCAN_LIMIT, 1L);
sendBody("direct:scan", null, headers);
results = (List<Map<String, Object>>) successEndpoint.getReceivedExchanges().get(1).getIn().getBody(List.class);
assertEquals(1, results.size(), "returned result is expected to have only 1 row");
errorEndpoint.assertIsSatisfied();
successEndpoint.assertIsSatisfied();
}
@Test
public void scanTable() throws InterruptedException {
createTestTable("TestTable");
insertRowInTestTable("TestTable");
errorEndpoint.expectedMessageCount(0);
successEndpoint.expectedMessageCount(1);
sendBody("direct:scan2", null);
errorEndpoint.assertIsSatisfied();
successEndpoint.assertIsSatisfied();
List<Map<String, Object>> results = (List<Map<String, Object>>) successEndpoint.getReceivedExchanges()
.get(0).getIn().getBody(List.class);
assertEquals(1, results.size(), "Wrong number of results.");
Map<String, Object> row = results.get(0);
// INT32 id=??, STRING title=Mr.,
// STRING name=Samuel, STRING lastname=Smith,
// STRING address=4359 Plainfield Avenue
assertTrue(row.containsKey("id"));
assertEquals("Mr.", row.get("title"));
assertEquals("Samuel", row.get("name"));
assertEquals("Smith", row.get("lastname"));
assertEquals("4359 Plainfield Avenue", row.get("address"));
}
}
| KuduScanTest |
java | spring-projects__spring-security | core/src/main/java/org/springframework/security/authentication/jaas/memory/InMemoryConfiguration.java | {
"start": 1376,
"end": 3624
} | class ____ extends Configuration {
private final AppConfigurationEntry @Nullable [] defaultConfiguration;
private final Map<String, AppConfigurationEntry[]> mappedConfigurations;
/**
* Creates a new instance with only a defaultConfiguration. Any configuration name
* will result in defaultConfiguration being returned.
* @param defaultConfiguration The result for any calls to
* {@link #getAppConfigurationEntry(String)}. Can be <code>null</code>.
*/
public InMemoryConfiguration(AppConfigurationEntry[] defaultConfiguration) {
this(Collections.emptyMap(), defaultConfiguration);
}
/**
* Creates a new instance with a mapping of login context name to an array of
* {@link AppConfigurationEntry}s.
* @param mappedConfigurations each key represents a login context name and each value
* is an Array of {@link AppConfigurationEntry}s that should be used.
*/
public InMemoryConfiguration(Map<String, AppConfigurationEntry[]> mappedConfigurations) {
this(mappedConfigurations, null);
}
/**
* Creates a new instance with a mapping of login context name to an array of
* {@link AppConfigurationEntry}s along with a default configuration that will be used
* if no mapping is found for the given login context name.
* @param mappedConfigurations each key represents a login context name and each value
* is an Array of {@link AppConfigurationEntry}s that should be used.
* @param defaultConfiguration The result for any calls to
* {@link #getAppConfigurationEntry(String)}. Can be <code>null</code>.
*/
public InMemoryConfiguration(Map<String, AppConfigurationEntry[]> mappedConfigurations,
AppConfigurationEntry @Nullable [] defaultConfiguration) {
Assert.notNull(mappedConfigurations, "mappedConfigurations cannot be null.");
this.mappedConfigurations = mappedConfigurations;
this.defaultConfiguration = defaultConfiguration;
}
@Override
public AppConfigurationEntry @Nullable [] getAppConfigurationEntry(String name) {
AppConfigurationEntry[] mappedResult = this.mappedConfigurations.get(name);
return (mappedResult != null) ? mappedResult : this.defaultConfiguration;
}
/**
* Does nothing, but required for JDK5
*/
@Override
public void refresh() {
}
}
| InMemoryConfiguration |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/FluxTakeUntil.java | {
"start": 1144,
"end": 1740
} | class ____<T> extends InternalFluxOperator<T, T> {
final Predicate<? super T> predicate;
FluxTakeUntil(Flux<? extends T> source, Predicate<? super T> predicate) {
super(source);
this.predicate = Objects.requireNonNull(predicate, "predicate");
}
@Override
public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) {
return new TakeUntilPredicateSubscriber<>(actual, predicate);
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return super.scanUnsafe(key);
}
static final | FluxTakeUntil |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/ser/impl/FilteredBeanPropertyWriter.java | {
"start": 1081,
"end": 3213
} | class ____
extends BeanPropertyWriter
{
protected final BeanPropertyWriter _delegate;
protected final Class<?> _view;
protected SingleView(BeanPropertyWriter delegate, Class<?> view)
{
super(delegate);
_delegate = delegate;
_view = view;
}
@Override
public SingleView rename(NameTransformer transformer) {
return new SingleView(_delegate.rename(transformer), _view);
}
@Override
public void assignSerializer(ValueSerializer<Object> ser) {
_delegate.assignSerializer(ser);
}
@Override
public void assignNullSerializer(ValueSerializer<Object> nullSer) {
_delegate.assignNullSerializer(nullSer);
}
@Override
public void serializeAsProperty(Object bean, JsonGenerator gen, SerializationContext prov)
throws Exception
{
Class<?> activeView = prov.getActiveView();
if (activeView == null || _view.isAssignableFrom(activeView)) {
_delegate.serializeAsProperty(bean, gen, prov);
} else {
_delegate.serializeAsOmittedProperty(bean, gen, prov);
}
}
@Override
public void serializeAsElement(Object bean, JsonGenerator gen, SerializationContext prov)
throws Exception
{
Class<?> activeView = prov.getActiveView();
if (activeView == null || _view.isAssignableFrom(activeView)) {
_delegate.serializeAsElement(bean, gen, prov);
} else {
_delegate.serializeAsOmittedElement(bean, gen, prov);
}
}
@Override
public void depositSchemaProperty(JsonObjectFormatVisitor v,
SerializationContext provider)
{
Class<?> activeView = provider.getActiveView();
if (activeView == null || _view.isAssignableFrom(activeView)) {
super.depositSchemaProperty(v, provider);
}
}
}
private final static | SingleView |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/protocol/datatransfer/sasl/TestCustomizedCallbackHandler.java | {
"start": 4245,
"end": 5588
} | class ____ {
public void handleCallbacks(List<Callback> callbacks, String name, char[] password)
throws UnsupportedCallbackException {
runHandleCallbacks(this, callbacks, name);
throw new UnsupportedCallbackException(callbacks.get(0));
}
}
@Test
public void testCustomizedCallbackMethod() throws Exception {
final Configuration conf = new Configuration();
final Callback[] callbacks = {new MyCallback()};
// without setting conf, expect UnsupportedCallbackException
reset();
LambdaTestUtils.intercept(UnsupportedCallbackException.class, () -> runTest(conf, callbacks));
// set conf and expect success
reset();
conf.setClass(HADOOP_SECURITY_SASL_CUSTOMIZEDCALLBACKHANDLER_CLASS_KEY,
MyCallbackMethod.class, Object.class);
runTest(conf, callbacks);
assertCallbacks(callbacks);
// set conf and expect exception
reset();
conf.setClass(HADOOP_SECURITY_SASL_CUSTOMIZEDCALLBACKHANDLER_CLASS_KEY,
MyExceptionMethod.class, Object.class);
LambdaTestUtils.intercept(IOException.class, () -> runTest(conf, callbacks));
}
static void runTest(Configuration conf, Callback... callbacks)
throws IOException, UnsupportedCallbackException {
new SaslServerCallbackHandler(conf, String::toCharArray).handle(callbacks);
}
}
| MyExceptionMethod |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/action/get/GetRequestBuilder.java | {
"start": 909,
"end": 5313
} | class ____ extends SingleShardOperationRequestBuilder<GetRequest, GetResponse, GetRequestBuilder> {
public GetRequestBuilder(ElasticsearchClient client) {
super(client, TransportGetAction.TYPE, new GetRequest());
}
public GetRequestBuilder(ElasticsearchClient client, @Nullable String index) {
super(client, TransportGetAction.TYPE, new GetRequest(index));
}
/**
* Sets the id of the document to fetch.
*/
public GetRequestBuilder setId(String id) {
request.id(id);
return this;
}
/**
* Controls the shard routing of the request. Using this value to hash the shard
* and not the id.
*/
public GetRequestBuilder setRouting(String routing) {
request.routing(routing);
return this;
}
/**
* Sets the preference to execute the search. Defaults to randomize across shards. Can be set to
* {@code _local} to prefer local shards or a custom value, which guarantees that the same order
* will be used across different requests.
*/
public GetRequestBuilder setPreference(String preference) {
request.preference(preference);
return this;
}
/**
* Explicitly specify the fields that will be returned. By default, the {@code _source}
* field will be returned.
*/
public GetRequestBuilder setStoredFields(String... fields) {
request.storedFields(fields);
return this;
}
/**
* Indicates whether the response should contain the stored _source.
*
* @return this for chaining
*/
public GetRequestBuilder setFetchSource(boolean fetch) {
FetchSourceContext context = request.fetchSourceContext() == null ? FetchSourceContext.FETCH_SOURCE : request.fetchSourceContext();
request.fetchSourceContext(FetchSourceContext.of(fetch, context.includes(), context.excludes()));
return this;
}
/**
* Indicate that _source should be returned, with an "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @param include An optional include (optionally wildcarded) pattern to filter the returned _source
* @param exclude An optional exclude (optionally wildcarded) pattern to filter the returned _source
*/
public GetRequestBuilder setFetchSource(@Nullable String include, @Nullable String exclude) {
return setFetchSource(
include == null ? Strings.EMPTY_ARRAY : new String[] { include },
exclude == null ? Strings.EMPTY_ARRAY : new String[] { exclude }
);
}
/**
* Indicate that _source should be returned, with an "include" and/or "exclude" set which can include simple wildcard
* elements.
*
* @param includes An optional list of include (optionally wildcarded) pattern to filter the returned _source
* @param excludes An optional list of exclude (optionally wildcarded) pattern to filter the returned _source
*/
public GetRequestBuilder setFetchSource(@Nullable String[] includes, @Nullable String[] excludes) {
FetchSourceContext context = request.fetchSourceContext() == null ? FetchSourceContext.FETCH_SOURCE : request.fetchSourceContext();
request.fetchSourceContext(FetchSourceContext.of(context.fetchSource(), includes, excludes));
return this;
}
/**
* Should a refresh be executed before this get operation causing the operation to
* return the latest value. Note, heavy get should not set this to {@code true}. Defaults
* to {@code false}.
*/
public GetRequestBuilder setRefresh(boolean refresh) {
request.refresh(refresh);
return this;
}
public GetRequestBuilder setRealtime(boolean realtime) {
request.realtime(realtime);
return this;
}
/**
* Sets the version, which will cause the get operation to only be performed if a matching
* version exists and no changes happened on the doc since then.
*/
public GetRequestBuilder setVersion(long version) {
request.version(version);
return this;
}
/**
* Sets the versioning type. Defaults to {@link org.elasticsearch.index.VersionType#INTERNAL}.
*/
public GetRequestBuilder setVersionType(VersionType versionType) {
request.versionType(versionType);
return this;
}
}
| GetRequestBuilder |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client/deployment/src/test/java/io/quarkus/rest/client/reactive/AsyncHeaderTest.java | {
"start": 2387,
"end": 2577
} | class ____ {
@GET
public String get(@HeaderParam("some-header") String headerValue) {
return String.format("passedHeader:%s", headerValue);
}
}
}
| Resource |
java | google__guava | android/guava-testlib/test/com/google/common/collect/testing/features/FeatureUtilTest.java | {
"start": 9121,
"end": 9549
} | class ____ {}
ConflictingRequirementsException e =
assertThrows(
ConflictingRequirementsException.class, () -> buildTesterRequirements(Tester.class));
assertThat(e.getConflicts()).containsExactly(FOO);
assertThat(e.getSource()).isEqualTo(Tester.class.getAnnotation(Require.class));
}
public void testBuildTesterRequirements_classClassConflict_inherited() {
@Require(FOO)
abstract | Tester |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/customproviders/ValidNonBlockingFiltersTest.java | {
"start": 1240,
"end": 2968
} | class ____ {
@RegisterExtension
static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(StandardBlockingRequestFilter.class, AnotherStandardBlockingRequestFilter.class,
StandardNonBlockingRequestFilter.class, DummyResource.class);
}
});
@Test
public void testBlockingEndpoint() {
Headers headers = RestAssured.given().get("/dummy/blocking")
.then().statusCode(200).extract().headers();
assertEquals(
"1-custom-non-blocking/2-another-custom-non-blocking/3-standard-non-blocking/4-standard-blocking/5-another-standard-blocking/6-custom-blocking",
headers.get("filter-request").getValue());
assertEquals(
"false/false/false/true/true/true",
headers.get("thread").getValue());
}
@Test
public void testNonBlockingEndpoint() {
Headers headers = RestAssured.given().get("/dummy/nonblocking")
.then().statusCode(200).extract().headers();
assertEquals(
"1-custom-non-blocking/2-another-custom-non-blocking/3-standard-non-blocking/4-standard-blocking/5-another-standard-blocking/6-custom-blocking",
headers.get("filter-request").getValue());
assertEquals(
"false/false/false/false/false/false",
headers.get("thread").getValue());
}
@Path("dummy")
public static | ValidNonBlockingFiltersTest |
java | apache__camel | components/camel-bean-validator/src/test/java/org/apache/camel/component/bean/validator/Car.java | {
"start": 862,
"end": 1038
} | interface ____ {
String getManufacturer();
void setManufacturer(String manufacturer);
String getLicensePlate();
void setLicensePlate(String licensePlate);
}
| Car |
java | mockito__mockito | mockito-core/src/test/java/org/mockito/internal/util/reflection/GenericMetadataSupportTest.java | {
"start": 2484,
"end": 20241
} | class ____ implements MiddleInterface<T> {}
}
@Test
public void typeVariable_of_self_type() {
GenericMetadataSupport genericMetadata =
inferFrom(GenericsSelfReference.class)
.resolveGenericReturnType(
firstNamedMethod("self", GenericsSelfReference.class));
assertThat(genericMetadata.rawType()).isEqualTo(GenericsSelfReference.class);
}
@Test
public void can_get_raw_type_from_Class() {
assertThat(inferFrom(ListOfAnyNumbers.class).rawType()).isEqualTo(ListOfAnyNumbers.class);
assertThat(inferFrom(ListOfNumbers.class).rawType()).isEqualTo(ListOfNumbers.class);
assertThat(inferFrom(GenericsNest.class).rawType()).isEqualTo(GenericsNest.class);
assertThat(inferFrom(StringList.class).rawType()).isEqualTo(StringList.class);
}
@Test
public void can_get_raw_type_from_ParameterizedType() {
assertThat(inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0]).rawType())
.isEqualTo(List.class);
assertThat(inferFrom(ListOfNumbers.class.getGenericInterfaces()[0]).rawType())
.isEqualTo(List.class);
assertThat(inferFrom(GenericsNest.class.getGenericInterfaces()[0]).rawType())
.isEqualTo(Map.class);
assertThat(inferFrom(StringList.class.getGenericSuperclass()).rawType())
.isEqualTo(ArrayList.class);
}
@Test
public void can_get_type_variables_from_Class() {
assertThat(inferFrom(GenericsNest.class).actualTypeArguments().keySet())
.hasSize(1)
.extracting(TypeVariable::getName)
.contains("K");
assertThat(inferFrom(ListOfNumbers.class).actualTypeArguments().keySet()).isEmpty();
assertThat(inferFrom(ListOfAnyNumbers.class).actualTypeArguments().keySet())
.hasSize(1)
.extracting(TypeVariable::getName)
.contains("N");
assertThat(inferFrom(Map.class).actualTypeArguments().keySet())
.hasSize(2)
.extracting(TypeVariable::getName)
.contains("K", "V");
assertThat(inferFrom(Serializable.class).actualTypeArguments().keySet()).isEmpty();
assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty();
}
@Test
public void can_resolve_type_variables_from_ancestors() throws Exception {
Method listGet = List.class.getMethod("get", int.class);
assertThat(
inferFrom(AnotherListOfNumbers.class)
.resolveGenericReturnType(listGet)
.rawType())
.isEqualTo(Number.class);
assertThat(
inferFrom(AnotherListOfNumbersImpl.class)
.resolveGenericReturnType(listGet)
.rawType())
.isEqualTo(Number.class);
}
@Test
public void can_get_type_variables_from_ParameterizedType() {
assertThat(
inferFrom(GenericsNest.class.getGenericInterfaces()[0])
.actualTypeArguments()
.keySet())
.hasSize(2)
.extracting(TypeVariable::getName)
.contains("K", "V");
assertThat(
inferFrom(ListOfAnyNumbers.class.getGenericInterfaces()[0])
.actualTypeArguments()
.keySet())
.hasSize(1)
.extracting(TypeVariable::getName)
.contains("E");
assertThat(
inferFrom(Integer.class.getGenericInterfaces()[0])
.actualTypeArguments()
.keySet())
.hasSize(1)
.extracting(TypeVariable::getName)
.contains("T");
assertThat(
inferFrom(StringBuilder.class.getGenericInterfaces()[0])
.actualTypeArguments()
.keySet())
.isEmpty();
assertThat(inferFrom(StringList.class).actualTypeArguments().keySet()).isEmpty();
}
@Test
public void
typeVariable_return_type_of____iterator____resolved_to_Iterator_and_type_argument_to_String() {
GenericMetadataSupport genericMetadata =
inferFrom(StringList.class)
.resolveGenericReturnType(firstNamedMethod("iterator", StringList.class));
assertThat(genericMetadata.rawType()).isEqualTo(Iterator.class);
assertThat(genericMetadata.actualTypeArguments().values()).contains(String.class);
}
@Test
public void
typeVariable_return_type_of____get____resolved_to_Set_and_type_argument_to_Number() {
GenericMetadataSupport genericMetadata =
inferFrom(GenericsNest.class)
.resolveGenericReturnType(firstNamedMethod("get", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Set.class);
assertThat(genericMetadata.actualTypeArguments().values()).contains(Number.class);
}
@Test
public void
bounded_typeVariable_return_type_of____returningK____resolved_to_Comparable_and_with_BoundedType() {
GenericMetadataSupport genericMetadata =
inferFrom(GenericsNest.class)
.resolveGenericReturnType(
firstNamedMethod("returningK", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class);
GenericMetadataSupport extraInterface_0 =
inferFrom(genericMetadata.extraInterfaces().get(0));
assertThat(extraInterface_0.rawType()).isEqualTo(Cloneable.class);
}
@Test
public void
fixed_ParamType_return_type_of____remove____resolved_to_Set_and_type_argument_to_Number() {
GenericMetadataSupport genericMetadata =
inferFrom(GenericsNest.class)
.resolveGenericReturnType(firstNamedMethod("remove", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Set.class);
assertThat(genericMetadata.actualTypeArguments().values()).contains(Number.class);
}
@Test
public void
paramType_return_type_of____values____resolved_to_Collection_and_type_argument_to_Parameterized_Set() {
GenericMetadataSupport genericMetadata =
inferFrom(GenericsNest.class)
.resolveGenericReturnType(firstNamedMethod("values", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Collection.class);
GenericMetadataSupport fromTypeVariableE =
inferFrom(typeVariableValue(genericMetadata.actualTypeArguments(), "E"));
assertThat(fromTypeVariableE.rawType()).isEqualTo(Set.class);
assertThat(fromTypeVariableE.actualTypeArguments().values()).contains(Number.class);
}
@Test
public void
paramType_with_type_parameters_return_type_of____paramType_with_type_params____resolved_to_Collection_and_type_argument_to_Parameterized_Set() {
GenericMetadataSupport genericMetadata =
inferFrom(GenericsNest.class)
.resolveGenericReturnType(
firstNamedMethod("paramType_with_type_params", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
Type firstBoundOfE =
((GenericMetadataSupport.TypeVarBoundedType)
typeVariableValue(genericMetadata.actualTypeArguments(), "E"))
.firstBound();
assertThat(inferFrom(firstBoundOfE).rawType()).isEqualTo(Comparable.class);
}
@Test
public void
typeVariable_with_type_parameters_return_type_of____typeVar_with_type_params____resolved_K_hence_to_Comparable_and_with_BoundedType() {
GenericMetadataSupport genericMetadata =
inferFrom(GenericsNest.class)
.resolveGenericReturnType(
firstNamedMethod("typeVar_with_type_params", GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(Comparable.class);
GenericMetadataSupport extraInterface_0 =
inferFrom(genericMetadata.extraInterfaces().get(0));
assertThat(extraInterface_0.rawType()).isEqualTo(Cloneable.class);
}
@Test
public void class_return_type_of____append____resolved_to_StringBuilder_and_type_arguments() {
GenericMetadataSupport genericMetadata =
inferFrom(StringBuilder.class)
.resolveGenericReturnType(firstNamedMethod("append", StringBuilder.class));
assertThat(genericMetadata.rawType()).isEqualTo(StringBuilder.class);
assertThat(genericMetadata.actualTypeArguments()).isEmpty();
}
@Test
public void
paramType_with_wildcard_return_type_of____returning_wildcard_with_class_lower_bound____resolved_to_List_and_type_argument_to_Integer() {
GenericMetadataSupport genericMetadata =
inferFrom(GenericsNest.class)
.resolveGenericReturnType(
firstNamedMethod(
"returning_wildcard_with_class_lower_bound",
GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
GenericMetadataSupport.BoundedType boundedType =
(GenericMetadataSupport.BoundedType)
typeVariableValue(genericMetadata.actualTypeArguments(), "E");
assertThat(boundedType.firstBound()).isEqualTo(Integer.class);
assertThat(boundedType.interfaceBounds()).isEmpty();
}
@Test
public void
paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_lower_bound____resolved_to_List_and_type_argument_to_Integer() {
GenericMetadataSupport genericMetadata =
inferFrom(GenericsNest.class)
.resolveGenericReturnType(
firstNamedMethod(
"returning_wildcard_with_typeVar_lower_bound",
GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
GenericMetadataSupport.BoundedType boundedType =
(GenericMetadataSupport.BoundedType)
typeVariableValue(genericMetadata.actualTypeArguments(), "E");
assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class);
assertThat(boundedType.interfaceBounds()).contains(Cloneable.class);
}
@Test
public void
paramType_with_wildcard_return_type_of____returning_wildcard_with_typeVar_upper_bound____resolved_to_List_and_type_argument_to_Integer() {
GenericMetadataSupport genericMetadata =
inferFrom(GenericsNest.class)
.resolveGenericReturnType(
firstNamedMethod(
"returning_wildcard_with_typeVar_upper_bound",
GenericsNest.class));
assertThat(genericMetadata.rawType()).isEqualTo(List.class);
GenericMetadataSupport.BoundedType boundedType =
(GenericMetadataSupport.BoundedType)
typeVariableValue(genericMetadata.actualTypeArguments(), "E");
assertThat(inferFrom(boundedType.firstBound()).rawType()).isEqualTo(Comparable.class);
assertThat(boundedType.interfaceBounds()).contains(Cloneable.class);
}
@Test
public void can_extract_raw_type_from_bounds_on_terminal_typeVariable() {
assertThat(
inferFrom(OwningClassWithDeclaredUpperBounds.AbstractInner.class)
.resolveGenericReturnType(
firstNamedMethod(
"generic",
OwningClassWithDeclaredUpperBounds.AbstractInner
.class))
.rawType())
.isEqualTo(List.class);
assertThat(
inferFrom(OwningClassWithNoDeclaredUpperBounds.AbstractInner.class)
.resolveGenericReturnType(
firstNamedMethod(
"generic",
OwningClassWithNoDeclaredUpperBounds.AbstractInner
.class))
.rawType())
.isEqualTo(Object.class);
}
@Test
public void can_extract_interface_type_from_bounds_on_terminal_typeVariable() {
assertThat(
inferFrom(OwningClassWithDeclaredUpperBounds.AbstractInner.class)
.resolveGenericReturnType(
firstNamedMethod(
"generic",
OwningClassWithDeclaredUpperBounds.AbstractInner
.class))
.rawExtraInterfaces())
.containsExactly(Comparable.class, Cloneable.class);
assertThat(
inferFrom(OwningClassWithDeclaredUpperBounds.AbstractInner.class)
.resolveGenericReturnType(
firstNamedMethod(
"generic",
OwningClassWithDeclaredUpperBounds.AbstractInner
.class))
.extraInterfaces())
.containsExactly(
parameterizedTypeOf(Comparable.class, null, String.class), Cloneable.class);
assertThat(
inferFrom(OwningClassWithNoDeclaredUpperBounds.AbstractInner.class)
.resolveGenericReturnType(
firstNamedMethod(
"generic",
OwningClassWithNoDeclaredUpperBounds.AbstractInner
.class))
.extraInterfaces())
.isEmpty();
}
private ParameterizedType parameterizedTypeOf(
final Class<?> rawType, final Class<?> ownerType, final Type... actualTypeArguments) {
return new ParameterizedType() {
@Override
public Type[] getActualTypeArguments() {
return actualTypeArguments;
}
@Override
public Type getRawType() {
return rawType;
}
@Override
public Type getOwnerType() {
return ownerType;
}
@SuppressWarnings("EqualsHashCode")
public boolean equals(Object other) {
if (other instanceof ParameterizedType) {
ParameterizedType otherParamType = (ParameterizedType) other;
if (this == otherParamType) {
return true;
} else {
return equals(ownerType, otherParamType.getOwnerType())
&& equals(rawType, otherParamType.getRawType())
&& Arrays.equals(
actualTypeArguments,
otherParamType.getActualTypeArguments());
}
} else {
return false;
}
}
private boolean equals(Object a, Object b) {
return (a == b) || (a != null && a.equals(b));
}
};
}
private Type typeVariableValue(
Map<TypeVariable<?>, Type> typeVariables, String typeVariableName) {
for (Map.Entry<TypeVariable<?>, Type> typeVariableTypeEntry : typeVariables.entrySet()) {
if (typeVariableTypeEntry.getKey().getName().equals(typeVariableName)) {
return typeVariableTypeEntry.getValue();
}
}
fail("'" + typeVariableName + "' was not found in " + typeVariables);
return null; // unreachable
}
private Method firstNamedMethod(String methodName, Class<?> clazz) {
for (Method method : clazz.getMethods()) {
boolean protect_against_different_jdk_ordering_avoiding_bridge_methods =
!method.isBridge();
if (method.getName().contains(methodName)
&& protect_against_different_jdk_ordering_avoiding_bridge_methods) {
return method;
}
}
throw new IllegalStateException(
"The method : '"
+ methodName
+ "' do not exist in '"
+ clazz.getSimpleName()
+ "'");
}
}
| AbstractInner |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/usertype/UserTypeLegacyBridge.java | {
"start": 734,
"end": 2159
} | class ____
extends BaseUserTypeSupport<Object>
implements ParameterizedType, TypeConfigurationAware {
public static final String TYPE_NAME_PARAM_KEY = "hbm-type-name";
private TypeConfiguration typeConfiguration;
private String hbmStyleTypeName;
public UserTypeLegacyBridge() {
}
public UserTypeLegacyBridge(String hbmStyleTypeName) {
this.hbmStyleTypeName = hbmStyleTypeName;
}
@Override
public TypeConfiguration getTypeConfiguration() {
return typeConfiguration;
}
@Override
public void setTypeConfiguration(TypeConfiguration typeConfiguration) {
this.typeConfiguration = typeConfiguration;
}
@Override
public void setParameterValues(Properties parameters) {
if ( hbmStyleTypeName == null ) {
hbmStyleTypeName = parameters.getProperty( TYPE_NAME_PARAM_KEY );
if ( hbmStyleTypeName == null ) {
throw new MappingException( "Missing `@Parameter` for `" + TYPE_NAME_PARAM_KEY + "`" );
}
}
// otherwise assume it was ctor-injected
}
@Override
protected void resolve(BiConsumer<BasicJavaType<Object>, JdbcType> resolutionConsumer) {
assert typeConfiguration != null;
final var registeredType =
(BasicType<Object>)
typeConfiguration.getBasicTypeRegistry()
.getRegisteredType( hbmStyleTypeName );
resolutionConsumer.accept(
(BasicJavaType<Object>) registeredType.getJavaTypeDescriptor(),
registeredType.getJdbcType()
);
}
}
| UserTypeLegacyBridge |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/action/internal/CollectionRemoveAction.java | {
"start": 687,
"end": 5382
} | class ____ extends CollectionAction {
private final Object affectedOwner;
private final boolean emptySnapshot;
/**
* Removes a persistent collection from its loaded owner.
* <p>
* Use this constructor when the collection is non-null.
*
* @param collection The collection to remove; must be non-null
* @param persister The collection's persister
* @param id The collection key
* @param emptySnapshot Indicates if the snapshot is empty
* @param session The session
*
* @throws AssertionFailure if collection is null.
*/
public CollectionRemoveAction(
final PersistentCollection<?> collection,
final CollectionPersister persister,
final Object id,
final boolean emptySnapshot,
final EventSource session) {
super( persister, collection, id, session );
if ( collection == null ) {
throw new AssertionFailure("collection == null");
}
this.emptySnapshot = emptySnapshot;
// the loaded owner will be set to null after the collection is removed,
// so capture its value as the affected owner so it is accessible to
// both pre- and post- events
this.affectedOwner = session.getPersistenceContextInternal().getLoadedCollectionOwnerOrNull( collection );
}
/**
* Removes a persistent collection from a specified owner.
* <p>
* Use this constructor when the collection to be removed has not been loaded.
*
* @param affectedOwner The collection's owner; must be non-null
* @param persister The collection's persister
* @param id The collection key
* @param emptySnapshot Indicates if the snapshot is empty
* @param session The session
*
* @throws AssertionFailure if affectedOwner is null.
*/
public CollectionRemoveAction(
final Object affectedOwner,
final CollectionPersister persister,
final Object id,
final boolean emptySnapshot,
final EventSource session) {
super( persister, null, id, session );
if ( affectedOwner == null ) {
throw new AssertionFailure("affectedOwner == null");
}
this.emptySnapshot = emptySnapshot;
this.affectedOwner = affectedOwner;
}
/**
* Removes a persistent collection for an unloaded proxy.
* <p>
* Use this constructor when the owning entity is has not been loaded.
*
* @param persister The collection's persister
* @param id The collection key
* @param session The session
*/
public CollectionRemoveAction(
final CollectionPersister persister,
final Object id,
final EventSource session) {
super( persister, null, id, session );
emptySnapshot = false;
affectedOwner = null;
}
@Override
public void execute() throws HibernateException {
preRemove();
final var session = getSession();
if ( !emptySnapshot ) {
// an existing collection that was either nonempty or uninitialized
// is replaced by null or a different collection
// (if the collection is uninitialized, Hibernate has no way of
// knowing if the collection is actually empty without querying the db)
final var persister = getPersister();
final Object key = getKey();
final var eventMonitor = session.getEventMonitor();
final var event = eventMonitor.beginCollectionRemoveEvent();
boolean success = false;
try {
persister.remove( key, session );
success = true;
}
finally {
eventMonitor.completeCollectionRemoveEvent( event, key, persister.getRole(), success, session );
}
}
final PersistentCollection<?> collection = getCollection();
if ( collection != null ) {
session.getPersistenceContextInternal().getCollectionEntry( collection ).afterAction( collection );
}
evict();
postRemove();
final var statistics = session.getFactory().getStatistics();
if ( statistics.isStatisticsEnabled() ) {
statistics.removeCollection( getPersister().getRole() );
}
}
private void preRemove() {
getEventListenerGroups().eventListenerGroup_PRE_COLLECTION_REMOVE
.fireLazyEventOnEachListener( this::newPreCollectionRemoveEvent,
PreCollectionRemoveEventListener::onPreRemoveCollection );
}
private PreCollectionRemoveEvent newPreCollectionRemoveEvent() {
return new PreCollectionRemoveEvent( getPersister(), getCollection(), eventSource(), affectedOwner );
}
private void postRemove() {
getEventListenerGroups().eventListenerGroup_POST_COLLECTION_REMOVE
.fireLazyEventOnEachListener( this::newPostCollectionRemoveEvent,
PostCollectionRemoveEventListener::onPostRemoveCollection );
}
private PostCollectionRemoveEvent newPostCollectionRemoveEvent() {
return new PostCollectionRemoveEvent( getPersister(), getCollection(), eventSource(), affectedOwner );
}
public Object getAffectedOwner() {
return affectedOwner;
}
}
| CollectionRemoveAction |
java | apache__camel | components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/model/date/BindyDatePatternCsvUnmarshallTest.java | {
"start": 2647,
"end": 3223
} | class ____ extends RouteBuilder {
BindyCsvDataFormat camelDataFormat = new BindyCsvDataFormat(Order.class);
@Override
public void configure() {
from(URI_DIRECT_START)
.unmarshal(camelDataFormat)
.marshal(camelDataFormat)
.convertBodyTo(String.class) // because the marshaler will return an OutputStream
.to(URI_MOCK_RESULT);
}
}
@CsvRecord(separator = ",")
@FormatFactories({ OrderNumberFormatFactory.class })
public static | ContextConfig |
java | apache__camel | components/camel-as2/camel-as2-api/src/main/java/org/apache/camel/component/as2/api/entity/ApplicationPkcs7SignatureEntity.java | {
"start": 1642,
"end": 5302
} | class ____ extends MimeEntity {
private static final String CONTENT_DISPOSITION = "attachment; filename=\"smime.p7s\"";
private static final String CONTENT_DESCRIPTION = "S/MIME Cryptographic Signature";
private byte[] signature;
public ApplicationPkcs7SignatureEntity(MimeEntity data, CMSSignedDataGenerator signer, String charset,
String contentTransferEncoding, boolean isMainBody) throws HttpException {
super(ContentType
.parse(EntityUtils.appendParameter(AS2MediaType.APPLICATION_PKCS7_SIGNATURE, "charset", charset)),
contentTransferEncoding);
ObjectHelper.notNull(data, "Data");
ObjectHelper.notNull(signer, "Signer");
addHeader(AS2Header.CONTENT_DISPOSITION, CONTENT_DISPOSITION);
addHeader(AS2Header.CONTENT_DESCRIPTION, CONTENT_DESCRIPTION);
setMainBody(isMainBody);
try {
this.signature = createSignature(data, signer);
} catch (Exception e) {
throw new HttpException("Failed to create signed data", e);
}
}
public ApplicationPkcs7SignatureEntity(byte[] signature,
String charset,
String contentTransferEncoding,
boolean isMainBody) {
super(ContentType
.parse(EntityUtils.appendParameter(AS2MediaType.APPLICATION_PKCS7_SIGNATURE, "charset", charset)),
contentTransferEncoding);
this.signature = ObjectHelper.notNull(signature, "signature");
addHeader(AS2Header.CONTENT_DISPOSITION, CONTENT_DISPOSITION);
addHeader(AS2Header.CONTENT_DESCRIPTION, CONTENT_DESCRIPTION);
setMainBody(isMainBody);
}
public byte[] getSignature() {
return signature;
}
@Override
public void writeTo(OutputStream outstream) throws IOException {
NoCloseOutputStream ncos = new NoCloseOutputStream(outstream);
// Write out mime part headers if this is not the main body of message.
if (!isMainBody()) {
try (CanonicalOutputStream canonicalOutstream = new CanonicalOutputStream(ncos, StandardCharsets.US_ASCII.name())) {
for (Header header : getAllHeaders()) {
canonicalOutstream.writeln(header.toString());
}
canonicalOutstream.writeln(); // ensure empty line between
// headers and body; RFC2046 -
// 5.1.1
}
}
// Write out signed data.
String transferEncoding = getContentTransferEncoding() == null ? null : getContentTransferEncoding().getValue();
try (OutputStream transferEncodedStream = EntityUtils.encode(ncos, transferEncoding)) {
transferEncodedStream.write(signature);
} catch (Exception e) {
throw new IOException("Failed to write to output stream", e);
}
}
private byte[] createSignature(MimeEntity data, CMSSignedDataGenerator signer) throws IOException, CMSException {
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
data.writeTo(bos);
bos.flush();
CMSTypedData contentData = new CMSProcessableByteArray(bos.toByteArray());
CMSSignedData signedData = signer.generate(contentData, false);
return signedData.getEncoded();
}
}
@Override
public void close() throws IOException {
// do nothing
}
}
| ApplicationPkcs7SignatureEntity |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/schedulers/SchedulerPoolFactoryTest.java | {
"start": 926,
"end": 2864
} | class ____ extends RxJavaTest {
@Test
public void utilityClass() {
TestHelper.checkUtilityClass(SchedulerPoolFactory.class);
}
@Test
public void boolPropertiesDisabledReturnsDefaultDisabled() throws Throwable {
assertTrue(SchedulerPoolFactory.getBooleanProperty(false, "key", false, true, failingPropertiesAccessor));
assertFalse(SchedulerPoolFactory.getBooleanProperty(false, "key", true, false, failingPropertiesAccessor));
}
@Test
public void boolPropertiesEnabledMissingReturnsDefaultMissing() throws Throwable {
assertTrue(SchedulerPoolFactory.getBooleanProperty(true, "key", true, false, missingPropertiesAccessor));
assertFalse(SchedulerPoolFactory.getBooleanProperty(true, "key", false, true, missingPropertiesAccessor));
}
@Test
public void boolPropertiesFailureReturnsDefaultMissing() throws Throwable {
assertTrue(SchedulerPoolFactory.getBooleanProperty(true, "key", true, false, failingPropertiesAccessor));
assertFalse(SchedulerPoolFactory.getBooleanProperty(true, "key", false, true, failingPropertiesAccessor));
}
@Test
public void boolPropertiesReturnsValue() throws Throwable {
assertTrue(SchedulerPoolFactory.getBooleanProperty(true, "true", true, false, Functions.<String>identity()));
assertFalse(SchedulerPoolFactory.getBooleanProperty(true, "false", false, true, Functions.<String>identity()));
}
static final Function<String, String> failingPropertiesAccessor = new Function<String, String>() {
@Override
public String apply(String v) throws Throwable {
throw new SecurityException();
}
};
static final Function<String, String> missingPropertiesAccessor = new Function<String, String>() {
@Override
public String apply(String v) throws Throwable {
return null;
}
};
}
| SchedulerPoolFactoryTest |
java | google__truth | extensions/liteproto/src/main/java/com/google/common/truth/extensions/proto/LiteProtoSubject.java | {
"start": 10191,
"end": 10583
} | class ____
implements Factory<LiteProtoSubject, MessageLite> {
private static final LiteProtoSubjectFactory INSTANCE = new LiteProtoSubjectFactory();
@Override
public LiteProtoSubject createSubject(
FailureMetadata failureMetadata, @Nullable MessageLite messageLite) {
return new LiteProtoSubject(failureMetadata, messageLite);
}
}
}
| LiteProtoSubjectFactory |
java | grpc__grpc-java | stub/src/main/java/io/grpc/stub/CallStreamObserver.java | {
"start": 2503,
"end": 6294
} | class ____<V> implements StreamObserver<V> {
/**
* If {@code true}, indicates that the observer is capable of sending additional messages
* without requiring excessive buffering internally. This value is just a suggestion and the
* application is free to ignore it, however doing so may result in excessive buffering within the
* observer.
*
* <p>If {@code false}, the runnable passed to {@link #setOnReadyHandler} will be called after
* {@code isReady()} transitions to {@code true}.
*/
public abstract boolean isReady();
/**
* Set a {@link Runnable} that will be executed every time the stream {@link #isReady()} state
* changes from {@code false} to {@code true}. While it is not guaranteed that the same
* thread will always be used to execute the {@link Runnable}, it is guaranteed that executions
* are serialized with calls to the 'inbound' {@link StreamObserver}.
*
* <p>On client-side this method may only be called during {@link
* ClientResponseObserver#beforeStart}. On server-side it may only be called during the initial
* call to the application, before the service returns its {@code StreamObserver}.
*
* <p>Because there is a processing delay to deliver this notification, it is possible for
* concurrent writes to cause {@code isReady() == false} within this callback. Handle "spurious"
* notifications by checking {@code isReady()}'s current value instead of assuming it is now
* {@code true}. If {@code isReady() == false} the normal expectations apply, so there would be
* <em>another</em> {@code onReadyHandler} callback.
*
* @param onReadyHandler to call when peer is ready to receive more messages.
*/
public abstract void setOnReadyHandler(Runnable onReadyHandler);
/**
* Disables automatic flow control where a token is returned to the peer after a call
* to the 'inbound' {@link io.grpc.stub.StreamObserver#onNext(Object)} has completed. If disabled
* an application must make explicit calls to {@link #request} to receive messages.
*
* <p>On client-side this method may only be called during {@link
* ClientResponseObserver#beforeStart}. On server-side it may only be called during the initial
* call to the application, before the service returns its {@code StreamObserver}.
*
* <p>Note that for cases where the runtime knows that only one inbound message is allowed
* calling this method will have no effect and the runtime will always permit one and only
* one message. This is true for:
* <ul>
* <li>{@link io.grpc.MethodDescriptor.MethodType#UNARY} operations on both the
* client and server.
* </li>
* <li>{@link io.grpc.MethodDescriptor.MethodType#CLIENT_STREAMING} operations on the client.
* </li>
* <li>{@link io.grpc.MethodDescriptor.MethodType#SERVER_STREAMING} operations on the server.
* </li>
* </ul>
* </p>
*
* <p>This API is being replaced, but is not yet deprecated. On server-side it being replaced
* with {@link ServerCallStreamObserver#disableAutoRequest}. On client-side {@link
* ClientCallStreamObserver#disableAutoRequestWithInitial disableAutoRequestWithInitial(1)}.
*/
public abstract void disableAutoInboundFlowControl();
/**
* Requests the peer to produce {@code count} more messages to be delivered to the 'inbound'
* {@link StreamObserver}.
*
* <p>This method is safe to call from multiple threads without external synchronization.
*
* @param count more messages
*/
public abstract void request(int count);
/**
* Sets message compression for subsequent calls to {@link #onNext}.
*
* @param enable whether to enable compression.
*/
public abstract void setMessageCompression(boolean enable);
}
| CallStreamObserver |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/TruthIncompatibleTypeTest.java | {
"start": 7013,
"end": 7518
} | class ____ {
public void f(Iterable<Long> xs, Number x) {
assertThat(xs).containsExactlyElementsIn(ImmutableList.of(x));
}
}
""")
.doTest();
}
@Test
public void variadicCall_noMatch() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import static com.google.common.truth.Truth.assertThat;
import com.google.common.collect.ImmutableList;
public | Test |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/util/Loader.java | {
"start": 9936,
"end": 10048
} | class ____.
* @return The class, or null if loader is null.
* @throws ClassNotFoundException if the | loader |
java | quarkusio__quarkus | independent-projects/qute/debug/src/main/java/io/quarkus/qute/debug/agent/completions/CompletionContext.java | {
"start": 958,
"end": 5046
} | class ____ implements ValueResolverContext {
/** Empty array of completion items for DAP responses. */
public static final CompletionItem[] EMPTY_COMPLETION_ITEMS = new CompletionItem[0];
/** The object to inspect for completions. */
private final Object base;
/** Stack frame associated with this context. */
private final RemoteStackFrame stackFrame;
/** Collected completion items. */
private final Collection<CompletionItem> targets;
/** Prevents duplicate completion labels. */
private final Set<String> existingNames;
public CompletionContext(Object base, RemoteStackFrame stackFrame) {
this.base = base;
this.stackFrame = stackFrame;
this.targets = new ArrayList<>();
this.existingNames = new HashSet<>();
}
public Object getBase() {
return base;
}
public RemoteStackFrame getStackFrame() {
return stackFrame;
}
/** Converts collected items to a DAP {@link CompletionsResponse}. */
public CompletionsResponse toResponse() {
CompletionsResponse response = new CompletionsResponse();
response.setTargets(targets.toArray(EMPTY_COMPLETION_ITEMS));
return response;
}
@Override
public void addMethod(Method method) {
CompletionItem item = new CompletionItem();
StringBuilder signature = new StringBuilder(method.getName());
signature.append("(");
var parameters = method.getParameters();
int selectionStart = parameters.length > 0 ? signature.length() : -1;
int selectionLength = -1;
for (int i = 0; i < parameters.length; i++) {
if (i > 0) {
signature.append(",");
}
String arg = parameters[i].getName();
signature.append(arg);
if (i == 0) {
selectionLength = arg.length();
}
}
signature.append(")");
item.setLabel(signature.toString());
item.setType(CompletionItemType.METHOD);
if (selectionStart != -1) {
item.setSelectionStart(selectionStart);
item.setSelectionLength(selectionLength);
}
add(item);
}
@Override
public void addProperty(Field field) {
CompletionItem item = new CompletionItem();
item.setLabel(field.getName());
item.setType(CompletionItemType.FIELD);
add(item);
}
@Override
public void addProperty(String property) {
add(createItem(property, CompletionItemType.PROPERTY));
}
@Override
public void addMethod(String method) {
add(createItem(method, CompletionItemType.FUNCTION));
}
/** Adds a completion item if it is not already present. */
public void add(CompletionItem item) {
if (!existingNames.contains(item.getLabel())) {
existingNames.add(item.getLabel());
targets.add(item);
}
}
/** Creates a completion item from a property or method name. */
private static CompletionItem createItem(String property, CompletionItemType type) {
String label = property;
CompletionItem item = new CompletionItem();
int selectionStart = property.indexOf("${");
int selectionEnd = -1;
if (selectionStart != -1) {
selectionEnd = property.indexOf("}", selectionStart + 1);
if (selectionEnd != -1) {
label = property.substring(0, selectionStart) + property.substring(selectionStart + 2, selectionEnd)
+ property.substring(selectionEnd + 1, property.length());
}
}
item.setLabel(label);
item.setType(type);
if (selectionEnd != -1) {
item.setSelectionStart(selectionStart);
item.setSelectionLength(selectionEnd - selectionStart - 2);
}
return item;
}
@Override
public boolean isCollectProperty() {
return true;
}
@Override
public boolean isCollectMethod() {
return true;
}
}
| CompletionContext |
java | google__dagger | javatests/dagger/hilt/android/EarlyEntryPointNoEntryPointsDefinedTest.java | {
"start": 2710,
"end": 3292
} | class ____ @HiltAndroidTest and that the processor is "
+ "running over your test");
}
@Test
public void testEarlyEntryPointsWrongEntryPointFails() throws Exception {
IllegalStateException exception =
assertThrows(
IllegalStateException.class,
() -> EarlyEntryPoints.get(getApplicationContext(), FooEntryPoint.class));
assertThat(exception)
.hasMessageThat()
.contains(
"FooEntryPoint should be called with EntryPoints.get() rather than "
+ "EarlyEntryPoints.get()");
}
}
| with |
java | eclipse-vertx__vert.x | vertx-core/src/main/java/io/vertx/core/net/impl/ServerID.java | {
"start": 547,
"end": 1258
} | class ____ {
private final int port;
private final String host;
public ServerID(int port, String host) {
this.port = port;
this.host = host;
}
public int port() {
return port;
}
public String host() {
return host;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof ServerID)) {
return false;
}
ServerID that = (ServerID) o;
return port == that.port && Objects.equals(host, that.host);
}
@Override
public int hashCode() {
int result = port;
result = 31 * result + host.hashCode();
return result;
}
public String toString() {
return host + ":" + port;
}
}
| ServerID |
java | apache__kafka | shell/src/main/java/org/apache/kafka/shell/command/HistoryCommandHandler.java | {
"start": 1418,
"end": 3603
} | class ____ implements Commands.Type {
private HistoryCommandType() {
}
@Override
public String name() {
return "history";
}
@Override
public String description() {
return "Print command history.";
}
@Override
public boolean shellOnly() {
return true;
}
@Override
public void addArguments(ArgumentParser parser) {
parser.addArgument("numEntriesToShow").
nargs("?").
type(Integer.class).
help("The number of entries to show.");
}
@Override
public Commands.Handler createHandler(Namespace namespace) {
Integer numEntriesToShow = namespace.getInt("numEntriesToShow");
return new HistoryCommandHandler(numEntriesToShow == null ?
Integer.MAX_VALUE : numEntriesToShow);
}
@Override
public void completeNext(
MetadataShellState state,
List<String> nextWords,
List<Candidate> candidates
) throws Exception {
// nothing to do
}
}
private final int numEntriesToShow;
public HistoryCommandHandler(int numEntriesToShow) {
this.numEntriesToShow = numEntriesToShow;
}
@Override
public void run(
Optional<InteractiveShell> shell,
PrintWriter writer,
MetadataShellState state
) throws Exception {
if (shell.isEmpty()) {
throw new RuntimeException("The history command requires a shell.");
}
Iterator<Map.Entry<Integer, String>> iter = shell.get().history(numEntriesToShow);
while (iter.hasNext()) {
Map.Entry<Integer, String> entry = iter.next();
writer.printf("% 5d %s%n", entry.getKey(), entry.getValue());
}
}
@Override
public int hashCode() {
return numEntriesToShow;
}
@Override
public boolean equals(Object other) {
if (!(other instanceof HistoryCommandHandler o)) return false;
return o.numEntriesToShow == numEntriesToShow;
}
}
| HistoryCommandType |
java | google__guava | android/guava-tests/test/com/google/common/hash/MacHashFunctionTest.java | {
"start": 1419,
"end": 14154
} | class ____ extends TestCase {
private static final ImmutableSet<String> INPUTS = ImmutableSet.of("", "Z", "foobar");
private static final SecretKey MD5_KEY =
new SecretKeySpec("secret key".getBytes(UTF_8), "HmacMD5");
private static final SecretKey SHA1_KEY =
new SecretKeySpec("secret key".getBytes(UTF_8), "HmacSHA1");
private static final SecretKey SHA256_KEY =
new SecretKeySpec("secret key".getBytes(UTF_8), "HmacSHA256");
private static final SecretKey SHA512_KEY =
new SecretKeySpec("secret key".getBytes(UTF_8), "HmacSHA512");
// From http://docs.oracle.com/javase/7/docs/technotes/guides/security/StandardNames.html#Mac
private static final ImmutableTable<String, SecretKey, HashFunction> ALGORITHMS =
new ImmutableTable.Builder<String, SecretKey, HashFunction>()
.put("HmacMD5", MD5_KEY, Hashing.hmacMd5(MD5_KEY))
.put("HmacSHA1", SHA1_KEY, Hashing.hmacSha1(SHA1_KEY))
.put("HmacSHA256", SHA256_KEY, Hashing.hmacSha256(SHA256_KEY))
.put("HmacSHA512", SHA512_KEY, Hashing.hmacSha512(SHA512_KEY))
.buildOrThrow();
public void testNulls() {
NullPointerTester tester =
new NullPointerTester().setDefault(String.class, "HmacMD5").setDefault(Key.class, MD5_KEY);
tester.testAllPublicConstructors(MacHashFunction.class);
tester.testAllPublicInstanceMethods(new MacHashFunction("HmacMD5", MD5_KEY, "toString"));
}
public void testHashing() throws Exception {
for (String stringToTest : INPUTS) {
for (Table.Cell<String, SecretKey, HashFunction> cell : ALGORITHMS.cellSet()) {
String algorithm = cell.getRowKey();
SecretKey key = cell.getColumnKey();
HashFunction hashFunc = cell.getValue();
assertMacHashing(HashTestUtils.ascii(stringToTest), algorithm, key, hashFunc);
}
}
}
@AndroidIncompatible // sun.security
public void testNoProviders() {
ProviderList providers = Providers.getProviderList();
Providers.setProviderList(ProviderList.newList());
try {
Hashing.hmacMd5(MD5_KEY);
fail("expected ISE");
} catch (IllegalStateException expected) {
} finally {
Providers.setProviderList(providers);
}
}
public void testMultipleUpdates() throws Exception {
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(SHA1_KEY);
mac.update("hello".getBytes(UTF_8));
mac.update("world".getBytes(UTF_8));
assertEquals(
HashCode.fromBytes(mac.doFinal()),
Hashing.hmacSha1(SHA1_KEY)
.newHasher()
.putString("hello", UTF_8)
.putString("world", UTF_8)
.hash());
}
public void testMultipleUpdatesDoFinal() throws Exception {
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(SHA1_KEY);
mac.update("hello".getBytes(UTF_8));
mac.update("world".getBytes(UTF_8));
assertEquals(
HashCode.fromBytes(mac.doFinal("!!!".getBytes(UTF_8))),
Hashing.hmacSha1(SHA1_KEY)
.newHasher()
.putString("hello", UTF_8)
.putString("world", UTF_8)
.putString("!!!", UTF_8)
.hash());
}
public void testCustomKey() throws Exception {
SecretKey customKey =
new SecretKey() {
@Override
public String getAlgorithm() {
return "HmacMD5";
}
@Override
public byte[] getEncoded() {
return new byte[8];
}
@Override
public String getFormat() {
return "RAW";
}
};
assertEquals(
"ad262969c53bc16032f160081c4a07a0",
Hashing.hmacMd5(customKey)
.hashString("The quick brown fox jumps over the lazy dog", UTF_8)
.toString());
}
public void testBadKey_emptyKey() throws Exception {
SecretKey badKey =
new SecretKey() {
@Override
public String getAlgorithm() {
return "HmacMD5";
}
@Override
public byte @Nullable [] getEncoded() {
return null;
}
@Override
public String getFormat() {
return "RAW";
}
};
try {
Hashing.hmacMd5(badKey);
fail();
} catch (IllegalArgumentException expected) {
} catch (NullPointerException toleratedOnAndroid) {
// TODO(cpovirk): In an ideal world, we'd check here that we're running on Android.
}
}
public void testEmptyInputs() throws Exception {
String knownOutput = "8cbf764cbe2e4623d99a41354adfd390";
Mac mac = Mac.getInstance("HmacMD5");
mac.init(MD5_KEY);
assertEquals(knownOutput, HashCode.fromBytes(mac.doFinal()).toString());
assertEquals(knownOutput, Hashing.hmacMd5(MD5_KEY).newHasher().hash().toString());
}
public void testEmptyInputs_mixedAlgorithms() throws Exception {
String knownOutput = "8cbf764cbe2e4623d99a41354adfd390";
Mac mac = Mac.getInstance("HmacMD5");
mac.init(SHA1_KEY);
assertEquals(knownOutput, HashCode.fromBytes(mac.doFinal()).toString());
assertEquals(knownOutput, Hashing.hmacMd5(SHA1_KEY).newHasher().hash().toString());
}
public void testKnownInputs() throws Exception {
String knownOutput = "9753980fe94daa8ecaa82216519393a9";
String input = "The quick brown fox jumps over the lazy dog";
Mac mac = Mac.getInstance("HmacMD5");
mac.init(MD5_KEY);
mac.update(input.getBytes(UTF_8));
assertEquals(knownOutput, HashCode.fromBytes(mac.doFinal()).toString());
assertEquals(knownOutput, HashCode.fromBytes(mac.doFinal(input.getBytes(UTF_8))).toString());
assertEquals(knownOutput, Hashing.hmacMd5(MD5_KEY).hashString(input, UTF_8).toString());
assertEquals(knownOutput, Hashing.hmacMd5(MD5_KEY).hashBytes(input.getBytes(UTF_8)).toString());
}
public void testKnownInputs_mixedAlgorithms() throws Exception {
String knownOutput = "9753980fe94daa8ecaa82216519393a9";
String input = "The quick brown fox jumps over the lazy dog";
Mac mac = Mac.getInstance("HmacMD5");
mac.init(SHA1_KEY);
mac.update(input.getBytes(UTF_8));
assertEquals(knownOutput, HashCode.fromBytes(mac.doFinal()).toString());
assertEquals(knownOutput, HashCode.fromBytes(mac.doFinal(input.getBytes(UTF_8))).toString());
assertEquals(knownOutput, Hashing.hmacMd5(SHA1_KEY).hashString(input, UTF_8).toString());
assertEquals(
knownOutput, Hashing.hmacMd5(SHA1_KEY).hashBytes(input.getBytes(UTF_8)).toString());
}
public void testPutAfterHash() {
Hasher hasher = Hashing.hmacMd5(MD5_KEY).newHasher();
assertEquals(
"9753980fe94daa8ecaa82216519393a9",
hasher.putString("The quick brown fox jumps over the lazy dog", UTF_8).hash().toString());
assertThrows(IllegalStateException.class, () -> hasher.putInt(42));
}
public void testHashTwice() {
Hasher hasher = Hashing.hmacMd5(MD5_KEY).newHasher();
assertEquals(
"9753980fe94daa8ecaa82216519393a9",
hasher.putString("The quick brown fox jumps over the lazy dog", UTF_8).hash().toString());
assertThrows(IllegalStateException.class, () -> hasher.hash());
}
public void testToString() {
byte[] keyData = "secret key".getBytes(UTF_8);
assertEquals(
"Hashing.hmacMd5(Key[algorithm=HmacMD5, format=RAW])", Hashing.hmacMd5(MD5_KEY).toString());
assertEquals(
"Hashing.hmacMd5(Key[algorithm=HmacMD5, format=RAW])", Hashing.hmacMd5(keyData).toString());
assertEquals(
"Hashing.hmacSha1(Key[algorithm=HmacSHA1, format=RAW])",
Hashing.hmacSha1(SHA1_KEY).toString());
assertEquals(
"Hashing.hmacSha1(Key[algorithm=HmacSHA1, format=RAW])",
Hashing.hmacSha1(keyData).toString());
assertEquals(
"Hashing.hmacSha256(Key[algorithm=HmacSHA256, format=RAW])",
Hashing.hmacSha256(SHA256_KEY).toString());
assertEquals(
"Hashing.hmacSha256(Key[algorithm=HmacSHA256, format=RAW])",
Hashing.hmacSha256(keyData).toString());
assertEquals(
"Hashing.hmacSha512(Key[algorithm=HmacSHA512, format=RAW])",
Hashing.hmacSha512(SHA512_KEY).toString());
assertEquals(
"Hashing.hmacSha512(Key[algorithm=HmacSHA512, format=RAW])",
Hashing.hmacSha512(keyData).toString());
}
private static void assertMacHashing(
byte[] input, String algorithm, SecretKey key, HashFunction hashFunc) throws Exception {
Mac mac = Mac.getInstance(algorithm);
mac.init(key);
mac.update(input);
assertEquals(HashCode.fromBytes(mac.doFinal()), hashFunc.hashBytes(input));
assertEquals(HashCode.fromBytes(mac.doFinal(input)), hashFunc.hashBytes(input));
}
// Tests from RFC2022: https://tools.ietf.org/html/rfc2202
public void testRfc2202_hmacSha1_case1() {
byte[] key = fillByteArray(20, 0x0b);
String data = "Hi There";
checkSha1("b617318655057264e28bc0b6fb378c8ef146be00", key, data);
}
public void testRfc2202_hmacSha1_case2() {
byte[] key = "Jefe".getBytes(UTF_8);
String data = "what do ya want for nothing?";
checkSha1("effcdf6ae5eb2fa2d27416d5f184df9c259a7c79", key, data);
}
public void testRfc2202_hmacSha1_case3() {
byte[] key = fillByteArray(20, 0xaa);
byte[] data = fillByteArray(50, 0xdd);
checkSha1("125d7342b9ac11cd91a39af48aa17b4f63f175d3", key, data);
}
public void testRfc2202_hmacSha1_case4() {
byte[] key = base16().lowerCase().decode("0102030405060708090a0b0c0d0e0f10111213141516171819");
byte[] data = fillByteArray(50, 0xcd);
checkSha1("4c9007f4026250c6bc8414f9bf50c86c2d7235da", key, data);
}
public void testRfc2202_hmacSha1_case5() {
byte[] key = fillByteArray(20, 0x0c);
String data = "Test With Truncation";
checkSha1("4c1a03424b55e07fe7f27be1d58bb9324a9a5a04", key, data);
}
public void testRfc2202_hmacSha1_case6() {
byte[] key = fillByteArray(80, 0xaa);
String data = "Test Using Larger Than Block-Size Key - Hash Key First";
checkSha1("aa4ae5e15272d00e95705637ce8a3b55ed402112", key, data);
}
public void testRfc2202_hmacSha1_case7() {
byte[] key = fillByteArray(80, 0xaa);
String data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data";
checkSha1("e8e99d0f45237d786d6bbaa7965c7808bbff1a91", key, data);
}
public void testRfc2202_hmacMd5_case1() {
byte[] key = fillByteArray(16, 0x0b);
String data = "Hi There";
checkMd5("9294727a3638bb1c13f48ef8158bfc9d", key, data);
}
public void testRfc2202_hmacMd5_case2() {
byte[] key = "Jefe".getBytes(UTF_8);
String data = "what do ya want for nothing?";
checkMd5("750c783e6ab0b503eaa86e310a5db738", key, data);
}
public void testRfc2202_hmacMd5_case3() {
byte[] key = fillByteArray(16, 0xaa);
byte[] data = fillByteArray(50, 0xdd);
checkMd5("56be34521d144c88dbb8c733f0e8b3f6", key, data);
}
public void testRfc2202_hmacMd5_case4() {
byte[] key = base16().lowerCase().decode("0102030405060708090a0b0c0d0e0f10111213141516171819");
byte[] data = fillByteArray(50, 0xcd);
checkMd5("697eaf0aca3a3aea3a75164746ffaa79", key, data);
}
public void testRfc2202_hmacMd5_case5() {
byte[] key = fillByteArray(16, 0x0c);
String data = "Test With Truncation";
checkMd5("56461ef2342edc00f9bab995690efd4c", key, data);
}
public void testRfc2202_hmacMd5_case6() {
byte[] key = fillByteArray(80, 0xaa);
String data = "Test Using Larger Than Block-Size Key - Hash Key First";
checkMd5("6b1ab7fe4bd7bf8f0b62e6ce61b9d0cd", key, data);
}
public void testRfc2202_hmacMd5_case7() {
byte[] key = fillByteArray(80, 0xaa);
String data = "Test Using Larger Than Block-Size Key and Larger Than One Block-Size Data";
checkMd5("6f630fad67cda0ee1fb1f562db3aa53e", key, data);
}
private static void checkSha1(String expected, byte[] key, String data) {
checkSha1(expected, key, data.getBytes(UTF_8));
}
private static void checkSha1(String expected, byte[] key, byte[] data) {
checkHmac(expected, Hashing.hmacSha1(key), data);
}
private static void checkMd5(String expected, byte[] key, String data) {
checkMd5(expected, key, data.getBytes(UTF_8));
}
private static void checkMd5(String expected, byte[] key, byte[] data) {
checkHmac(expected, Hashing.hmacMd5(key), data);
}
private static void checkHmac(String expected, HashFunction hashFunc, byte[] data) {
assertEquals(HashCode.fromString(expected), hashFunc.hashBytes(data));
}
private static byte[] fillByteArray(int size, int toFillWith) {
byte[] array = new byte[size];
Arrays.fill(array, (byte) toFillWith);
return array;
}
}
| MacHashFunctionTest |
java | apache__camel | dsl/camel-jbang/camel-jbang-plugin-edit/src/main/java/org/apache/camel/dsl/jbang/core/commands/edit/EditCommand.java | {
"start": 2826,
"end": 3039
} | class ____ extends ParameterConsumer<EditCommand> {
@Override
protected void doConsumeParameters(Stack<String> args, EditCommand cmd) {
cmd.file = args.pop();
}
}
}
| FileConsumer |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/ClassTemplateInvocationTests.java | {
"start": 55659,
"end": 55842
} | class ____ {
@Test
void a() {
}
@Nested
@ClassTemplate
@ExtendWith(TwoInvocationsClassTemplateInvocationContextProvider.class)
| NestedClassTemplateWithTwoInvocationsTestCase |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/ErrorTranslation.java | {
"start": 9579,
"end": 9927
} | class ____ is
// so rather than use its type, we look for an OpenSSL string in the message
if (thrown.getMessage().contains(OPENSSL_STREAM_CLOSED)) {
return new HttpChannelEOFException(path, message, thrown);
}
return null;
}
/**
* AWS error codes explicitly recognized and processes specially;
* kept in their own | this |
java | apache__camel | components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FromFtpNoFilesIT.java | {
"start": 1308,
"end": 2144
} | class ____ extends FtpServerTestSupport {
private String getFtpUrl() {
return "ftp://admin@localhost:{{ftp.server.port}}/slowfile?password=admin&binary=false&readLock=rename&delay=2000";
}
@Test
public void testPoolIn3SecondsButNoFiles() {
deleteDirectory(service.getFtpRootDir());
createDirectory(service.getFtpRootDir().resolve("slowfile"));
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(0);
await().atMost(3, TimeUnit.SECONDS)
.untilAsserted(() -> mock.assertIsSatisfied());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from(getFtpUrl()).to("mock:result");
}
};
}
}
| FromFtpNoFilesIT |
java | apache__camel | components/camel-thrift/src/test/java/org/apache/camel/component/thrift/generated/Calculator.java | {
"start": 44519,
"end": 48727
} | class ____<I extends AsyncIface>
extends org.apache.thrift.AsyncProcessFunction<I, calculate_args, java.lang.Integer, calculate_result> {
public calculate() {
super("calculate");
}
@Override
public calculate_result getEmptyResultInstance() {
return new calculate_result();
}
@Override
public calculate_args getEmptyArgsInstance() {
return new calculate_args();
}
@Override
public org.apache.thrift.async.AsyncMethodCallback<java.lang.Integer> getResultHandler(
final org.apache.thrift.server.AbstractNonblockingServer.AsyncFrameBuffer fb, final int seqid) {
final org.apache.thrift.AsyncProcessFunction fcall = this;
return new org.apache.thrift.async.AsyncMethodCallback<java.lang.Integer>() {
@Override
public void onComplete(java.lang.Integer o) {
calculate_result result = new calculate_result();
result.success = o;
result.setSuccessIsSet(true);
try {
fcall.sendResponse(fb, result, org.apache.thrift.protocol.TMessageType.REPLY, seqid);
} catch (org.apache.thrift.transport.TTransportException e) {
_LOGGER.error("TTransportException writing to internal frame buffer", e);
fb.close();
} catch (java.lang.Exception e) {
_LOGGER.error("Exception writing to internal frame buffer", e);
onError(e);
}
}
@Override
public void onError(java.lang.Exception e) {
byte msgType = org.apache.thrift.protocol.TMessageType.REPLY;
org.apache.thrift.TSerializable msg;
calculate_result result = new calculate_result();
if (e instanceof InvalidOperation) {
result.ouch = (InvalidOperation) e;
result.setOuchIsSet(true);
msg = result;
} else if (e instanceof org.apache.thrift.transport.TTransportException) {
_LOGGER.error("TTransportException inside handler", e);
fb.close();
return;
} else if (e instanceof org.apache.thrift.TApplicationException) {
_LOGGER.error("TApplicationException inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = (org.apache.thrift.TApplicationException) e;
} else {
_LOGGER.error("Exception inside handler", e);
msgType = org.apache.thrift.protocol.TMessageType.EXCEPTION;
msg = new org.apache.thrift.TApplicationException(
org.apache.thrift.TApplicationException.INTERNAL_ERROR, e.getMessage());
}
try {
fcall.sendResponse(fb, msg, msgType, seqid);
} catch (java.lang.Exception ex) {
_LOGGER.error("Exception writing to internal frame buffer", ex);
fb.close();
}
}
};
}
@Override
public boolean isOneway() {
return false;
}
@Override
public void start(
I iface, calculate_args args, org.apache.thrift.async.AsyncMethodCallback<java.lang.Integer> resultHandler)
throws org.apache.thrift.TException {
iface.calculate(args.logid, args.w, resultHandler);
}
}
public static | calculate |
java | quarkusio__quarkus | extensions/netty/runtime/src/main/java/io/quarkus/netty/runtime/graal/NettySubstitutions.java | {
"start": 18195,
"end": 18800
} | class ____ {
// The START_TIME field is kept but not used.
// All the accesses to it have been replaced with Holder_io_netty_util_concurrent_ScheduledFutureTask
@Substitute
static long initialNanoTime() {
return Holder_io_netty_util_concurrent_ScheduledFutureTask.START_TIME;
}
@Substitute
static long defaultCurrentTimeNanos() {
return System.nanoTime() - Holder_io_netty_util_concurrent_ScheduledFutureTask.START_TIME;
}
}
@TargetClass(className = "io.netty.channel.ChannelHandlerMask")
final | Target_io_netty_util_concurrent_AbstractScheduledEventExecutor |
java | netty__netty | testsuite/src/main/java/io/netty/testsuite/transport/socket/SocketDataReadInitialStateTest.java | {
"start": 1460,
"end": 8520
} | class ____ extends AbstractSocketTest {
@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testAutoReadOffNoDataReadUntilReadCalled(TestInfo testInfo) throws Throwable {
run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
@Override
public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
testAutoReadOffNoDataReadUntilReadCalled(serverBootstrap, bootstrap);
}
});
}
public void testAutoReadOffNoDataReadUntilReadCalled(ServerBootstrap sb, Bootstrap cb) throws Throwable {
Channel serverChannel = null;
Channel clientChannel = null;
final int sleepMs = 100;
try {
sb.option(AUTO_READ, false);
sb.childOption(AUTO_READ, false);
cb.option(AUTO_READ, false);
final CountDownLatch serverReadyLatch = new CountDownLatch(1);
final CountDownLatch acceptorReadLatch = new CountDownLatch(1);
final CountDownLatch serverReadLatch = new CountDownLatch(1);
final CountDownLatch clientReadLatch = new CountDownLatch(1);
final AtomicReference<Channel> serverConnectedChannelRef = new AtomicReference<Channel>();
sb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) {
acceptorReadLatch.countDown();
ctx.fireChannelRead(msg);
}
});
}
});
sb.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
serverConnectedChannelRef.set(ch);
ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
ctx.writeAndFlush(msg.retainedDuplicate());
serverReadLatch.countDown();
}
});
serverReadyLatch.countDown();
}
});
cb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
clientReadLatch.countDown();
}
});
}
});
serverChannel = sb.bind().sync().channel();
clientChannel = cb.connect(serverChannel.localAddress()).sync().channel();
clientChannel.writeAndFlush(clientChannel.alloc().buffer().writeZero(1)).syncUninterruptibly();
// The acceptor shouldn't read any data until we call read() below, but give it some time to see if it will.
Thread.sleep(sleepMs);
assertEquals(1, acceptorReadLatch.getCount());
serverChannel.read();
serverReadyLatch.await();
Channel serverConnectedChannel = serverConnectedChannelRef.get();
assertNotNull(serverConnectedChannel);
// Allow some amount of time for the server peer to receive the message (which isn't expected to happen
// until we call read() below).
Thread.sleep(sleepMs);
assertEquals(1, serverReadLatch.getCount());
serverConnectedChannel.read();
serverReadLatch.await();
// Allow some amount of time for the client to read the echo.
Thread.sleep(sleepMs);
assertEquals(1, clientReadLatch.getCount());
clientChannel.read();
clientReadLatch.await();
} finally {
if (serverChannel != null) {
serverChannel.close().sync();
}
if (clientChannel != null) {
clientChannel.close().sync();
}
}
}
@Test
@Timeout(value = 10000, unit = TimeUnit.MILLISECONDS)
public void testAutoReadOnDataReadImmediately(TestInfo testInfo) throws Throwable {
run(testInfo, new Runner<ServerBootstrap, Bootstrap>() {
@Override
public void run(ServerBootstrap serverBootstrap, Bootstrap bootstrap) throws Throwable {
testAutoReadOnDataReadImmediately(serverBootstrap, bootstrap);
}
});
}
public void testAutoReadOnDataReadImmediately(ServerBootstrap sb, Bootstrap cb) throws Throwable {
Channel serverChannel = null;
Channel clientChannel = null;
try {
sb.option(AUTO_READ, true);
sb.childOption(AUTO_READ, true);
cb.option(AUTO_READ, true);
final CountDownLatch serverReadLatch = new CountDownLatch(1);
final CountDownLatch clientReadLatch = new CountDownLatch(1);
sb.childHandler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new SimpleChannelInboundHandler<ByteBuf>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
ctx.writeAndFlush(msg.retainedDuplicate());
serverReadLatch.countDown();
}
});
}
});
cb.handler(new ChannelInitializer<Channel>() {
@Override
protected void initChannel(Channel ch) {
ch.pipeline().addLast(new SimpleChannelInboundHandler<Object>() {
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
clientReadLatch.countDown();
}
});
}
});
serverChannel = sb.bind().sync().channel();
clientChannel = cb.connect(serverChannel.localAddress()).sync().channel();
clientChannel.writeAndFlush(clientChannel.alloc().buffer().writeZero(1)).syncUninterruptibly();
serverReadLatch.await();
clientReadLatch.await();
} finally {
if (serverChannel != null) {
serverChannel.close().sync();
}
if (clientChannel != null) {
clientChannel.close().sync();
}
}
}
}
| SocketDataReadInitialStateTest |
java | apache__camel | components/camel-google/camel-google-mail/src/generated/java/org/apache/camel/component/google/mail/GoogleMailEndpointUriFactory.java | {
"start": 521,
"end": 4364
} | class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = ":apiName/methodName";
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<>(53);
props.add("accessToken");
props.add("apiName");
props.add("applicationName");
props.add("backoffErrorThreshold");
props.add("backoffIdleThreshold");
props.add("backoffMultiplier");
props.add("batchDeleteMessagesRequest");
props.add("batchModifyMessagesRequest");
props.add("bridgeErrorHandler");
props.add("clientId");
props.add("clientSecret");
props.add("content");
props.add("delay");
props.add("delegate");
props.add("deleted");
props.add("exceptionHandler");
props.add("exchangePattern");
props.add("format");
props.add("greedy");
props.add("historyTypes");
props.add("id");
props.add("inBody");
props.add("includeSpamTrash");
props.add("initialDelay");
props.add("internalDateSource");
props.add("labelId");
props.add("labelIds");
props.add("lazyStartProducer");
props.add("maxResults");
props.add("mediaContent");
props.add("messageId");
props.add("metadataHeaders");
props.add("methodName");
props.add("modifyMessageRequest");
props.add("neverMarkSpam");
props.add("pageToken");
props.add("pollStrategy");
props.add("processForCalendar");
props.add("q");
props.add("refreshToken");
props.add("repeatCount");
props.add("runLoggingLevel");
props.add("scheduledExecutorService");
props.add("scheduler");
props.add("schedulerProperties");
props.add("scopes");
props.add("sendEmptyMessageWhenIdle");
props.add("serviceAccountKey");
props.add("startHistoryId");
props.add("startScheduler");
props.add("timeUnit");
props.add("useFixedDelay");
props.add("userId");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
Set<String> secretProps = new HashSet<>(3);
secretProps.add("accessToken");
secretProps.add("clientSecret");
secretProps.add("refreshToken");
SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps);
Map<String, String> prefixes = new HashMap<>(1);
prefixes.put("schedulerProperties", "scheduler.");
MULTI_VALUE_PREFIXES = Collections.unmodifiableMap(prefixes);
}
@Override
public boolean isEnabled(String scheme) {
return "google-mail".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, "apiName", null, true, copy);
uri = buildPathParameter(syntax, uri, "methodName", 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;
}
}
| GoogleMailEndpointUriFactory |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy-jaxb/deployment/src/test/java/io/quarkus/resteasy/jaxb/deployment/ConsumesXMLTestCase.java | {
"start": 1112,
"end": 1342
} | class ____ {
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.TEXT_PLAIN)
public String post(Bar bar) {
return bar.name + " " + bar.description;
}
}
}
| FooResource |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/router/async/utils/AsyncApplyFunction.java | {
"start": 1123,
"end": 1245
} | interface ____ a function that
* asynchronously accepts a value of type T and produces a result
* of type R. This | represents |
java | elastic__elasticsearch | x-pack/plugin/security/qa/tls-basic/src/javaRestTest/java/org/elasticsearch/xpack/security/TlsWithBasicLicenseIT.java | {
"start": 1283,
"end": 4946
} | class ____ extends ESRestTestCase {
private static Path httpTrustStore;
@BeforeClass
public static void findTrustStore() throws Exception {
final URL resource = TlsWithBasicLicenseIT.class.getResource("/ssl/ca.p12");
if (resource == null) {
throw new FileNotFoundException("Cannot find classpath resource /ssl/ca.p12");
}
httpTrustStore = PathUtils.get(resource.toURI());
}
@AfterClass
public static void cleanupStatics() {
httpTrustStore = null;
}
@Override
protected String getProtocol() {
return "https";
}
@Override
protected Settings restClientSettings() {
String token = basicAuthHeaderValue("admin", new SecureString("admin-password".toCharArray()));
return Settings.builder()
.put(ThreadContext.PREFIX + ".Authorization", token)
.put(TRUSTSTORE_PATH, httpTrustStore)
.put(TRUSTSTORE_PASSWORD, "password")
.build();
}
public void testWithBasicLicense() throws Exception {
checkLicenseType("basic");
checkSSLEnabled();
checkCertificateAPI();
}
public void testWithTrialLicense() throws Exception {
startTrial();
try {
checkLicenseType("trial");
checkSSLEnabled();
checkCertificateAPI();
} finally {
revertTrial();
}
}
private void startTrial() throws IOException {
Response response = client().performRequest(new Request("POST", "/_license/start_trial?acknowledge=true"));
assertOK(response);
}
private void revertTrial() throws IOException {
client().performRequest(new Request("POST", "/_license/start_basic?acknowledge=true"));
}
private void checkLicenseType(String type) throws Exception {
assertBusy(() -> {
try {
Map<String, Object> license = getAsMap("/_license");
assertThat(license, notNullValue());
assertThat(ObjectPath.evaluate(license, "license.type"), equalTo(type));
} catch (ResponseException e) {
throw new AssertionError(e);
}
});
}
private void checkSSLEnabled() throws IOException {
Map<String, Object> usage = getAsMap("/_xpack/usage");
assertThat(usage, notNullValue());
assertThat(ObjectPath.evaluate(usage, "security.ssl.http.enabled"), equalTo(true));
assertThat(ObjectPath.evaluate(usage, "security.ssl.transport.enabled"), equalTo(true));
}
@SuppressWarnings("unchecked")
private void checkCertificateAPI() throws IOException {
Response response = client().performRequest(new Request("GET", "/_ssl/certificates"));
ObjectPath path = ObjectPath.createFromResponse(response);
final Object body = path.evaluate("");
assertThat(body, instanceOf(List.class));
final List<?> certs = (List<?>) body;
assertThat(certs, iterableWithSize(3));
final List<Map<String, Object>> certInfo = new ArrayList<>();
for (int i = 0; i < certs.size(); i++) {
final Object element = certs.get(i);
assertThat(element, instanceOf(Map.class));
final Map<String, Object> map = (Map<String, Object>) element;
certInfo.add(map);
assertThat(map.get("format"), equalTo("PEM"));
}
List<String> paths = certInfo.stream().map(m -> String.valueOf(m.get("path"))).collect(Collectors.toList());
assertThat(paths, containsInAnyOrder("http.crt", "transport.crt", "ca.crt"));
}
}
| TlsWithBasicLicenseIT |
java | spring-projects__spring-boot | module/spring-boot-liquibase/src/main/java/org/springframework/boot/liquibase/autoconfigure/LiquibaseAutoConfiguration.java | {
"start": 8864,
"end": 9131
} | class ____ {
@Bean
@ConditionalOnBean(Customizer.class)
SpringLiquibaseCustomizer springLiquibaseCustomizer(Customizer<Liquibase> customizer) {
return (springLiquibase) -> springLiquibase.setCustomizer(customizer);
}
}
static final | CustomizerConfiguration |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/MixedMutabilityReturnTypeTest.java | {
"start": 14934,
"end": 15464
} | class ____ {
<T> List<T> foo(T a) {
if (hashCode() > 0) {
return new ArrayList<>(Collections.singleton(a));
}
return Collections.singletonList(a);
}
}
""")
.addOutputLines(
"Test.java",
"""
import com.google.common.collect.ImmutableList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
| Test |
java | google__guice | extensions/grapher/test/com/google/inject/grapher/demo/DancePartyFactory.java | {
"start": 747,
"end": 828
} | interface ____ {
DanceParty newDanceParty(String thatNewSound);
}
| DancePartyFactory |
java | alibaba__nacos | common/src/test/java/com/alibaba/nacos/common/pathencoder/PathEncoderManagerTest.java | {
"start": 1305,
"end": 4034
} | class ____ {
private String cachedOsName;
private Field targetEncoder;
private Object cachedEncoder;
@BeforeEach
void setUp() throws Exception {
cachedOsName = System.getProperty("os.name");
targetEncoder = PathEncoderManager.class.getDeclaredField("targetEncoder");
targetEncoder.setAccessible(true);
cachedEncoder = targetEncoder.get(PathEncoderManager.getInstance());
}
@AfterEach
void tearDown() throws Exception {
System.setProperty("os.name", cachedOsName);
targetEncoder.set(PathEncoderManager.getInstance(), cachedEncoder);
}
@Test
void testInitWithWindows()
throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
Constructor<PathEncoderManager> constructor = PathEncoderManager.class.getDeclaredConstructor();
constructor.setAccessible(true);
System.setProperty("os.name", "window");
PathEncoderManager instance = constructor.newInstance();
assertTrue(targetEncoder.get(instance) instanceof WindowsEncoder);
}
/**
* test expose method.
*/
@Test
void testWindowsEncode() throws Exception {
// load static
PathEncoderManager instance = PathEncoderManager.getInstance();
String case1 = "aa||a";
String case2 = "aa%A9%%A9%a";
// try to encode if in windows
targetEncoder.set(instance, new WindowsEncoder());
assertEquals(PathEncoderManager.getInstance().encode(case1), case2);
assertEquals(PathEncoderManager.getInstance().decode(case2), case1);
}
@Test
void testEncodeWithNonExistOs() throws Exception {
// load static
PathEncoderManager instance = PathEncoderManager.getInstance();
// remove impl
targetEncoder.set(instance, null);
// try to encode, non windows
String case1 = "aa||a";
assertEquals(PathEncoderManager.getInstance().encode(case1), case1);
String case2 = "aa%A9%%A9%a";
assertEquals(PathEncoderManager.getInstance().decode(case2), case2);
}
@Test
void testEncodeForNull() throws IllegalAccessException {
PathEncoder mockPathEncoder = mock(PathEncoder.class);
targetEncoder.set(PathEncoderManager.getInstance(), mockPathEncoder);
assertNull(PathEncoderManager.getInstance().encode(null));
assertNull(PathEncoderManager.getInstance().decode(null));
verify(mockPathEncoder, never()).encode(null, Charset.defaultCharset().name());
verify(mockPathEncoder, never()).decode(null, Charset.defaultCharset().name());
}
}
| PathEncoderManagerTest |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/web/client/RequestExpectation.java | {
"start": 1051,
"end": 1507
} | interface ____ extends ResponseActions, RequestMatcher, ResponseCreator {
/**
* Whether there is a remaining count of invocations for this expectation.
*/
boolean hasRemainingCount();
/**
* Increase the matched request count and check we haven't passed the max count.
* @since 5.0.3
*/
void incrementAndValidate();
/**
* Whether the requirements for this request expectation have been met.
*/
boolean isSatisfied();
}
| RequestExpectation |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/internal/log/SubSystemLogging.java | {
"start": 956,
"end": 1397
} | interface ____ {
/**
* Base category name for sub-system style logging
*/
String BASE = "org.hibernate.orm";
/**
* The sub-system name, which is used as the "logger name"
*/
String name();
/**
* Description of the information logged
*/
String description();
/**
* Aside from test usage, is the associated logger always used
* through the sub-system category name?
*/
boolean mixed() default false;
}
| SubSystemLogging |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/tier/NoOpMasterAgent.java | {
"start": 1065,
"end": 1814
} | class ____ implements TierMasterAgent {
public static final NoOpMasterAgent INSTANCE = new NoOpMasterAgent();
@Override
public void registerJob(JobID jobID, TierShuffleHandler tierShuffleHandler) {
// noop
}
@Override
public void unregisterJob(JobID jobID) {
// noop
}
@Override
public TierShuffleDescriptor addPartitionAndGetShuffleDescriptor(
JobID jobID, int numSubpartitions, ResultPartitionID resultPartitionID) {
// noop
return NoOpTierShuffleDescriptor.INSTANCE;
}
@Override
public void releasePartition(TierShuffleDescriptor shuffleDescriptor) {
// noop
}
@Override
public void close() {
// noop
}
}
| NoOpMasterAgent |
java | hibernate__hibernate-orm | tooling/metamodel-generator/src/main/java/org/hibernate/processor/annotation/CriteriaFinderMethod.java | {
"start": 312,
"end": 3769
} | class ____ extends AbstractCriteriaMethod {
private final List<Boolean> paramNullability;
CriteriaFinderMethod(
AnnotationMetaEntity annotationMetaEntity,
ExecutableElement method,
String methodName, String entity,
@Nullable String containerType,
List<String> paramNames, List<String> paramTypes,
List<Boolean> paramNullability,
List<Boolean> multivalued,
List<Boolean> paramPatterns,
boolean belongsToDao,
String sessionType,
String sessionName,
List<String> fetchProfiles,
List<OrderBy> orderBys,
boolean addNonnullAnnotation,
boolean dataRepository,
String fullReturnType,
boolean nullable) {
super( annotationMetaEntity, method, methodName, entity, containerType, belongsToDao, sessionType, sessionName,
fetchProfiles, paramNames, paramTypes, orderBys, addNonnullAnnotation, dataRepository, multivalued,
paramPatterns, fullReturnType, nullable );
this.paramNullability = paramNullability;
}
@Override
public boolean isNullable(int index) {
return paramNullability.get(index);
}
@Override
boolean singleResult() {
return containerType == null;
}
@Override
void executeQuery(StringBuilder declaration, List<String> paramTypes) {
declaration
.append('\n');
createSpecification( declaration );
handleRestrictionParameters( declaration, paramTypes );
collectOrdering( declaration, paramTypes, containerType );
inTry( declaration );
createQuery( declaration, true );
declaration.append( ";\n" );
results( declaration, paramTypes, containerType );
castResult( declaration );
select( declaration );
handlePageParameters( declaration, paramTypes, containerType );
boolean unwrapped = initiallyUnwrapped();
unwrapped = enableFetchProfile( declaration, unwrapped );
execute( declaration, paramTypes, unwrapped );
}
private void castResult(StringBuilder declaration) {
if ( containerType == null && !fetchProfiles.isEmpty()
&& isUsingEntityManager() ) {
declaration
.append("(")
.append(annotationMetaEntity.importType(entity))
.append(") ");
}
}
private void execute(StringBuilder declaration, List<String> paramTypes, boolean unwrapped) {
executeSelect( declaration, paramTypes, containerType, unwrapped, isHibernateQueryType(containerType) );
}
@Override
String createQueryMethod() {
return isUsingEntityManager()
|| isReactive()
|| isUnspecializedQueryType(containerType)
? "createQuery"
: "createSelectionQuery";
}
@Override
String createCriteriaMethod() {
return "createQuery";
}
// @Override
// String returnType() {
// final StringBuilder type = new StringBuilder();
// if ( "[]".equals(containerType) ) {
// if ( returnTypeName == null ) {
// throw new AssertionFailure("array return type, but no type name");
// }
// type.append(annotationMetaEntity.importType(returnTypeName)).append("[]");
// }
// else {
// final boolean returnsUni = isReactive() && isUnifiableReturnType(containerType);
// if ( returnsUni ) {
// type.append(annotationMetaEntity.importType(Constants.UNI)).append('<');
// }
// if ( containerType != null ) {
// type.append(annotationMetaEntity.importType(containerType)).append('<');
// }
// type.append(annotationMetaEntity.importType(entity));
// if ( containerType != null ) {
// type.append('>');
// }
// if ( returnsUni ) {
// type.append('>');
// }
// }
// return type.toString();
// }
}
| CriteriaFinderMethod |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/query/JpaQueryCreatorTests.java | {
"start": 31756,
"end": 32469
} | interface ____ {
QueryCreatorBuilder returning(ReturnedType returnedType);
QueryCreatorBuilder forTree(Class<?> root, String querySource);
QueryCreatorBuilder withParameters(Object... arguments);
QueryCreatorBuilder withParameterTypes(Class<?>... argumentTypes);
QueryCreatorBuilder ignoreCaseAs(JpqlQueryTemplates queryTemplate);
default <T> T as(Function<QueryCreatorBuilder, T> transformer) {
return transformer.apply(this);
}
default String render() {
return render(null);
}
ParameterAccessor bindableParameters();
int bindingIndexFor(String placeholder);
String render(@Nullable Sort sort);
QueryCreatorBuilder returning(Class<?> type);
}
private | QueryCreatorBuilder |
java | apache__camel | core/camel-core-model/src/main/java/org/apache/camel/model/cloud/CachingServiceCallServiceDiscoveryConfiguration.java | {
"start": 1525,
"end": 7597
} | class ____ extends ServiceCallServiceDiscoveryConfiguration {
@XmlAttribute
@Metadata(defaultValue = "60", javaType = "java.lang.Integer")
private String timeout = Integer.toString(60);
@XmlAttribute
@Metadata(javaType = "java.util.concurrent.TimeUnit", defaultValue = "SECONDS",
enums = "NANOSECONDS,MICROSECONDS,MILLISECONDS,SECONDS,MINUTES,HOURS,DAYS")
private String units = TimeUnit.SECONDS.name();
@XmlElements({
@XmlElement(name = "consulServiceDiscovery", type = ConsulServiceCallServiceDiscoveryConfiguration.class),
@XmlElement(name = "dnsServiceDiscovery", type = DnsServiceCallServiceDiscoveryConfiguration.class),
@XmlElement(name = "kubernetesServiceDiscovery", type = KubernetesServiceCallServiceDiscoveryConfiguration.class),
@XmlElement(name = "combinedServiceDiscovery", type = CombinedServiceCallServiceDiscoveryConfiguration.class),
@XmlElement(name = "staticServiceDiscovery", type = StaticServiceCallServiceDiscoveryConfiguration.class) })
private ServiceCallServiceDiscoveryConfiguration serviceDiscoveryConfiguration;
public CachingServiceCallServiceDiscoveryConfiguration() {
this(null);
}
public CachingServiceCallServiceDiscoveryConfiguration(ServiceCallDefinition parent) {
super(parent, "caching-service-discovery");
}
// *************************************************************************
// Properties
// *************************************************************************
public String getTimeout() {
return timeout;
}
/**
* Set the time the services will be retained.
*/
public void setTimeout(String timeout) {
this.timeout = timeout;
}
public String getUnits() {
return units;
}
/**
* Set the time unit for the timeout.
*/
public void setUnits(String units) {
this.units = units;
}
public ServiceCallServiceDiscoveryConfiguration getServiceDiscoveryConfiguration() {
return serviceDiscoveryConfiguration;
}
/**
* Set the service-call configuration to use
*/
public void setServiceDiscoveryConfiguration(ServiceCallServiceDiscoveryConfiguration serviceDiscoveryConfiguration) {
this.serviceDiscoveryConfiguration = serviceDiscoveryConfiguration;
}
// *************************************************************************
// Fluent API
// *************************************************************************
/**
* Set the time the services will be retained.
*/
public CachingServiceCallServiceDiscoveryConfiguration timeout(int timeout) {
return timeout(Integer.toString(timeout));
}
/**
* Set the time the services will be retained.
*/
public CachingServiceCallServiceDiscoveryConfiguration timeout(String timeout) {
setTimeout(timeout);
return this;
}
/**
* Set the time unit for the timeout.
*/
public CachingServiceCallServiceDiscoveryConfiguration units(TimeUnit units) {
return units(units.name());
}
/**
* Set the time unit for the timeout.
*/
public CachingServiceCallServiceDiscoveryConfiguration units(String units) {
setUnits(units);
return this;
}
/**
* Set the service-call configuration to use
*/
public CachingServiceCallServiceDiscoveryConfiguration serviceDiscoveryConfiguration(
ServiceCallServiceDiscoveryConfiguration serviceDiscoveryConfiguration) {
setServiceDiscoveryConfiguration(serviceDiscoveryConfiguration);
return this;
}
// *****************************
// Shortcuts - ServiceDiscovery
// *****************************
public CachingServiceCallServiceDiscoveryConfiguration cachingServiceDiscovery() {
CachingServiceCallServiceDiscoveryConfiguration conf = new CachingServiceCallServiceDiscoveryConfiguration();
setServiceDiscoveryConfiguration(conf);
return serviceDiscoveryConfiguration(conf);
}
public ConsulServiceCallServiceDiscoveryConfiguration consulServiceDiscovery() {
ConsulServiceCallServiceDiscoveryConfiguration conf = new ConsulServiceCallServiceDiscoveryConfiguration();
setServiceDiscoveryConfiguration(conf);
return conf;
}
public DnsServiceCallServiceDiscoveryConfiguration dnsServiceDiscovery() {
DnsServiceCallServiceDiscoveryConfiguration conf = new DnsServiceCallServiceDiscoveryConfiguration();
setServiceDiscoveryConfiguration(conf);
return conf;
}
public KubernetesServiceCallServiceDiscoveryConfiguration kubernetesServiceDiscovery() {
KubernetesServiceCallServiceDiscoveryConfiguration conf = new KubernetesServiceCallServiceDiscoveryConfiguration();
setServiceDiscoveryConfiguration(conf);
return conf;
}
public CombinedServiceCallServiceDiscoveryConfiguration combinedServiceDiscovery() {
CombinedServiceCallServiceDiscoveryConfiguration conf = new CombinedServiceCallServiceDiscoveryConfiguration();
setServiceDiscoveryConfiguration(conf);
return conf;
}
public StaticServiceCallServiceDiscoveryConfiguration staticServiceDiscovery() {
StaticServiceCallServiceDiscoveryConfiguration conf = new StaticServiceCallServiceDiscoveryConfiguration();
setServiceDiscoveryConfiguration(conf);
return conf;
}
// *************************************************************************
// Utilities
// *************************************************************************
@Override
protected void postProcessFactoryParameters(CamelContext camelContext, Map<String, Object> parameters) throws Exception {
if (serviceDiscoveryConfiguration != null) {
parameters.put("serviceDiscovery", serviceDiscoveryConfiguration.newInstance(camelContext));
}
}
}
| CachingServiceCallServiceDiscoveryConfiguration |
java | apache__flink | flink-table/flink-sql-parser/src/main/java/org/apache/flink/sql/parser/utils/ParserResource.java | {
"start": 1021,
"end": 3528
} | interface ____ {
/** Resources. */
ParserResource RESOURCE = Resources.create(ParserResource.class);
@Resources.BaseMessage("Multiple WATERMARK statements is not supported yet.")
Resources.ExInst<ParseException> multipleWatermarksUnsupported();
@Resources.BaseMessage("OVERWRITE expression is only used with INSERT statement.")
Resources.ExInst<ParseException> overwriteIsOnlyUsedWithInsert();
@Resources.BaseMessage(
"CREATE SYSTEM FUNCTION is not supported, system functions can only be registered as temporary function, you can use CREATE TEMPORARY SYSTEM FUNCTION instead.")
Resources.ExInst<ParseException> createSystemFunctionOnlySupportTemporary();
@Resources.BaseMessage("Duplicate EXPLAIN DETAIL is not allowed.")
Resources.ExInst<ParseException> explainDetailIsDuplicate();
@Resources.BaseMessage(
"Unsupported CREATE OR REPLACE statement for EXPLAIN. The statement must define a query using the AS clause (i.e. CTAS/RTAS statements).")
Resources.ExInst<ParseException> explainCreateOrReplaceStatementUnsupported();
@Resources.BaseMessage(
"Columns identifiers without types in the schema are supported on CTAS/RTAS statements only.")
Resources.ExInst<ParseException> columnsIdentifiersUnsupported();
@Resources.BaseMessage("CREATE FUNCTION USING JAR syntax is not applicable to {0} language.")
Resources.ExInst<ParseException> createFunctionUsingJar(String language);
@Resources.BaseMessage("WITH DRAIN could only be used after WITH SAVEPOINT.")
Resources.ExInst<ParseException> withDrainOnlyUsedWithSavepoint();
@Resources.BaseMessage("Bucket count must be a positive integer.")
Resources.ExInst<ParseException> bucketCountMustBePositiveInteger();
@Resources.BaseMessage(
"MATERIALIZED TABLE only supports define interval type FRESHNESS, please refer to the materialized table document.")
Resources.ExInst<ParseException> unsupportedFreshnessType();
@Resources.BaseMessage("CREATE TEMPORARY MATERIALIZED TABLE is not supported.")
Resources.ExInst<ParseException> createTemporaryMaterializedTableUnsupported();
@Resources.BaseMessage("REPLACE MATERIALIZED TABLE is not supported.")
Resources.ExInst<ParseException> replaceMaterializedTableUnsupported();
@Resources.BaseMessage("DROP TEMPORARY MATERIALIZED TABLE is not supported.")
Resources.ExInst<ParseException> dropTemporaryMaterializedTableUnsupported();
}
| ParserResource |
java | spring-projects__spring-boot | module/spring-boot-rsocket/src/main/java/org/springframework/boot/rsocket/autoconfigure/RSocketServerAutoConfiguration.java | {
"start": 3740,
"end": 3879
} | class ____ {
@Conditional(OnRSocketWebServerCondition.class)
@Configuration(proxyBeanMethods = false)
static | RSocketServerAutoConfiguration |
java | apache__camel | components/camel-opensearch/src/main/java/org/apache/camel/component/opensearch/OpensearchEndpoint.java | {
"start": 1537,
"end": 2658
} | class ____ extends DefaultEndpoint implements EndpointServiceLocation {
@UriParam
private final OpensearchConfiguration configuration;
private final RestClient client;
public OpensearchEndpoint(String uri, OpensearchComponent component, OpensearchConfiguration config,
RestClient client) {
super(uri, component);
this.configuration = config;
this.client = client;
}
public OpensearchConfiguration getConfiguration() {
return configuration;
}
@Override
public Producer createProducer() {
return new OpensearchProducer(this, configuration);
}
@Override
public Consumer createConsumer(Processor processor) {
throw new UnsupportedOperationException("Cannot consume from an OpenSearch: " + getEndpointUri());
}
public RestClient getClient() {
return client;
}
@Override
public String getServiceUrl() {
return configuration.getHostAddresses();
}
@Override
public String getServiceProtocol() {
return "opensearch";
}
}
| OpensearchEndpoint |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/jls/JLS_15_12_2_5Test.java | {
"start": 805,
"end": 1895
} | class ____ {
/**
* The JLS §15.12.2.5 states that the compiler must chose the most specific overload in Java 6 or Java 7,
* but with generics in the matcher, <strong>javac</strong> selects the upper bound, which is {@code Object},
* as such javac selects the most generic method.
*
* https://docs.oracle.com/javase/specs/jls/se6/html/expressions.html#15.12.2.5
* https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.5
*
* <blockquote>
* <p>If more than one member method is both accessible and applicable to a method invocation, it is necessary to
* choose one to provide the descriptor for the run-time method dispatch. The Java programming language uses
* the rule that the most specific method is chosen.</p>
*
* <p>The informal intuition is that one method is more specific than another if any invocation handled by
* the first method could be passed on to the other one without a compile-time type error.</p>
* </blockquote>
*/
public static | JLS_15_12_2_5Test |
java | apache__spark | common/network-common/src/test/java/org/apache/spark/network/StreamSuite.java | {
"start": 5461,
"end": 7883
} | class ____ implements Runnable {
private final TransportClient client;
private final String streamId;
private final long timeoutMs;
private Throwable error;
StreamTask(TransportClient client, String streamId, long timeoutMs) {
this.client = client;
this.streamId = streamId;
this.timeoutMs = timeoutMs;
}
@Override
public void run() {
ByteBuffer srcBuffer = null;
OutputStream out = null;
File outFile = null;
try {
ByteArrayOutputStream baos = null;
switch (streamId) {
case "largeBuffer" -> {
baos = new ByteArrayOutputStream();
out = baos;
srcBuffer = testData.largeBuffer;
}
case "smallBuffer" -> {
baos = new ByteArrayOutputStream();
out = baos;
srcBuffer = testData.smallBuffer;
}
case "file" -> {
outFile = File.createTempFile("data", ".tmp", testData.tempDir);
out = new FileOutputStream(outFile);
}
case "emptyBuffer" -> {
baos = new ByteArrayOutputStream();
out = baos;
srcBuffer = testData.emptyBuffer;
}
default -> throw new IllegalArgumentException(streamId);
}
TestCallback callback = new TestCallback(out);
client.stream(streamId, callback);
callback.waitForCompletion(timeoutMs);
if (srcBuffer == null) {
assertTrue(JavaUtils.contentEquals(testData.testFile, outFile),
"File stream did not match.");
} else {
ByteBuffer base;
synchronized (srcBuffer) {
base = srcBuffer.duplicate();
}
byte[] result = baos.toByteArray();
byte[] expected = new byte[base.remaining()];
base.get(expected);
assertEquals(expected.length, result.length);
assertArrayEquals(expected, result, "buffers don't match");
}
} catch (Throwable t) {
error = t;
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
// ignore.
}
}
if (outFile != null) {
outFile.delete();
}
}
}
public void check() throws Throwable {
if (error != null) {
throw error;
}
}
}
static | StreamTask |
java | apache__kafka | clients/src/main/java/org/apache/kafka/clients/consumer/ConsumerRebalanceListener.java | {
"start": 6905,
"end": 8027
} | class ____ implements ConsumerRebalanceListener {
* private Consumer<?,?> consumer;
*
* public SaveOffsetsOnRebalance(Consumer<?,?> consumer) {
* this.consumer = consumer;
* }
*
* public void onPartitionsRevoked(Collection<TopicPartition> partitions) {
* // save the offsets in an external store using some custom code not described here
* for(TopicPartition partition: partitions)
* saveOffsetInExternalStore(consumer.position(partition));
* }
*
* public void onPartitionsLost(Collection<TopicPartition> partitions) {
* // do not need to save the offsets since these partitions are probably owned by other consumers already
* }
*
* public void onPartitionsAssigned(Collection<TopicPartition> partitions) {
* // read the offsets from an external store using some custom code not described here
* for(TopicPartition partition: partitions)
* consumer.seek(partition, readOffsetFromExternalStore(partition));
* }
* }
* }
* </pre>
*/
public | SaveOffsetsOnRebalance |
java | apache__camel | core/camel-main/src/test/java/org/apache/camel/main/MainBeansClassStaticFactoryMethodTest.java | {
"start": 2214,
"end": 2400
} | class ____ extends RouteBuilder {
@Override
public void configure() {
from("direct:start").to("mock:foo");
}
}
public static final | MyRouteBuilder |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/subjects/SingleSubject.java | {
"start": 4891,
"end": 10344
} | class ____<T> extends Single<T> implements SingleObserver<T> {
final AtomicReference<SingleDisposable<T>[]> observers;
@SuppressWarnings("rawtypes")
static final SingleDisposable[] EMPTY = new SingleDisposable[0];
@SuppressWarnings("rawtypes")
static final SingleDisposable[] TERMINATED = new SingleDisposable[0];
final AtomicBoolean once;
T value;
Throwable error;
/**
* Creates a fresh SingleSubject.
* @param <T> the value type received and emitted
* @return the new SingleSubject instance
*/
@CheckReturnValue
@NonNull
public static <T> SingleSubject<T> create() {
return new SingleSubject<>();
}
@SuppressWarnings("unchecked")
SingleSubject() {
once = new AtomicBoolean();
observers = new AtomicReference<>(EMPTY);
}
@Override
public void onSubscribe(@NonNull Disposable d) {
if (observers.get() == TERMINATED) {
d.dispose();
}
}
@SuppressWarnings("unchecked")
@Override
public void onSuccess(@NonNull T value) {
ExceptionHelper.nullCheck(value, "onSuccess called with a null value.");
if (once.compareAndSet(false, true)) {
this.value = value;
for (SingleDisposable<T> md : observers.getAndSet(TERMINATED)) {
md.downstream.onSuccess(value);
}
}
}
@SuppressWarnings("unchecked")
@Override
public void onError(@NonNull Throwable e) {
ExceptionHelper.nullCheck(e, "onError called with a null Throwable.");
if (once.compareAndSet(false, true)) {
this.error = e;
for (SingleDisposable<T> md : observers.getAndSet(TERMINATED)) {
md.downstream.onError(e);
}
} else {
RxJavaPlugins.onError(e);
}
}
@Override
protected void subscribeActual(@NonNull SingleObserver<? super T> observer) {
SingleDisposable<T> md = new SingleDisposable<>(observer, this);
observer.onSubscribe(md);
if (add(md)) {
if (md.isDisposed()) {
remove(md);
}
} else {
Throwable ex = error;
if (ex != null) {
observer.onError(ex);
} else {
observer.onSuccess(value);
}
}
}
boolean add(@NonNull SingleDisposable<T> inner) {
for (;;) {
SingleDisposable<T>[] a = observers.get();
if (a == TERMINATED) {
return false;
}
int n = a.length;
@SuppressWarnings("unchecked")
SingleDisposable<T>[] b = new SingleDisposable[n + 1];
System.arraycopy(a, 0, b, 0, n);
b[n] = inner;
if (observers.compareAndSet(a, b)) {
return true;
}
}
}
@SuppressWarnings("unchecked")
void remove(@NonNull SingleDisposable<T> inner) {
for (;;) {
SingleDisposable<T>[] a = observers.get();
int n = a.length;
if (n == 0) {
return;
}
int j = -1;
for (int i = 0; i < n; i++) {
if (a[i] == inner) {
j = i;
break;
}
}
if (j < 0) {
return;
}
SingleDisposable<T>[] b;
if (n == 1) {
b = EMPTY;
} else {
b = new SingleDisposable[n - 1];
System.arraycopy(a, 0, b, 0, j);
System.arraycopy(a, j + 1, b, j, n - j - 1);
}
if (observers.compareAndSet(a, b)) {
return;
}
}
}
/**
* Returns the success value if this SingleSubject was terminated with a success value.
* @return the success value or null
*/
@Nullable
public T getValue() {
if (observers.get() == TERMINATED) {
return value;
}
return null;
}
/**
* Returns true if this SingleSubject was terminated with a success value.
* @return true if this SingleSubject was terminated with a success value
*/
public boolean hasValue() {
return observers.get() == TERMINATED && value != null;
}
/**
* Returns the terminal error if this SingleSubject has been terminated with an error, null otherwise.
* @return the terminal error or null if not terminated or not with an error
*/
@Nullable
public Throwable getThrowable() {
if (observers.get() == TERMINATED) {
return error;
}
return null;
}
/**
* Returns true if this SingleSubject has been terminated with an error.
* @return true if this SingleSubject has been terminated with an error
*/
public boolean hasThrowable() {
return observers.get() == TERMINATED && error != null;
}
/**
* Returns true if this SingleSubject has observers.
* @return true if this SingleSubject has observers
*/
public boolean hasObservers() {
return observers.get().length != 0;
}
/**
* Returns the number of current observers.
* @return the number of current observers
*/
/* test */ int observerCount() {
return observers.get().length;
}
static final | SingleSubject |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-api/src/main/java/org/apache/hadoop/yarn/exceptions/InvalidResourceRequestException.java | {
"start": 2556,
"end": 3462
} | enum ____ {
LESS_THAN_ZERO, GREATER_THEN_MAX_ALLOCATION, UNKNOWN;
}
private static final long serialVersionUID = 13498237L;
private final InvalidResourceType invalidResourceType;
public InvalidResourceRequestException(Throwable cause) {
super(cause);
this.invalidResourceType = InvalidResourceType.UNKNOWN;
}
public InvalidResourceRequestException(String message) {
this(message, InvalidResourceType.UNKNOWN);
}
public InvalidResourceRequestException(String message,
InvalidResourceType invalidResourceType) {
super(message);
this.invalidResourceType = invalidResourceType;
}
public InvalidResourceRequestException(String message, Throwable cause) {
super(message, cause);
this.invalidResourceType = InvalidResourceType.UNKNOWN;
}
public InvalidResourceType getInvalidResourceType() {
return invalidResourceType;
}
}
| InvalidResourceType |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authc/saml/SamlRealmSettings.java | {
"start": 15231,
"end": 17038
} | class ____ {
public static final String ATTRIBUTES_PREFIX = "attributes.";
public static final String ATTRIBUTE_PATTERNS_PREFIX = "attribute_patterns.";
private final Setting.AffixSetting<String> attribute;
private final Setting.AffixSetting<String> pattern;
public AttributeSetting(String type, String name) {
attribute = RealmSettings.simpleString(type, ATTRIBUTES_PREFIX + name, Setting.Property.NodeScope);
pattern = RealmSettings.simpleString(type, ATTRIBUTE_PATTERNS_PREFIX + name, Setting.Property.NodeScope);
}
public Collection<Setting.AffixSetting<?>> settings() {
return Arrays.asList(getAttribute(), getPattern());
}
public String name(RealmConfig config) {
return getAttribute().getConcreteSettingForNamespace(config.name()).getKey();
}
public Setting.AffixSetting<String> getAttribute() {
return attribute;
}
public Setting.AffixSetting<String> getPattern() {
return pattern;
}
}
/**
* The SAML realm offers a setting where a multivalued attribute can be configured to have a delimiter for its values, for the case
* when all values are provided in a single string item, separated by a delimiter.
* As in {@link AttributeSetting} there are two settings:
* <ul>
* <li>The name of the SAML attribute to use</li>
* <li>A delimiter to apply to that attribute value in order to extract the substrings that should be used.</li>
* </ul>
* For example, the Elasticsearch Group could be configured to come from the SAML "department" attribute, where all groups are provided
* as a csv value in a single list item.
*/
public static final | AttributeSetting |
java | apache__kafka | streams/src/test/java/org/apache/kafka/streams/state/internals/KeyValueStoreBuilderTest.java | {
"start": 1841,
"end": 6136
} | class ____ {
@Mock
private KeyValueBytesStoreSupplier supplier;
@Mock
private KeyValueStore<Bytes, byte[]> inner;
private KeyValueStoreBuilder<String, String> builder;
public void setUpWithoutInner() {
when(supplier.name()).thenReturn("name");
when(supplier.metricsScope()).thenReturn("metricScope");
builder = new KeyValueStoreBuilder<>(
supplier,
Serdes.String(),
Serdes.String(),
new MockTime()
);
}
public void setUp() {
when(supplier.get()).thenReturn(inner);
setUpWithoutInner();
}
@Test
public void shouldHaveMeteredStoreAsOuterStore() {
setUp();
final KeyValueStore<String, String> store = builder.build();
assertThat(store, instanceOf(MeteredKeyValueStore.class));
}
@Test
public void shouldHaveChangeLoggingStoreByDefault() {
setUp();
final KeyValueStore<String, String> store = builder.build();
assertThat(store, instanceOf(MeteredKeyValueStore.class));
final StateStore next = ((WrappedStateStore) store).wrapped();
assertThat(next, instanceOf(ChangeLoggingKeyValueBytesStore.class));
}
@Test
public void shouldNotHaveChangeLoggingStoreWhenDisabled() {
setUp();
final KeyValueStore<String, String> store = builder.withLoggingDisabled().build();
final StateStore next = ((WrappedStateStore) store).wrapped();
assertThat(next, CoreMatchers.equalTo(inner));
}
@Test
public void shouldHaveCachingStoreWhenEnabled() {
setUp();
final KeyValueStore<String, String> store = builder.withCachingEnabled().build();
final StateStore wrapped = ((WrappedStateStore) store).wrapped();
assertThat(store, instanceOf(MeteredKeyValueStore.class));
assertThat(wrapped, instanceOf(CachingKeyValueStore.class));
}
@Test
public void shouldHaveChangeLoggingStoreWhenLoggingEnabled() {
setUp();
final KeyValueStore<String, String> store = builder
.withLoggingEnabled(Collections.emptyMap())
.build();
final StateStore wrapped = ((WrappedStateStore) store).wrapped();
assertThat(store, instanceOf(MeteredKeyValueStore.class));
assertThat(wrapped, instanceOf(ChangeLoggingKeyValueBytesStore.class));
assertThat(((WrappedStateStore) wrapped).wrapped(), CoreMatchers.equalTo(inner));
}
@Test
public void shouldHaveCachingAndChangeLoggingWhenBothEnabled() {
setUp();
final KeyValueStore<String, String> store = builder
.withLoggingEnabled(Collections.emptyMap())
.withCachingEnabled()
.build();
final WrappedStateStore caching = (WrappedStateStore) ((WrappedStateStore) store).wrapped();
final WrappedStateStore changeLogging = (WrappedStateStore) caching.wrapped();
assertThat(store, instanceOf(MeteredKeyValueStore.class));
assertThat(caching, instanceOf(CachingKeyValueStore.class));
assertThat(changeLogging, instanceOf(ChangeLoggingKeyValueBytesStore.class));
assertThat(changeLogging.wrapped(), CoreMatchers.equalTo(inner));
}
@SuppressWarnings("all")
@Test
public void shouldThrowNullPointerIfInnerIsNull() {
setUpWithoutInner();
assertThrows(NullPointerException.class, () -> new KeyValueStoreBuilder<>(null, Serdes.String(),
Serdes.String(), new MockTime()));
}
@Test
public void shouldThrowNullPointerIfTimeIsNull() {
setUpWithoutInner();
assertThrows(NullPointerException.class, () -> new KeyValueStoreBuilder<>(supplier, Serdes.String(), Serdes.String(), null));
}
@Test
public void shouldThrowNullPointerIfMetricsScopeIsNull() {
setUpWithoutInner();
when(supplier.name()).thenReturn("name");
when(supplier.metricsScope()).thenReturn(null);
final Exception e = assertThrows(NullPointerException.class,
() -> new KeyValueStoreBuilder<>(supplier, Serdes.String(), Serdes.String(), new MockTime()));
assertThat(e.getMessage(), equalTo("storeSupplier's metricsScope can't be null"));
}
} | KeyValueStoreBuilderTest |
java | quarkusio__quarkus | integration-tests/redis-client/src/test/java/io/quarkus/redis/it/QuarkusRedisIT.java | {
"start": 108,
"end": 239
} | class ____ extends QuarkusRedisTest {
@Override
String getKey(String k) {
return "native-" + k;
}
}
| QuarkusRedisIT |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/cache/interceptor/CachePutOperation.java | {
"start": 871,
"end": 1340
} | class ____ extends CacheOperation {
private final @Nullable String unless;
/**
* Create a new {@link CachePutOperation} instance from the given builder.
* @since 4.3
*/
public CachePutOperation(CachePutOperation.Builder b) {
super(b);
this.unless = b.unless;
}
public @Nullable String getUnless() {
return this.unless;
}
/**
* A builder that can be used to create a {@link CachePutOperation}.
* @since 4.3
*/
public static | CachePutOperation |
java | elastic__elasticsearch | x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/RestSqlAsyncDeleteResultsAction.java | {
"start": 1020,
"end": 1666
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(new Route(DELETE, SQL_ASYNC_DELETE_REST_ENDPOINT + "{" + ID_NAME + "}"));
}
@Override
public String getName() {
return "sql_delete_async_result";
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) {
DeleteAsyncResultRequest delete = new DeleteAsyncResultRequest(request.param(ID_NAME));
return channel -> client.execute(TransportDeleteAsyncResultAction.TYPE, delete, new RestToXContentListener<>(channel));
}
}
| RestSqlAsyncDeleteResultsAction |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/validation/ClassBeanMultipleScopesTest.java | {
"start": 447,
"end": 850
} | class ____ {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder().beanClasses(Alpha.class).shouldFail().build();
@Test
public void testFailure() {
Throwable error = container.getFailure();
assertNotNull(error);
assertTrue(error instanceof DefinitionException);
}
@Singleton
@Dependent
static | ClassBeanMultipleScopesTest |
java | apache__camel | components/camel-groovy/src/test/java/org/apache/camel/processor/groovy/GroovyFilterTest.java | {
"start": 1156,
"end": 1949
} | class ____ extends CamelSpringTestSupport {
@Override
protected AbstractApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/processor/groovy/groovyFilter.xml");
}
@Test
public void testSendMatchingMessage() throws Exception {
getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
template.sendBodyAndHeader("direct:start", "Hello World", "foo", 123);
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testSendNotMatchingMessage() throws Exception {
getMockEndpoint("mock:result").expectedMessageCount(0);
template.sendBody("direct:start", "Bye World");
MockEndpoint.assertIsSatisfied(context);
}
}
| GroovyFilterTest |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/constants/CommonConstants.java | {
"start": 19533,
"end": 22071
} | interface ____ a point
* to point interface} that the Dubbo application will determine whether to ignore the point-to-point network
* interface
*
* @since 3.3
*/
String DUBBO_NETWORK_INTERFACE_POINT_TO_POINT_IGNORED = "dubbo.network.interface.point-to-point.ignored";
String DUBBO_CLASS_DESERIALIZE_ALLOWED_LIST = "dubbo.security.serialize.allowedClassList";
String DUBBO_CLASS_DESERIALIZE_BLOCKED_LIST = "dubbo.security.serialize.blockedClassList";
String DUBBO_CLASS_DESERIALIZE_OPEN_CHECK = "dubbo.security.serialize.openCheckClass";
String DUBBO_CLASS_DESERIALIZE_BLOCK_ALL = "dubbo.security.serialize.blockAllClassExceptAllow";
String DUBBO_RESOLVE_FILE = "dubbo.resolve.file";
String DUBBO_IP_TO_REGISTRY = "DUBBO_IP_TO_REGISTRY";
String DUBBO_MONITOR_ADDRESS = "dubbo.monitor.address";
String DUBBO_CONTAINER_KEY = "dubbo.container";
String DUBBO_SHUTDOWN_HOOK_KEY = "dubbo.shutdown.hook";
String DUBBO_SPRING_CONFIG = "dubbo.spring.config";
String DUBBO_MAPPING_CACHE_FILEPATH = "dubbo.mapping.cache.filePath";
String DUBBO_MAPPING_CACHE_FILENAME = "dubbo.mapping.cache.fileName";
String DUBBO_MAPPING_CACHE_ENTRYSIZE = "dubbo.mapping.cache.entrySize";
String DUBBO_MAPPING_CACHE_MAXFILESIZE = "dubbo.mapping.cache.maxFileSize";
String DUBBO_META_CACHE_FILEPATH = "dubbo.meta.cache.filePath";
String DUBBO_META_CACHE_FILENAME = "dubbo.meta.cache.fileName";
String DUBBO_META_CACHE_ENTRYSIZE = "dubbo.meta.cache.entrySize";
String DUBBO_META_CACHE_MAXFILESIZE = "dubbo.meta.cache.maxFileSize";
String DUBBO_USE_SECURE_RANDOM_ID = "dubbo.application.use-secure-random-request-id";
String DUBBO_CLOSE_TIMEOUT_CONFIG_KEY = "dubbo.protocol.default-close-timeout";
String DUBBO_HEARTBEAT_CONFIG_KEY = "dubbo.protocol.default-heartbeat";
String DUBBO_DEFAULT_REMOTING_SERIALIZATION_PROPERTY = "DUBBO_DEFAULT_SERIALIZATION";
String DUBBO_HESSIAN_ALLOW_NON_SERIALIZABLE = "dubbo.hessian.allowNonSerializable";
String DUBBO_HESSIAN_WHITELIST = "dubbo.application.hessian2.whitelist";
String DUBBO_HESSIAN_ALLOW = "dubbo.application.hessian2.allow";
String DUBBO_HESSIAN_DENY = "dubbo.application.hessian2.deny";
String DUBBO_MANUAL_REGISTER_KEY = "dubbo.application.manual-register";
String DUBBO2_COMPACT_ENABLE = "dubbo.compact.enable";
}
}
| is |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/security/oauthbearer/internals/expiring/ExpiringCredentialRefreshingLoginTest.java | {
"start": 7244,
"end": 9128
} | class ____ extends LoginContext {
private final TestExpiringCredentialRefreshingLogin testExpiringCredentialRefreshingLogin;
private final LoginContext mockLoginContext;
public TestLoginContext(TestExpiringCredentialRefreshingLogin testExpiringCredentialRefreshingLogin,
LoginContext mockLoginContext) throws LoginException {
super("contextName", null, null, EMPTY_WILDCARD_CONFIGURATION);
this.testExpiringCredentialRefreshingLogin = Objects.requireNonNull(testExpiringCredentialRefreshingLogin);
// sanity check to make sure it is likely a mock
if (!MockUtil.isMock(mockLoginContext))
throw new IllegalArgumentException();
this.mockLoginContext = mockLoginContext;
}
@Override
public void login() throws LoginException {
/*
* Here is where we get the functionality of a mock while simultaneously
* performing the creation of an expiring credential
*/
mockLoginContext.login();
testExpiringCredentialRefreshingLogin.createNewExpiringCredential();
}
@Override
public void logout() throws LoginException {
/*
* Here is where we get the functionality of a mock while simultaneously
* performing the removal of an expiring credential
*/
mockLoginContext.logout();
testExpiringCredentialRefreshingLogin.clearExpiringCredential();
}
@Override
public Subject getSubject() {
// here we just need the functionality of a mock
return mockLoginContext.getSubject();
}
}
/*
* An implementation of LoginContextFactory that returns an instance of
* TestLoginContext
*/
private static | TestLoginContext |
java | quarkusio__quarkus | extensions/vertx/deployment/src/test/java/io/quarkus/vertx/mdc/VerticleDeployer.java | {
"start": 1107,
"end": 2919
} | class ____ extends AbstractVerticle {
private static final Logger LOGGER = Logger.getLogger(TestVerticle.class);
@Override
public void start(Promise<Void> startPromise) {
WebClient webClient = WebClient.create(vertx);
var request = webClient.getAbs("http://localhost:" + VERTICLE_PORT + "/now");
Promise<HttpServer> httpServerPromise = Promise.promise();
httpServerPromise.future().<Void> mapEmpty().onComplete(startPromise);
vertx.createHttpServer()
.requestHandler(req -> {
if (req.path().equals("/now")) {
req.response().end(Long.toString(System.currentTimeMillis()));
return;
}
String requestId = req.getHeader(REQUEST_ID_HEADER);
MDC.put(MDC_KEY, requestId);
LOGGER.info("Received HTTP request ### " + MDC.get(MDC_KEY));
vertx.setTimer(50, l -> {
LOGGER.info("Timer fired ### " + MDC.get(MDC_KEY));
vertx.executeBlocking(() -> {
LOGGER.info("Blocking task executed ### " + MDC.get(MDC_KEY));
return null;
}, false).onComplete(bar -> request.send(rar -> {
String value = (String) MDC.get(MDC_KEY);
LOGGER.info("Received Web Client response ### " + value);
req.response().end(value);
}));
});
})
.listen(VERTICLE_PORT, httpServerPromise);
}
}
}
| TestVerticle |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/RObjectReactive.java | {
"start": 854,
"end": 7261
} | interface ____ {
/**
* Returns number of seconds spent since last write or read operation over this object.
*
* @return number of seconds
*/
Mono<Long> getIdleTime();
/**
* Returns count of references over this object.
*
* @return count of reference
*/
Mono<Integer> getReferenceCount();
/**
* Returns the logarithmic access frequency counter over this object.
*
* @return frequency counter
*/
Mono<Integer> getAccessFrequency();
/**
* Returns the internal encoding for the Redis object
*
* @return internal encoding
*/
Mono<ObjectEncoding> getInternalEncoding();
String getName();
Codec getCodec();
/**
* Returns bytes amount used by object in Redis memory.
*
* @return size in bytes
*/
Mono<Long> sizeInMemory();
/**
* Restores object using its state returned by {@link #dump()} method.
*
* @param state - state of object
* @return void
*/
Mono<Void> restore(byte[] state);
/**
* Restores object using its state returned by {@link #dump()} method and set time to live for it.
*
* @param state - state of object
* @param timeToLive - time to live of the object
* @param timeUnit - time unit
* @return void
*/
Mono<Void> restore(byte[] state, long timeToLive, TimeUnit timeUnit);
/**
* Restores and replaces object if it already exists.
*
* @param state - state of the object
* @return void
*/
Mono<Void> restoreAndReplace(byte[] state);
/**
* Restores and replaces object if it already exists and set time to live for it.
*
* @param state - state of the object
* @param timeToLive - time to live of the object
* @param timeUnit - time unit
* @return void
*/
Mono<Void> restoreAndReplace(byte[] state, long timeToLive, TimeUnit timeUnit);
/**
* Returns dump of object
*
* @return dump
*/
Mono<byte[]> dump();
/**
* Update the last access time of an object.
*
* @return <code>true</code> if object was touched else <code>false</code>
*/
Mono<Boolean> touch();
/**
* Delete the objects.
* Actual removal will happen later asynchronously.
* <p>
* Requires Redis 4.0+
*
* @return <code>true</code> if it was exist and deleted else <code>false</code>
*/
Mono<Boolean> unlink();
/**
* Copy object from source Redis instance to destination Redis instance
*
* @param host - destination host
* @param port - destination port
* @param database - destination database
* @param timeout - maximum idle time in any moment of the communication with the destination instance in milliseconds
* @return void
*/
Mono<Void> copy(String host, int port, int database, long timeout);
/**
* Copy this object instance to the new instance with a defined name.
*
* @param destination name of the destination instance
* @return <code>true</code> if this object instance was copied else <code>false</code>
*/
Mono<Boolean> copy(String destination);
/**
* Copy this object instance to the new instance with a defined name and database.
*
* @param destination name of the destination instance
* @param database database number
* @return <code>true</code> if this object instance was copied else <code>false</code>
*/
Mono<Boolean> copy(String destination, int database);
/**
* Copy this object instance to the new instance with a defined name, and replace it if it already exists.
*
* @param destination name of the destination instance
* @return <code>true</code> if this object instance was copied else <code>false</code>
*/
Mono<Boolean> copyAndReplace(String destination);
/**
* Copy this object instance to the new instance with a defined name and database, and replace it if it already exists.
*
* @param destination name of the destination instance
* @param database database number
* @return <code>true</code> if this object instance was copied else <code>false</code>
*/
Mono<Boolean> copyAndReplace(String destination, int database);
/**
* Transfer a object from a source Redis instance to a destination Redis instance
* in mode
*
* @param host - destination host
* @param port - destination port
* @param database - destination database
* @param timeout - maximum idle time in any moment of the communication with the destination instance in milliseconds
* @return void
*/
Mono<Void> migrate(String host, int port, int database, long timeout);
/**
* Move object to another database in mode
*
* @param database - number of Redis database
* @return <code>true</code> if key was moved <code>false</code> if not
*/
Mono<Boolean> move(int database);
/**
* Delete object in mode
*
* @return <code>true</code> if object was deleted <code>false</code> if not
*/
Mono<Boolean> delete();
/**
* Rename current object key to <code>newName</code>
* in mode
*
* @param newName - new name of object
* @return void
*/
Mono<Void> rename(String newName);
/**
* Rename current object key to <code>newName</code>
* in mode only if new key is not exists
*
* @param newName - new name of object
* @return <code>true</code> if object has been renamed successfully and <code>false</code> otherwise
*/
Mono<Boolean> renamenx(String newName);
/**
* Check object existence
*
* @return <code>true</code> if object exists and <code>false</code> otherwise
*/
Mono<Boolean> isExists();
/**
* Adds object event listener
*
* @see org.redisson.api.ExpiredObjectListener
* @see org.redisson.api.DeletedObjectListener
*
* @param listener - object event listener
* @return listener id
*/
Mono<Integer> addListener(ObjectListener listener);
/**
* Removes object event listener
*
* @param listenerId - listener id
* @return void
*/
Mono<Void> removeListener(int listenerId);
}
| RObjectReactive |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/codec/vectors/es93/ES93HnswBinaryQuantizedVectorsFormatTests.java | {
"start": 1789,
"end": 5182
} | class ____ extends BaseHnswVectorsFormatTestCase {
@Override
protected KnnVectorsFormat createFormat() {
return new ES93HnswBinaryQuantizedVectorsFormat(DenseVectorFieldMapper.ElementType.FLOAT, random().nextBoolean());
}
@Override
protected KnnVectorsFormat createFormat(int maxConn, int beamWidth) {
return new ES93HnswBinaryQuantizedVectorsFormat(
maxConn,
beamWidth,
DenseVectorFieldMapper.ElementType.FLOAT,
random().nextBoolean()
);
}
@Override
protected KnnVectorsFormat createFormat(int maxConn, int beamWidth, int numMergeWorkers, ExecutorService service) {
return new ES93HnswBinaryQuantizedVectorsFormat(
maxConn,
beamWidth,
DenseVectorFieldMapper.ElementType.FLOAT,
random().nextBoolean(),
numMergeWorkers,
service
);
}
public void testToString() {
String expected = "ES93HnswBinaryQuantizedVectorsFormat("
+ "name=ES93HnswBinaryQuantizedVectorsFormat, maxConn=10, beamWidth=20, flatVectorFormat=%s)";
expected = format(
Locale.ROOT,
expected,
"ES93BinaryQuantizedVectorsFormat(name=ES93BinaryQuantizedVectorsFormat, rawVectorFormat=%s,"
+ " scorer=ES818BinaryFlatVectorsScorer(nonQuantizedDelegate={}()))"
);
expected = format(Locale.ROOT, expected, "ES93GenericFlatVectorsFormat(name=ES93GenericFlatVectorsFormat, format=%s)");
expected = format(Locale.ROOT, expected, "Lucene99FlatVectorsFormat(name=Lucene99FlatVectorsFormat, flatVectorScorer={}())");
String defaultScorer = expected.replaceAll("\\{}", "DefaultFlatVectorScorer");
String memSegScorer = expected.replaceAll("\\{}", "Lucene99MemorySegmentFlatVectorsScorer");
KnnVectorsFormat format = createFormat(10, 20, 1, null);
assertThat(format, hasToString(oneOf(defaultScorer, memSegScorer)));
}
public void testSimpleOffHeapSize() throws IOException {
try (Directory dir = newDirectory()) {
testSimpleOffHeapSizeImpl(dir, newIndexWriterConfig(), true);
}
}
public void testSimpleOffHeapSizeMMapDir() throws IOException {
try (Directory dir = newMMapDirectory()) {
testSimpleOffHeapSizeImpl(dir, newIndexWriterConfig(), true);
}
}
public void testSimpleOffHeapSizeImpl(Directory dir, IndexWriterConfig config, boolean expectVecOffHeap) throws IOException {
float[] vector = randomVector(random().nextInt(12, 500));
var matcher = expectVecOffHeap
? allOf(
aMapWithSize(3),
hasEntry("vex", 1L),
hasEntry(equalTo("veb"), greaterThan(0L)),
hasEntry("vec", (long) vector.length * Float.BYTES)
)
: allOf(aMapWithSize(2), hasEntry("vex", 1L), hasEntry(equalTo("veb"), greaterThan(0L)));
testSimpleOffHeapSize(dir, config, vector, matcher);
}
static Directory newMMapDirectory() throws IOException {
Directory dir = new MMapDirectory(createTempDir("ES93BinaryQuantizedVectorsFormatTests"));
if (random().nextBoolean()) {
dir = new MockDirectoryWrapper(random(), dir);
}
return dir;
}
}
| ES93HnswBinaryQuantizedVectorsFormatTests |
java | spring-projects__spring-boot | core/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/AutoConfiguration.java | {
"start": 2438,
"end": 2757
} | interface ____ {
/**
* Explicitly specify the name of the Spring bean definition associated with the
* {@code @AutoConfiguration} class. If left unspecified (the common case), a bean
* name will be automatically generated.
* <p>
* The custom name applies only if the {@code @AutoConfiguration} | AutoConfiguration |
java | spring-projects__spring-boot | core/spring-boot-testcontainers/src/dockerTest/java/org/springframework/boot/testcontainers/lifecycle/TestcontainersLifecycleOrderWithScopeIntegrationTests.java | {
"start": 4510,
"end": 4995
} | class ____ extends AnnotationConfigContextLoader {
@Override
protected GenericApplicationContext createContext() {
CustomScope customScope = new CustomScope();
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext() {
@Override
protected void onClose() {
customScope.destroy();
super.onClose();
}
};
context.getBeanFactory().registerScope("custom", customScope);
return context;
}
}
static | ScopedContextLoader |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/consumer/RemoteInputChannelTest.java | {
"start": 5977,
"end": 12790
} | class ____ {
@RegisterExtension
private static final TestExecutorExtension<ScheduledExecutorService> EXECUTOR_EXTENSION =
TestingUtils.defaultExecutorExtension();
private static final long CHECKPOINT_ID = 1L;
private static final CheckpointOptions UNALIGNED =
CheckpointOptions.unaligned(CheckpointType.CHECKPOINT, getDefault());
private static final CheckpointOptions ALIGNED_WITH_TIMEOUT =
alignedWithTimeout(CheckpointType.CHECKPOINT, getDefault(), 10);
@Test
void testGateNotifiedOnBarrierConversion() throws IOException, InterruptedException {
final int sequenceNumber = 0;
final NetworkBufferPool networkBufferPool = new NetworkBufferPool(1, 4096);
try {
SingleInputGate inputGate =
new SingleInputGateBuilder()
.setBufferPoolFactory(networkBufferPool.createBufferPool(1, 1))
.build();
inputGate.setup();
RemoteInputChannel channel =
InputChannelBuilder.newBuilder()
.setConnectionManager(
new TestVerifyConnectionManager(
new TestVerifyPartitionRequestClient()))
.buildRemoteChannel(inputGate);
channel.requestSubpartitions();
channel.onBuffer(
toBuffer(
new CheckpointBarrier(
1L,
123L,
alignedWithTimeout(
CheckpointType.CHECKPOINT,
getDefault(),
Integer.MAX_VALUE)),
false),
sequenceNumber,
0,
0);
inputGate.pollNext(); // process announcement to allow the gate remember the SQN
channel.convertToPriorityEvent(sequenceNumber);
assertThat(inputGate.getPriorityEventAvailableFuture()).isDone();
} finally {
networkBufferPool.destroy();
}
}
@Test
void testExceptionOnReordering() throws Exception {
// Setup
final SingleInputGate inputGate = createSingleInputGate(1);
final RemoteInputChannel inputChannel = createRemoteInputChannel(inputGate);
final Buffer buffer = createBuffer(TestBufferFactory.BUFFER_SIZE);
// The test
inputChannel.onBuffer(buffer.retainBuffer(), 0, -1, 0);
// This does not yet throw the exception, but sets the error at the channel.
inputChannel.onBuffer(buffer, 29, -1, 0);
assertThatThrownBy(inputChannel::getNextBuffer)
.withFailMessage(
"Did not throw expected exception after enqueuing an out-of-order buffer.");
assertThat(buffer.isRecycled()).isFalse();
// free remaining buffer instances
inputChannel.releaseAllResources();
assertThat(buffer.isRecycled()).isTrue();
}
@Test
void testExceptionOnPersisting() throws Exception {
// Setup
final SingleInputGate inputGate = createSingleInputGate(1);
final RemoteInputChannel inputChannel =
InputChannelBuilder.newBuilder()
.setStateWriter(
new ChannelStateWriter.NoOpChannelStateWriter() {
@Override
public void addInputData(
long checkpointId,
InputChannelInfo info,
int startSeqNum,
CloseableIterator<Buffer> data) {
try {
data.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
throw new ExpectedTestException();
}
})
.buildRemoteChannel(inputGate);
inputChannel.checkpointStarted(
new CheckpointBarrier(
42,
System.currentTimeMillis(),
CheckpointOptions.unaligned(CheckpointType.CHECKPOINT, getDefault())));
final Buffer buffer = createBuffer(TestBufferFactory.BUFFER_SIZE);
assertThat(buffer.isRecycled()).isFalse();
assertThatThrownBy(() -> inputChannel.onBuffer(buffer, 0, -1, 0))
.isInstanceOf(ExpectedTestException.class);
// This check is not strictly speaking necessary. Generally speaking if exception happens
// during persisting, there are two potentially correct outcomes:
// 1. buffer is recycled only once, in #onBuffer call when handling exception
// 2. buffer is stored inside RemoteInputChannel and recycled on releaseAllResources.
// What's not acceptable is that it would be released twice, in both places. Without this
// check below, we would be just relaying on Buffer throwing IllegalReferenceCountException.
// I've added this check just to be sure. It's freezing the current implementation that's
// unlikely to change, on the other hand, thanks to it we don't need to relay on
// IllegalReferenceCountException being thrown from the Buffer.
//
// In other words, if you end up reading this after refactoring RemoteInputChannel, it might
// be safe to remove this assertion. Just make sure double recycling of the same buffer is
// still throwing IllegalReferenceCountException.
assertThat(buffer.isRecycled()).isFalse();
inputChannel.releaseAllResources();
assertThat(buffer.isRecycled()).isTrue();
}
@Test
void testConcurrentOnBufferAndRelease() throws Exception {
testConcurrentReleaseAndSomething(
8192,
(inputChannel, buffer, j) -> {
inputChannel.onBuffer(buffer, j, -1, 0);
return true;
});
}
@Test
void testConcurrentNotifyBufferAvailableAndRelease() throws Exception {
testConcurrentReleaseAndSomething(
1024,
(inputChannel, buffer, j) ->
inputChannel.getBufferManager().notifyBufferAvailable(buffer));
}
private | RemoteInputChannelTest |
java | spring-projects__spring-security | oauth2/oauth2-client/src/main/java/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.java | {
"start": 20843,
"end": 27954
} | class ____ implements ClientResponseHandler {
/**
* A map of HTTP Status Code to OAuth 2.0 Error codes for HTTP status codes that
* should be interpreted as authentication or authorization failures.
*/
private final Map<HttpStatusCode, String> httpStatusToOAuth2ErrorCodeMap;
/**
* The {@link ReactiveOAuth2AuthorizationFailureHandler} to notify when an
* authentication/authorization failure occurs.
*/
private final ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler;
private AuthorizationFailureForwarder(ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler) {
Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null");
this.authorizationFailureHandler = authorizationFailureHandler;
Map<HttpStatusCode, String> httpStatusToOAuth2Error = new HashMap<>();
httpStatusToOAuth2Error.put(HttpStatus.UNAUTHORIZED, OAuth2ErrorCodes.INVALID_TOKEN);
httpStatusToOAuth2Error.put(HttpStatus.FORBIDDEN, OAuth2ErrorCodes.INSUFFICIENT_SCOPE);
this.httpStatusToOAuth2ErrorCodeMap = Collections.unmodifiableMap(httpStatusToOAuth2Error);
}
@Override
public Mono<ClientResponse> handleResponse(ClientRequest request, Mono<ClientResponse> responseMono) {
// @formatter:off
return responseMono
.flatMap((response) -> handleResponse(request, response).thenReturn(response))
.onErrorResume(WebClientResponseException.class,
(e) -> handleWebClientResponseException(request, e).then(Mono.error(e))
)
.onErrorResume(OAuth2AuthorizationException.class,
(e) -> handleAuthorizationException(request, e).then(Mono.error(e)));
// @formatter:on
}
private Mono<Void> handleResponse(ClientRequest request, ClientResponse response) {
// @formatter:off
return Mono.justOrEmpty(resolveErrorIfPossible(response))
.flatMap((oauth2Error) -> {
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
Mono<String> clientRegistrationId = effectiveClientRegistrationId(request);
return Mono
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
serverWebExchange, clientRegistrationId)
.flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(),
new ClientAuthorizationException(oauth2Error, zipped.getT3())));
});
// @formatter:on
}
private OAuth2Error resolveErrorIfPossible(ClientResponse response) {
// Try to resolve from 'WWW-Authenticate' header
if (!response.headers().header(HttpHeaders.WWW_AUTHENTICATE).isEmpty()) {
String wwwAuthenticateHeader = response.headers().header(HttpHeaders.WWW_AUTHENTICATE).get(0);
Map<String, String> authParameters = parseAuthParameters(wwwAuthenticateHeader);
if (authParameters.containsKey(OAuth2ParameterNames.ERROR)) {
return new OAuth2Error(authParameters.get(OAuth2ParameterNames.ERROR),
authParameters.get(OAuth2ParameterNames.ERROR_DESCRIPTION),
authParameters.get(OAuth2ParameterNames.ERROR_URI));
}
}
return resolveErrorIfPossible(response.statusCode());
}
private OAuth2Error resolveErrorIfPossible(HttpStatusCode statusCode) {
if (this.httpStatusToOAuth2ErrorCodeMap.containsKey(statusCode)) {
return new OAuth2Error(this.httpStatusToOAuth2ErrorCodeMap.get(statusCode), null,
"https://tools.ietf.org/html/rfc6750#section-3.1");
}
return null;
}
private Map<String, String> parseAuthParameters(String wwwAuthenticateHeader) {
// @formatter:off
return Stream.of(wwwAuthenticateHeader)
.filter((header) -> StringUtils.hasLength(header))
.filter((header) -> header.toLowerCase(Locale.ENGLISH).startsWith("bearer"))
.map((header) -> header.substring("bearer".length()))
.map((header) -> header.split(","))
.flatMap(Stream::of)
.map((parameter) -> parameter.split("="))
.filter((parameter) -> parameter.length > 1)
.collect(Collectors.toMap((parameters) -> parameters[0].trim(),
(parameters) -> parameters[1].trim().replace("\"", ""))
);
// @formatter:on
}
/**
* Handles the given http status code returned from a resource server by notifying
* the authorization failure handler if the http status code is in the
* {@link #httpStatusToOAuth2ErrorCodeMap}.
* @param request the request being processed
* @param exception The root cause exception for the failure
* @return a {@link Mono} that completes empty after the authorization failure
* handler completes.
*/
private Mono<Void> handleWebClientResponseException(ClientRequest request,
WebClientResponseException exception) {
return Mono.justOrEmpty(resolveErrorIfPossible(exception.getStatusCode())).flatMap((oauth2Error) -> {
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
Mono<String> clientRegistrationId = effectiveClientRegistrationId(request);
return Mono
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
serverWebExchange, clientRegistrationId)
.flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(),
new ClientAuthorizationException(oauth2Error, zipped.getT3(), exception)));
});
}
/**
* Handles the given OAuth2AuthorizationException that occurred downstream by
* notifying the authorization failure handler.
* @param request the request being processed
* @param exception the authorization exception to include in the failure event.
* @return a {@link Mono} that completes empty after the authorization failure
* handler completes.
*/
private Mono<Void> handleAuthorizationException(ClientRequest request, OAuth2AuthorizationException exception) {
Mono<Optional<ServerWebExchange>> serverWebExchange = effectiveServerWebExchange(request);
return Mono
.zip(ServerOAuth2AuthorizedClientExchangeFilterFunction.this.currentAuthenticationMono,
serverWebExchange)
.flatMap((zipped) -> handleAuthorizationFailure(zipped.getT1(), zipped.getT2(), exception));
}
/**
* Delegates to the authorization failure handler of the failed authorization.
* @param principal the principal associated with the failed authorization attempt
* @param exchange the currently active exchange
* @param exception the authorization exception to include in the failure event.
* @return a {@link Mono} that completes empty after the authorization failure
* handler completes.
*/
private Mono<Void> handleAuthorizationFailure(Authentication principal, Optional<ServerWebExchange> exchange,
OAuth2AuthorizationException exception) {
return this.authorizationFailureHandler.onAuthorizationFailure(exception, principal,
createAttributes(exchange.orElse(null)));
}
private Map<String, Object> createAttributes(ServerWebExchange exchange) {
if (exchange == null) {
return Collections.emptyMap();
}
return Collections.singletonMap(ServerWebExchange.class.getName(), exchange);
}
}
}
| AuthorizationFailureForwarder |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/jndi/JndiContext.java | {
"start": 13196,
"end": 13778
} | class ____ implements NamingEnumeration<Object> {
private final Iterator<Map.Entry<String, Object>> i = bindings.entrySet().iterator();
@Override
public boolean hasMore() throws NamingException {
return i.hasNext();
}
@Override
public boolean hasMoreElements() {
return i.hasNext();
}
protected Map.Entry<String, Object> getNext() {
return i.next();
}
@Override
public void close() throws NamingException {
}
}
private | LocalNamingEnumeration |
java | quarkusio__quarkus | integration-tests/gradle/src/test/java/io/quarkus/gradle/devmode/MultiModuleKotlinProjectDevModeTest.java | {
"start": 193,
"end": 1063
} | class ____ extends QuarkusDevGradleTestBase {
@Override
protected String projectDirectoryName() {
return "multi-module-kotlin-project";
}
@Override
protected String[] buildArguments() {
return new String[] { "clean", ":web:quarkusDev" };
}
protected void testDevMode() throws Exception {
assertThat(getHttpResponse())
.contains("ready")
.contains("quarkusmm")
.contains("org.acme")
.contains("1.0.0-SNAPSHOT");
assertThat(getHttpResponse("/hello")).contains("howdy");
replace("domain/src/main/kotlin/com/example/quarkusmm/domain/CustomerServiceImpl.kt",
ImmutableMap.of("return \"howdy\"", "return \"modified\""));
assertUpdatedResponseContains("/hello", "modified");
}
}
| MultiModuleKotlinProjectDevModeTest |
java | apache__camel | components/camel-sql/src/main/java/org/apache/camel/processor/idempotent/jdbc/JdbcMessageIdRepository.java | {
"start": 1490,
"end": 8845
} | class ____ extends AbstractJdbcMessageIdRepository {
protected static final String DEFAULT_TABLENAME = "CAMEL_MESSAGEPROCESSED";
protected static final String DEFAULT_TABLE_EXISTS_STRING = "SELECT 1 FROM CAMEL_MESSAGEPROCESSED WHERE 1 = 0";
protected static final String DEFAULT_CREATE_STRING
= "CREATE TABLE CAMEL_MESSAGEPROCESSED (processorName VARCHAR(255), messageId VARCHAR(100), "
+ "createdAt TIMESTAMP, PRIMARY KEY (processorName, messageId))";
protected static final String DEFAULT_QUERY_STRING
= "SELECT COUNT(*) FROM CAMEL_MESSAGEPROCESSED WHERE processorName = ? AND messageId = ?";
protected static final String DEFAULT_INSERT_STRING
= "INSERT INTO CAMEL_MESSAGEPROCESSED (processorName, messageId, createdAt) VALUES (?, ?, ?)";
protected static final String DEFAULT_DELETE_STRING
= "DELETE FROM CAMEL_MESSAGEPROCESSED WHERE processorName = ? AND messageId = ?";
protected static final String DEFAULT_CLEAR_STRING = "DELETE FROM CAMEL_MESSAGEPROCESSED WHERE processorName = ?";
@Metadata(description = "The name of the table to use in the database", defaultValue = "CAMEL_MESSAGEPROCESSED")
private String tableName;
@Metadata(description = "Whether to create the table in the database if none exists on startup", defaultValue = "true")
private boolean createTableIfNotExists = true;
@Metadata(label = "advanced", description = "SQL query to use for checking if table exists")
private String tableExistsString = DEFAULT_TABLE_EXISTS_STRING;
@Metadata(label = "advanced", description = "SQL query to use for creating table")
private String createString = DEFAULT_CREATE_STRING;
@Metadata(label = "advanced", description = "SQL query to use for check if message id already exists")
private String queryString = DEFAULT_QUERY_STRING;
@Metadata(label = "advanced", description = "SQL query to use for inserting a new message id in the table")
private String insertString = DEFAULT_INSERT_STRING;
@Metadata(label = "advanced", description = "SQL query to use for deleting message id from the table")
private String deleteString = DEFAULT_DELETE_STRING;
@Metadata(label = "advanced", description = "SQL query to delete all message ids from the table")
private String clearString = DEFAULT_CLEAR_STRING;
public JdbcMessageIdRepository() {
}
public JdbcMessageIdRepository(DataSource dataSource, String processorName) {
super(dataSource, processorName);
}
public JdbcMessageIdRepository(DataSource dataSource, TransactionTemplate transactionTemplate, String processorName) {
super(dataSource, transactionTemplate, processorName);
}
public JdbcMessageIdRepository(JdbcTemplate jdbcTemplate, TransactionTemplate transactionTemplate) {
super(jdbcTemplate, transactionTemplate);
}
@Override
protected void doInit() throws Exception {
super.doInit();
if (tableName != null) {
// update query strings from default table name to the new table name
tableExistsString = DEFAULT_TABLE_EXISTS_STRING.replace(DEFAULT_TABLENAME, tableName);
createString = DEFAULT_CREATE_STRING.replace(DEFAULT_TABLENAME, tableName);
queryString = DEFAULT_QUERY_STRING.replace(DEFAULT_TABLENAME, tableName);
insertString = DEFAULT_INSERT_STRING.replace(DEFAULT_TABLENAME, tableName);
deleteString = DEFAULT_DELETE_STRING.replace(DEFAULT_TABLENAME, tableName);
clearString = DEFAULT_CLEAR_STRING.replace(DEFAULT_TABLENAME, tableName);
}
}
@Override
protected void doStart() throws Exception {
super.doStart();
boolean tableExists = transactionTemplate.execute(status -> {
try {
// we will receive an exception if the table doesn't exists or we cannot access it
jdbcTemplate.execute(getTableExistsString());
log.debug("Expected table for JdbcMessageIdRepository exist");
return true;
} catch (DataAccessException e) {
log.debug("Expected table for JdbcMessageIdRepository does not exist");
return false;
}
});
if (!tableExists && createTableIfNotExists) {
transactionTemplate.executeWithoutResult(status -> {
try {
log.debug("creating table for JdbcMessageIdRepository because it doesn't exist...");
jdbcTemplate.execute(getCreateString());
log.info("table created with query '{}'", getCreateString());
} catch (DataAccessException dae) {
// we will fail if we cannot create it
log.error(
"Can't create table for JdbcMessageIdRepository with query '{}' because of: {}. This may be a permissions problem. Please create this table and try again.",
getCreateString(), dae.getMessage());
throw dae;
}
});
}
}
@Override
protected int queryForInt(String key) {
return jdbcTemplate.queryForObject(getQueryString(), Integer.class, processorName, key);
}
@Override
protected int insert(String key) {
return jdbcTemplate.update(getInsertString(), processorName, key, new Timestamp(System.currentTimeMillis()));
}
@Override
protected int delete(String key) {
return jdbcTemplate.update(getDeleteString(), processorName, key);
}
@Override
protected int delete() {
return jdbcTemplate.update(getClearString(), processorName);
}
public boolean isCreateTableIfNotExists() {
return createTableIfNotExists;
}
public void setCreateTableIfNotExists(boolean createTableIfNotExists) {
this.createTableIfNotExists = createTableIfNotExists;
}
public String getTableExistsString() {
return tableExistsString;
}
public void setTableExistsString(String tableExistsString) {
this.tableExistsString = tableExistsString;
}
public String getTableName() {
return tableName;
}
/**
* To use a custom table name instead of the default name: CAMEL_MESSAGEPROCESSED
*/
public void setTableName(String tableName) {
this.tableName = tableName;
}
public String getCreateString() {
return createString;
}
public void setCreateString(String createString) {
this.createString = createString;
}
public String getQueryString() {
return queryString;
}
public void setQueryString(String queryString) {
this.queryString = queryString;
}
public String getInsertString() {
return insertString;
}
public void setInsertString(String insertString) {
this.insertString = insertString;
}
public String getDeleteString() {
return deleteString;
}
public void setDeleteString(String deleteString) {
this.deleteString = deleteString;
}
public String getClearString() {
return clearString;
}
public void setClearString(String clearString) {
this.clearString = clearString;
}
}
| JdbcMessageIdRepository |
java | grpc__grpc-java | testing/src/test/java/io/grpc/testing/GrpcCleanupRuleTest.java | {
"start": 1759,
"end": 14288
} | class ____ {
public static final FakeClock fakeClock = new FakeClock();
@Test
public void registerChannelReturnSameChannel() {
ManagedChannel channel = mock(ManagedChannel.class);
assertSame(channel, new GrpcCleanupRule().register(channel));
}
@Test
public void registerServerReturnSameServer() {
Server server = mock(Server.class);
assertSame(server, new GrpcCleanupRule().register(server));
}
@Test
public void registerNullChannelThrowsNpe() {
ManagedChannel channel = null;
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
NullPointerException e = assertThrows(NullPointerException.class,
() -> grpcCleanup.register(channel));
assertThat(e).hasMessageThat().isEqualTo("channel");
}
@Test
public void registerNullServerThrowsNpe() {
Server server = null;
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
NullPointerException e = assertThrows(NullPointerException.class,
() -> grpcCleanup.register(server));
assertThat(e).hasMessageThat().isEqualTo("server");
}
@Test
public void singleChannelCleanup() throws Throwable {
// setup
ManagedChannel channel = mock(ManagedChannel.class);
Statement statement = mock(Statement.class);
InOrder inOrder = inOrder(statement, channel);
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
// run
grpcCleanup.register(channel);
boolean awaitTerminationFailed = false;
try {
// will throw because channel.awaitTermination(long, TimeUnit) will return false;
grpcCleanup.apply(statement, null /* description*/).evaluate();
} catch (AssertionError e) {
awaitTerminationFailed = true;
}
// verify
assertTrue(awaitTerminationFailed);
inOrder.verify(statement).evaluate();
inOrder.verify(channel).shutdown();
inOrder.verify(channel).awaitTermination(anyLong(), any(TimeUnit.class));
inOrder.verify(channel).shutdownNow();
}
@Test
public void singleServerCleanup() throws Throwable {
// setup
Server server = mock(Server.class);
Statement statement = mock(Statement.class);
InOrder inOrder = inOrder(statement, server);
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
// run
grpcCleanup.register(server);
boolean awaitTerminationFailed = false;
try {
// will throw because channel.awaitTermination(long, TimeUnit) will return false;
grpcCleanup.apply(statement, null /* description*/).evaluate();
} catch (AssertionError e) {
awaitTerminationFailed = true;
}
// verify
assertTrue(awaitTerminationFailed);
inOrder.verify(statement).evaluate();
inOrder.verify(server).shutdown();
inOrder.verify(server).awaitTermination(anyLong(), any(TimeUnit.class));
inOrder.verify(server).shutdownNow();
}
@Test
public void multiResource_cleanupGracefully() throws Throwable {
// setup
Resource resource1 = mock(Resource.class);
Resource resource2 = mock(Resource.class);
Resource resource3 = mock(Resource.class);
doReturn(true).when(resource1).awaitReleased(anyLong(), any(TimeUnit.class));
doReturn(true).when(resource2).awaitReleased(anyLong(), any(TimeUnit.class));
doReturn(true).when(resource3).awaitReleased(anyLong(), any(TimeUnit.class));
Statement statement = mock(Statement.class);
InOrder inOrder = inOrder(statement, resource1, resource2, resource3);
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
// run
grpcCleanup.register(resource1);
grpcCleanup.register(resource2);
grpcCleanup.register(resource3);
grpcCleanup.apply(statement, null /* description*/).evaluate();
// Verify.
inOrder.verify(statement).evaluate();
inOrder.verify(resource3).cleanUp();
inOrder.verify(resource2).cleanUp();
inOrder.verify(resource1).cleanUp();
inOrder.verify(resource3).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verify(resource2).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verify(resource1).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verifyNoMoreInteractions();
verify(resource1, never()).forceCleanUp();
verify(resource2, never()).forceCleanUp();
verify(resource3, never()).forceCleanUp();
}
@Test
public void baseTestFails() throws Throwable {
// setup
Resource resource = mock(Resource.class);
Statement statement = mock(Statement.class);
doThrow(new Exception()).when(statement).evaluate();
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
// run
grpcCleanup.register(resource);
boolean baseTestFailed = false;
try {
grpcCleanup.apply(statement, null /* description*/).evaluate();
} catch (Exception e) {
baseTestFailed = true;
}
// verify
assertTrue(baseTestFailed);
verify(resource).forceCleanUp();
verifyNoMoreInteractions(resource);
verify(resource, never()).cleanUp();
verify(resource, never()).awaitReleased(anyLong(), any(TimeUnit.class));
}
@Test
public void multiResource_awaitReleasedFails() throws Throwable {
// setup
Resource resource1 = mock(Resource.class);
Resource resource2 = mock(Resource.class);
Resource resource3 = mock(Resource.class);
doReturn(true).when(resource1).awaitReleased(anyLong(), any(TimeUnit.class));
doReturn(false).when(resource2).awaitReleased(anyLong(), any(TimeUnit.class));
doReturn(true).when(resource3).awaitReleased(anyLong(), any(TimeUnit.class));
Statement statement = mock(Statement.class);
InOrder inOrder = inOrder(statement, resource1, resource2, resource3);
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
// run
grpcCleanup.register(resource1);
grpcCleanup.register(resource2);
grpcCleanup.register(resource3);
boolean cleanupFailed = false;
try {
grpcCleanup.apply(statement, null /* description*/).evaluate();
} catch (AssertionError e) {
cleanupFailed = true;
}
// verify
assertTrue(cleanupFailed);
inOrder.verify(statement).evaluate();
inOrder.verify(resource3).cleanUp();
inOrder.verify(resource2).cleanUp();
inOrder.verify(resource1).cleanUp();
inOrder.verify(resource3).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verify(resource2).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verify(resource1).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verify(resource2).forceCleanUp();
inOrder.verifyNoMoreInteractions();
verify(resource3, never()).forceCleanUp();
verify(resource1, never()).forceCleanUp();
}
@Test
public void multiResource_awaitReleasedInterrupted() throws Throwable {
// setup
Resource resource1 = mock(Resource.class);
Resource resource2 = mock(Resource.class);
Resource resource3 = mock(Resource.class);
doReturn(true).when(resource1).awaitReleased(anyLong(), any(TimeUnit.class));
doThrow(new InterruptedException())
.when(resource2).awaitReleased(anyLong(), any(TimeUnit.class));
doReturn(true).when(resource3).awaitReleased(anyLong(), any(TimeUnit.class));
Statement statement = mock(Statement.class);
InOrder inOrder = inOrder(statement, resource1, resource2, resource3);
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
// run
grpcCleanup.register(resource1);
grpcCleanup.register(resource2);
grpcCleanup.register(resource3);
boolean cleanupFailed = false;
try {
grpcCleanup.apply(statement, null /* description*/).evaluate();
} catch (Throwable e) {
cleanupFailed = true;
}
// verify
assertTrue(cleanupFailed);
assertTrue(Thread.interrupted());
inOrder.verify(statement).evaluate();
inOrder.verify(resource3).cleanUp();
inOrder.verify(resource2).cleanUp();
inOrder.verify(resource1).cleanUp();
inOrder.verify(resource3).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verify(resource2).awaitReleased(anyLong(), any(TimeUnit.class));
inOrder.verify(resource2).forceCleanUp();
inOrder.verify(resource1).forceCleanUp();
inOrder.verifyNoMoreInteractions();
verify(resource3, never()).forceCleanUp();
verify(resource1, never()).awaitReleased(anyLong(), any(TimeUnit.class));
}
@Test
public void multiResource_timeoutCalculation() throws Throwable {
// setup
Resource resource1 = mock(FakeResource.class,
delegatesTo(new FakeResource(1 /* cleanupNanos */, 10 /* awaitReleaseNanos */)));
Resource resource2 = mock(FakeResource.class,
delegatesTo(new FakeResource(100 /* cleanupNanos */, 1000 /* awaitReleaseNanos */)));
Statement statement = mock(Statement.class);
InOrder inOrder = inOrder(statement, resource1, resource2);
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule().setTicker(fakeClock.getTicker());
// run
grpcCleanup.register(resource1);
grpcCleanup.register(resource2);
grpcCleanup.apply(statement, null /* description*/).evaluate();
// verify
inOrder.verify(statement).evaluate();
inOrder.verify(resource2).cleanUp();
inOrder.verify(resource1).cleanUp();
inOrder.verify(resource2).awaitReleased(
TimeUnit.SECONDS.toNanos(10) - 100 - 1, TimeUnit.NANOSECONDS);
inOrder.verify(resource1).awaitReleased(
TimeUnit.SECONDS.toNanos(10) - 100 - 1 - 1000, TimeUnit.NANOSECONDS);
inOrder.verifyNoMoreInteractions();
verify(resource2, never()).forceCleanUp();
verify(resource1, never()).forceCleanUp();
}
@Test
public void multiResource_timeoutCalculation_customTimeout() throws Throwable {
// setup
Resource resource1 = mock(FakeResource.class,
delegatesTo(new FakeResource(1 /* cleanupNanos */, 10 /* awaitReleaseNanos */)));
Resource resource2 = mock(FakeResource.class,
delegatesTo(new FakeResource(100 /* cleanupNanos */, 1000 /* awaitReleaseNanos */)));
Statement statement = mock(Statement.class);
InOrder inOrder = inOrder(statement, resource1, resource2);
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule()
.setTicker(fakeClock.getTicker()).setTimeout(3000, TimeUnit.NANOSECONDS);
// run
grpcCleanup.register(resource1);
grpcCleanup.register(resource2);
grpcCleanup.apply(statement, null /* description*/).evaluate();
// verify
inOrder.verify(statement).evaluate();
inOrder.verify(resource2).cleanUp();
inOrder.verify(resource1).cleanUp();
inOrder.verify(resource2).awaitReleased(3000 - 100 - 1, TimeUnit.NANOSECONDS);
inOrder.verify(resource1).awaitReleased(3000 - 100 - 1 - 1000, TimeUnit.NANOSECONDS);
inOrder.verifyNoMoreInteractions();
verify(resource2, never()).forceCleanUp();
verify(resource1, never()).forceCleanUp();
}
@Test
public void baseTestFailsThenCleanupFails() throws Throwable {
// setup
Exception baseTestFailure = new Exception("base test failure");
Exception cleanupFailure = new RuntimeException("force cleanup failed");
Statement statement = mock(Statement.class);
doThrow(baseTestFailure).when(statement).evaluate();
Resource resource1 = mock(Resource.class);
Resource resource2 = mock(Resource.class);
Resource resource3 = mock(Resource.class);
doThrow(cleanupFailure).when(resource2).forceCleanUp();
InOrder inOrder = inOrder(statement, resource1, resource2, resource3);
GrpcCleanupRule grpcCleanup = new GrpcCleanupRule();
// run
grpcCleanup.register(resource1);
grpcCleanup.register(resource2);
grpcCleanup.register(resource3);
Throwable failure = null;
try {
grpcCleanup.apply(statement, null /* description*/).evaluate();
} catch (Throwable e) {
failure = e;
}
// verify
if (failure instanceof MultipleFailureException) {
// JUnit 4.13+
assertThat(((MultipleFailureException) failure).getFailures())
.containsExactly(baseTestFailure, cleanupFailure);
} else {
// JUnit 4.12. Suffers from https://github.com/junit-team/junit4/issues/1334
assertThat(failure).isSameInstanceAs(cleanupFailure);
}
inOrder.verify(statement).evaluate();
inOrder.verify(resource3).forceCleanUp();
inOrder.verify(resource2).forceCleanUp();
inOrder.verifyNoMoreInteractions();
verify(resource1, never()).cleanUp();
verify(resource2, never()).cleanUp();
verify(resource3, never()).cleanUp();
verify(resource1, never()).forceCleanUp();
}
public static | GrpcCleanupRuleTest |
java | netty__netty | microbench/src/main/java/io/netty/microbench/http/HttpRequestDecoderUtils.java | {
"start": 712,
"end": 2804
} | class ____ {
private HttpRequestDecoderUtils() {
}
static final byte[] CONTENT_MIXED_DELIMITERS = createContent("\r\n", "\n");
static final int CONTENT_LENGTH = 120;
private static byte[] createContent(String... lineDelimiters) {
String lineDelimiter;
String lineDelimiter2;
if (lineDelimiters.length == 2) {
lineDelimiter = lineDelimiters[0];
lineDelimiter2 = lineDelimiters[1];
} else {
lineDelimiter = lineDelimiters[0];
lineDelimiter2 = lineDelimiters[0];
}
// This GET request is incorrect but it does not matter for HttpRequestDecoder.
// It used only to get a long request.
return ("GET /some/path?foo=bar&wibble=eek HTTP/1.1" + "\r\n" +
"Upgrade: WebSocket" + lineDelimiter2 +
"Connection: Upgrade" + lineDelimiter +
"Host: localhost" + lineDelimiter2 +
"Referer: http://www.site.ru/index.html" + lineDelimiter +
"User-Agent: Mozilla/5.0 (X11; U; Linux i686; ru; rv:1.9b5) Gecko/2008050509 Firefox/3.0b5" +
lineDelimiter2 +
"Accept: text/html" + lineDelimiter +
"Cookie: income=1" + lineDelimiter2 +
"Origin: http://localhost:8080" + lineDelimiter +
"Sec-WebSocket-Key1: 10 28 8V7 8 48 0" + lineDelimiter2 +
"Sec-WebSocket-Key2: 8 Xt754O3Q3QW 0 _60" + lineDelimiter +
"Content-Type: application/x-www-form-urlencoded" + lineDelimiter2 +
"Content-Length: " + CONTENT_LENGTH + lineDelimiter +
"\r\n" +
"1234567890\r\n" +
"1234567890\r\n" +
"1234567890\r\n" +
"1234567890\r\n" +
"1234567890\r\n" +
"1234567890\r\n" +
"1234567890\r\n" +
"1234567890\r\n" +
"1234567890\r\n" +
"1234567890\r\n"
).getBytes(CharsetUtil.US_ASCII);
}
}
| HttpRequestDecoderUtils |
java | square__retrofit | retrofit-adapters/rxjava2/src/test/java/retrofit2/adapter/rxjava2/FlowableThrowingTest.java | {
"start": 1673,
"end": 10444
} | interface ____ {
@GET("/")
Flowable<String> body();
@GET("/")
Flowable<Response<String>> response();
@GET("/")
Flowable<Result<String>> result();
}
private Service service;
@Before
public void setUp() {
Retrofit retrofit =
new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(new StringConverterFactory())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
service = retrofit.create(Service.class);
}
@Test
public void bodyThrowingInOnNextDeliveredToError() {
server.enqueue(new MockResponse());
RecordingSubscriber<String> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.body()
.safeSubscribe(
new ForwardingSubscriber<String>(subscriber) {
@Override
public void onNext(String value) {
throw e;
}
});
subscriber.assertError(e);
}
@Test
public void bodyThrowingInOnCompleteDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<String> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingSubscriber<String>(subscriber) {
@Override
public void onComplete() {
throw e;
}
});
subscriber.assertAnyValue();
Throwable throwable = throwableRef.get();
assertThat(throwable).isInstanceOf(UndeliverableException.class);
assertThat(throwable).hasCauseThat().isSameInstanceAs(e);
}
@Test
public void bodyThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setResponseCode(404));
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<String> subscriber = subscriberRule.create();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final RuntimeException e = new RuntimeException();
service
.body()
.subscribe(
new ForwardingSubscriber<String>(subscriber) {
@Override
public void onError(Throwable throwable) {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void responseThrowingInOnNextDeliveredToError() {
server.enqueue(new MockResponse());
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.response()
.safeSubscribe(
new ForwardingSubscriber<Response<String>>(subscriber) {
@Override
public void onNext(Response<String> value) {
throw e;
}
});
subscriber.assertError(e);
}
@Test
public void responseThrowingInOnCompleteDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingSubscriber<Response<String>>(subscriber) {
@Override
public void onComplete() {
throw e;
}
});
subscriber.assertAnyValue();
Throwable throwable = throwableRef.get();
assertThat(throwable).isInstanceOf(UndeliverableException.class);
assertThat(throwable).hasCauseThat().isSameInstanceAs(e);
}
@Test
public void responseThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse().setSocketPolicy(DISCONNECT_AFTER_REQUEST));
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<Response<String>> subscriber = subscriberRule.create();
final AtomicReference<Throwable> errorRef = new AtomicReference<>();
final RuntimeException e = new RuntimeException();
service
.response()
.subscribe(
new ForwardingSubscriber<Response<String>>(subscriber) {
@Override
public void onError(Throwable throwable) {
if (!errorRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
throw e;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(errorRef.get(), e);
}
@Test
public void resultThrowingInOnNextDeliveredToError() {
server.enqueue(new MockResponse());
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.result()
.safeSubscribe(
new ForwardingSubscriber<Result<String>>(subscriber) {
@Override
public void onNext(Result<String> value) {
throw e;
}
});
subscriber.assertError(e);
}
@Test
public void resultThrowingInOnCompletedDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
final RuntimeException e = new RuntimeException();
service
.result()
.subscribe(
new ForwardingSubscriber<Result<String>>(subscriber) {
@Override
public void onComplete() {
throw e;
}
});
subscriber.assertAnyValue();
Throwable throwable = throwableRef.get();
assertThat(throwable).isInstanceOf(UndeliverableException.class);
assertThat(throwable).hasCauseThat().isSameInstanceAs(e);
}
@Test
public void resultThrowingInOnErrorDeliveredToPlugin() {
server.enqueue(new MockResponse());
final AtomicReference<Throwable> throwableRef = new AtomicReference<>();
RxJavaPlugins.setErrorHandler(
throwable -> {
if (!throwableRef.compareAndSet(null, throwable)) {
throw Exceptions.propagate(throwable);
}
});
RecordingSubscriber<Result<String>> subscriber = subscriberRule.create();
final RuntimeException first = new RuntimeException();
final RuntimeException second = new RuntimeException();
service
.result()
.safeSubscribe(
new ForwardingSubscriber<Result<String>>(subscriber) {
@Override
public void onNext(Result<String> value) {
// The only way to trigger onError for a result is if onNext throws.
throw first;
}
@Override
public void onError(Throwable throwable) {
throw second;
}
});
//noinspection ThrowableResultOfMethodCallIgnored
CompositeException composite = (CompositeException) throwableRef.get();
assertThat(composite.getExceptions()).containsExactly(first, second);
}
private abstract static | Service |
java | apache__kafka | connect/mirror/src/test/java/org/apache/kafka/connect/mirror/MirrorSourceTaskTest.java | {
"start": 2479,
"end": 19078
} | class ____ {
@Test
public void testSerde() {
byte[] key = new byte[]{'a', 'b', 'c', 'd', 'e'};
byte[] value = new byte[]{'f', 'g', 'h', 'i', 'j', 'k'};
Headers headers = new RecordHeaders();
headers.add("header1", new byte[]{'l', 'm', 'n', 'o'});
headers.add("header2", new byte[]{'p', 'q', 'r', 's', 't'});
ConsumerRecord<byte[], byte[]> consumerRecord = new ConsumerRecord<>("topic1", 2, 3L, 4L,
TimestampType.CREATE_TIME, 5, 6, key, value, headers, Optional.empty());
MirrorSourceTask mirrorSourceTask = new MirrorSourceTask(null, null, "cluster7",
new DefaultReplicationPolicy(), null);
SourceRecord sourceRecord = mirrorSourceTask.convertRecord(consumerRecord);
assertEquals("cluster7.topic1", sourceRecord.topic(),
"Failure on cluster7.topic1 consumerRecord serde");
assertEquals(2, sourceRecord.kafkaPartition().intValue(),
"sourceRecord kafka partition is incorrect");
assertEquals(new TopicPartition("topic1", 2), MirrorUtils.unwrapPartition(sourceRecord.sourcePartition()),
"topic1 unwrapped from sourcePartition is incorrect");
assertEquals(3L, MirrorUtils.unwrapOffset(sourceRecord.sourceOffset()).longValue(),
"sourceRecord's sourceOffset is incorrect");
assertEquals(4L, sourceRecord.timestamp().longValue(),
"sourceRecord's timestamp is incorrect");
assertEquals(key, sourceRecord.key(), "sourceRecord's key is incorrect");
assertEquals(value, sourceRecord.value(), "sourceRecord's value is incorrect");
assertEquals(headers.lastHeader("header1").value(), sourceRecord.headers().lastWithName("header1").value(),
"sourceRecord's header1 is incorrect");
assertEquals(headers.lastHeader("header2").value(), sourceRecord.headers().lastWithName("header2").value(),
"sourceRecord's header2 is incorrect");
}
@Test
public void testOffsetSync() {
OffsetSyncWriter.PartitionState partitionState = new OffsetSyncWriter.PartitionState(50);
assertTrue(partitionState.update(0, 100), "always emit offset sync on first update");
assertTrue(partitionState.shouldSyncOffsets, "should sync offsets");
partitionState.reset();
assertFalse(partitionState.shouldSyncOffsets, "should sync offsets to false");
assertTrue(partitionState.update(2, 102), "upstream offset skipped -> resync");
partitionState.reset();
assertFalse(partitionState.update(3, 152), "no sync");
partitionState.reset();
assertTrue(partitionState.update(4, 153), "one past target offset");
partitionState.reset();
assertFalse(partitionState.update(5, 154), "no sync");
partitionState.reset();
assertFalse(partitionState.update(6, 203), "no sync");
partitionState.reset();
assertTrue(partitionState.update(7, 204), "one past target offset");
partitionState.reset();
assertTrue(partitionState.update(2, 206), "upstream reset");
partitionState.reset();
assertFalse(partitionState.update(3, 207), "no sync");
partitionState.reset();
assertTrue(partitionState.update(4, 3), "downstream reset");
partitionState.reset();
assertFalse(partitionState.update(5, 4), "no sync");
assertTrue(partitionState.update(7, 6), "sync");
assertTrue(partitionState.update(7, 6), "sync");
assertTrue(partitionState.update(8, 7), "sync");
assertTrue(partitionState.update(10, 57), "sync");
partitionState.reset();
assertFalse(partitionState.update(11, 58), "sync");
assertFalse(partitionState.shouldSyncOffsets, "should sync offsets to false");
}
@Test
public void testZeroOffsetSync() {
OffsetSyncWriter.PartitionState partitionState = new OffsetSyncWriter.PartitionState(0);
// if max offset lag is zero, should always emit offset syncs
assertTrue(partitionState.update(0, 100), "zeroOffsetSync downStreamOffset 100 is incorrect");
assertTrue(partitionState.shouldSyncOffsets, "should sync offsets");
partitionState.reset();
assertFalse(partitionState.shouldSyncOffsets, "should sync offsets to false");
assertTrue(partitionState.update(2, 102), "zeroOffsetSync downStreamOffset 102 is incorrect");
partitionState.reset();
assertTrue(partitionState.update(3, 153), "zeroOffsetSync downStreamOffset 153 is incorrect");
partitionState.reset();
assertTrue(partitionState.update(4, 154), "zeroOffsetSync downStreamOffset 154 is incorrect");
partitionState.reset();
assertTrue(partitionState.update(5, 155), "zeroOffsetSync downStreamOffset 155 is incorrect");
partitionState.reset();
assertTrue(partitionState.update(6, 207), "zeroOffsetSync downStreamOffset 207 is incorrect");
partitionState.reset();
assertTrue(partitionState.update(2, 208), "zeroOffsetSync downStreamOffset 208 is incorrect");
partitionState.reset();
assertTrue(partitionState.update(3, 209), "zeroOffsetSync downStreamOffset 209 is incorrect");
partitionState.reset();
assertTrue(partitionState.update(4, 3), "zeroOffsetSync downStreamOffset 3 is incorrect");
partitionState.reset();
assertTrue(partitionState.update(5, 4), "zeroOffsetSync downStreamOffset 4 is incorrect");
assertTrue(partitionState.update(7, 6), "zeroOffsetSync downStreamOffset 6 is incorrect");
assertTrue(partitionState.update(7, 6), "zeroOffsetSync downStreamOffset 6 is incorrect");
assertTrue(partitionState.update(8, 7), "zeroOffsetSync downStreamOffset 7 is incorrect");
assertTrue(partitionState.update(10, 57), "zeroOffsetSync downStreamOffset 57 is incorrect");
partitionState.reset();
assertTrue(partitionState.update(11, 58), "zeroOffsetSync downStreamOffset 58 is incorrect");
}
@Test
public void testPoll() {
// Create a consumer mock
byte[] key1 = "abc".getBytes();
byte[] value1 = "fgh".getBytes();
byte[] key2 = "123".getBytes();
byte[] value2 = "456".getBytes();
List<ConsumerRecord<byte[], byte[]>> consumerRecordsList = new ArrayList<>();
String topicName = "test";
String headerKey = "key";
RecordHeaders headers = new RecordHeaders(new Header[] {
new RecordHeader(headerKey, "value".getBytes()),
});
consumerRecordsList.add(new ConsumerRecord<>(topicName, 0, 0, System.currentTimeMillis(),
TimestampType.CREATE_TIME, key1.length, value1.length, key1, value1, headers, Optional.empty()));
consumerRecordsList.add(new ConsumerRecord<>(topicName, 1, 1, System.currentTimeMillis(),
TimestampType.CREATE_TIME, key2.length, value2.length, key2, value2, headers, Optional.empty()));
final TopicPartition tp = new TopicPartition(topicName, 0);
ConsumerRecords<byte[], byte[]> consumerRecords =
new ConsumerRecords<>(Map.of(tp, consumerRecordsList), Map.of(tp, new OffsetAndMetadata(2, Optional.empty(), "")));
@SuppressWarnings("unchecked")
KafkaConsumer<byte[], byte[]> consumer = mock(KafkaConsumer.class);
when(consumer.poll(any())).thenReturn(consumerRecords);
MirrorSourceMetrics metrics = mock(MirrorSourceMetrics.class);
String sourceClusterName = "cluster1";
ReplicationPolicy replicationPolicy = new DefaultReplicationPolicy();
MirrorSourceTask mirrorSourceTask = new MirrorSourceTask(consumer, metrics, sourceClusterName,
replicationPolicy, null);
List<SourceRecord> sourceRecords = mirrorSourceTask.poll();
assertEquals(2, sourceRecords.size());
for (int i = 0; i < sourceRecords.size(); i++) {
SourceRecord sourceRecord = sourceRecords.get(i);
ConsumerRecord<byte[], byte[]> consumerRecord = consumerRecordsList.get(i);
assertEquals(consumerRecord.key(), sourceRecord.key(),
"consumerRecord key does not equal sourceRecord key");
assertEquals(consumerRecord.value(), sourceRecord.value(),
"consumerRecord value does not equal sourceRecord value");
// We expect that the topicname will be based on the replication policy currently used
assertEquals(replicationPolicy.formatRemoteTopic(sourceClusterName, topicName),
sourceRecord.topic(), "topicName not the same as the current replicationPolicy");
// We expect that MirrorMaker will keep the same partition assignment
assertEquals(consumerRecord.partition(), sourceRecord.kafkaPartition().intValue(),
"partition assignment not the same as the current replicationPolicy");
// Check header values
List<Header> expectedHeaders = new ArrayList<>();
consumerRecord.headers().forEach(expectedHeaders::add);
List<org.apache.kafka.connect.header.Header> taskHeaders = new ArrayList<>();
sourceRecord.headers().forEach(taskHeaders::add);
compareHeaders(expectedHeaders, taskHeaders);
}
}
@Test
public void testSeekBehaviorDuringStart() {
// Setting up mock behavior.
@SuppressWarnings("unchecked")
KafkaConsumer<byte[], byte[]> mockConsumer = mock(KafkaConsumer.class);
SourceTaskContext mockSourceTaskContext = mock(SourceTaskContext.class);
OffsetStorageReader mockOffsetStorageReader = mock(OffsetStorageReader.class);
when(mockSourceTaskContext.offsetStorageReader()).thenReturn(mockOffsetStorageReader);
Set<TopicPartition> topicPartitions = Set.of(
new TopicPartition("previouslyReplicatedTopic", 8),
new TopicPartition("previouslyReplicatedTopic1", 0),
new TopicPartition("previouslyReplicatedTopic", 1),
new TopicPartition("newTopicToReplicate1", 1),
new TopicPartition("newTopicToReplicate1", 4),
new TopicPartition("newTopicToReplicate2", 0)
);
long arbitraryCommittedOffset = 4L;
long offsetToSeek = arbitraryCommittedOffset + 1L;
when(mockOffsetStorageReader.offset(anyMap())).thenAnswer(testInvocation -> {
Map<String, Object> topicPartitionOffsetMap = testInvocation.getArgument(0);
String topicName = topicPartitionOffsetMap.get("topic").toString();
// Only return the offset for previously replicated topics.
// For others, there is no value set.
if (topicName.startsWith("previouslyReplicatedTopic")) {
topicPartitionOffsetMap.put("offset", arbitraryCommittedOffset);
}
return topicPartitionOffsetMap;
});
MirrorSourceTask mirrorSourceTask = new MirrorSourceTask(mockConsumer, null, null,
new DefaultReplicationPolicy(), null);
mirrorSourceTask.initialize(mockSourceTaskContext);
// Call test subject
mirrorSourceTask.initializeConsumer(topicPartitions);
// Verifications
// Ensure all the topic partitions are assigned to consumer
verify(mockConsumer, times(1)).assign(topicPartitions);
// Ensure seek is only called for previously committed topic partitions.
verify(mockConsumer, times(1))
.seek(new TopicPartition("previouslyReplicatedTopic", 8), offsetToSeek);
verify(mockConsumer, times(1))
.seek(new TopicPartition("previouslyReplicatedTopic", 1), offsetToSeek);
verify(mockConsumer, times(1))
.seek(new TopicPartition("previouslyReplicatedTopic1", 0), offsetToSeek);
verifyNoMoreInteractions(mockConsumer);
}
@Test
public void testCommitRecordWithNullMetadata() {
// Create a consumer mock
byte[] key1 = "abc".getBytes();
byte[] value1 = "fgh".getBytes();
String topicName = "test";
String headerKey = "key";
RecordHeaders headers = new RecordHeaders(new Header[] {
new RecordHeader(headerKey, "value".getBytes()),
});
@SuppressWarnings("unchecked")
KafkaConsumer<byte[], byte[]> consumer = mock(KafkaConsumer.class);
MirrorSourceMetrics metrics = mock(MirrorSourceMetrics.class);
String sourceClusterName = "cluster1";
ReplicationPolicy replicationPolicy = new DefaultReplicationPolicy();
MirrorSourceTask mirrorSourceTask = new MirrorSourceTask(consumer, metrics, sourceClusterName,
replicationPolicy, null);
SourceRecord sourceRecord = mirrorSourceTask.convertRecord(new ConsumerRecord<>(topicName, 0, 0, System.currentTimeMillis(),
TimestampType.CREATE_TIME, key1.length, value1.length, key1, value1, headers, Optional.empty()));
// Expect that commitRecord will not throw an exception
mirrorSourceTask.commitRecord(sourceRecord, null);
}
@Test
public void testSendSyncEvent() {
byte[] recordKey = "key".getBytes();
byte[] recordValue = "value".getBytes();
long maxOffsetLag = 50;
int recordPartition = 0;
int recordOffset = 0;
int metadataOffset = 100;
String topicName = "topic";
String sourceClusterName = "sourceCluster";
RecordHeaders headers = new RecordHeaders();
ReplicationPolicy replicationPolicy = new DefaultReplicationPolicy();
@SuppressWarnings("unchecked")
KafkaConsumer<byte[], byte[]> consumer = mock(KafkaConsumer.class);
MirrorSourceMetrics metrics = mock(MirrorSourceMetrics.class);
PartitionState partitionState = new PartitionState(maxOffsetLag);
Map<TopicPartition, PartitionState> partitionStates = new HashMap<>();
OffsetSyncWriter offsetSyncWriter = mock(OffsetSyncWriter.class);
when(offsetSyncWriter.maxOffsetLag()).thenReturn(maxOffsetLag);
doNothing().when(offsetSyncWriter).firePendingOffsetSyncs();
doNothing().when(offsetSyncWriter).promoteDelayedOffsetSyncs();
MirrorSourceTask mirrorSourceTask = new MirrorSourceTask(consumer, metrics, sourceClusterName,
replicationPolicy, offsetSyncWriter);
SourceRecord sourceRecord = mirrorSourceTask.convertRecord(new ConsumerRecord<>(topicName, recordPartition,
recordOffset, System.currentTimeMillis(), TimestampType.CREATE_TIME, recordKey.length,
recordValue.length, recordKey, recordValue, headers, Optional.empty()));
TopicPartition sourceTopicPartition = MirrorUtils.unwrapPartition(sourceRecord.sourcePartition());
partitionStates.put(sourceTopicPartition, partitionState);
RecordMetadata recordMetadata = new RecordMetadata(sourceTopicPartition, metadataOffset, 0, 0, 0, recordPartition);
doNothing().when(offsetSyncWriter).maybeQueueOffsetSyncs(eq(sourceTopicPartition), eq((long) recordOffset), eq(recordMetadata.offset()));
mirrorSourceTask.commitRecord(sourceRecord, recordMetadata);
// We should have dispatched this sync to the producer
verify(offsetSyncWriter, times(1)).maybeQueueOffsetSyncs(eq(sourceTopicPartition), eq((long) recordOffset), eq(recordMetadata.offset()));
verify(offsetSyncWriter, times(1)).firePendingOffsetSyncs();
mirrorSourceTask.commit();
// No more syncs should take place; we've been able to publish all of them so far
verify(offsetSyncWriter, times(1)).promoteDelayedOffsetSyncs();
verify(offsetSyncWriter, times(2)).firePendingOffsetSyncs();
}
private void compareHeaders(List<Header> expectedHeaders, List<org.apache.kafka.connect.header.Header> taskHeaders) {
assertEquals(expectedHeaders.size(), taskHeaders.size());
for (int i = 0; i < expectedHeaders.size(); i++) {
Header expectedHeader = expectedHeaders.get(i);
org.apache.kafka.connect.header.Header taskHeader = taskHeaders.get(i);
assertEquals(expectedHeader.key(), taskHeader.key(),
"taskHeader's key expected to equal " + taskHeader.key());
assertEquals(expectedHeader.value(), taskHeader.value(),
"taskHeader's value expected to equal " + taskHeader.value().toString());
}
}
}
| MirrorSourceTaskTest |
java | google__dagger | javatests/dagger/internal/codegen/ComponentCreatorTest.java | {
"start": 29674,
"end": 29809
} | class ____ {")
.addLinesIf(
BUILDER,
" @Component.Builder",
" | SimpleComponent |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/transaction/manager/LookUpTxMgrViaTransactionManagementConfigurerTests.java | {
"start": 2656,
"end": 3047
} | class ____ implements TransactionManagementConfigurer {
@Override
public PlatformTransactionManager annotationDrivenTransactionManager() {
return txManager1();
}
@Bean
PlatformTransactionManager txManager1() {
return new CallCountingTransactionManager();
}
@Bean
PlatformTransactionManager txManager2() {
return new CallCountingTransactionManager();
}
}
}
| Config |
java | apache__rocketmq | store/src/main/java/org/apache/rocketmq/store/FlushManager.java | {
"start": 948,
"end": 1289
} | interface ____ {
void start();
void shutdown();
void wakeUpFlush();
void wakeUpCommit();
void handleDiskFlush(AppendMessageResult result, PutMessageResult putMessageResult, MessageExt messageExt);
CompletableFuture<PutMessageStatus> handleDiskFlush(AppendMessageResult result, MessageExt messageExt);
}
| FlushManager |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/collection/bag/EagerBagsTest.java | {
"start": 824,
"end": 1894
} | class ____ {
@BeforeAll
public void setUp(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
EntityC c = new EntityC( 1l, "c" );
EntityC c1 = new EntityC( 2l, "c1" );
EntityC c2 = new EntityC( 3l, "c2" );
EntityC c3 = new EntityC( 4l, "c3" );
EntityB b = new EntityB( 1l, "b" );
b.addAttribute( c );
b.addAttribute( c1 );
EntityB b1 = new EntityB( 2l, "b1" );
b1.addAttribute( c2 );
b1.addAttribute( c3 );
EntityA a = new EntityA( 1l, "a" );
a.addAttribute( b );
a.addAttribute( b1 );
session.persist( c );
session.persist( c1 );
session.persist( c2 );
session.persist( c3 );
session.persist( b );
session.persist( b1 );
session.persist( a );
}
);
}
@Test
public void testIt(SessionFactoryScope scope) {
scope.inTransaction(
session -> {
EntityA entityA = session.find( EntityA.class, 1l );
assertThat( entityA.attributes.size() ).isEqualTo( 2 );
}
);
}
@Entity(name = "EntityA")
public static | EagerBagsTest |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesNodesEndpointBuilderFactory.java | {
"start": 46804,
"end": 48291
} | interface ____
extends
AdvancedKubernetesNodesEndpointConsumerBuilder,
AdvancedKubernetesNodesEndpointProducerBuilder {
default KubernetesNodesEndpointBuilder basic() {
return (KubernetesNodesEndpointBuilder) this;
}
/**
* Connection timeout in milliseconds to use when making requests to the
* Kubernetes API server.
*
* The option is a: <code>java.lang.Integer</code> type.
*
* Group: advanced
*
* @param connectionTimeout the value to set
* @return the dsl builder
*/
default AdvancedKubernetesNodesEndpointBuilder connectionTimeout(Integer connectionTimeout) {
doSetProperty("connectionTimeout", connectionTimeout);
return this;
}
/**
* Connection timeout in milliseconds to use when making requests to the
* Kubernetes API server.
*
* The option will be converted to a <code>java.lang.Integer</code>
* type.
*
* Group: advanced
*
* @param connectionTimeout the value to set
* @return the dsl builder
*/
default AdvancedKubernetesNodesEndpointBuilder connectionTimeout(String connectionTimeout) {
doSetProperty("connectionTimeout", connectionTimeout);
return this;
}
}
public | AdvancedKubernetesNodesEndpointBuilder |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/callbacks/PrePersistIdTest.java | {
"start": 777,
"end": 1083
} | class ____ {
@Test void test(SessionFactoryScope scope) {
scope.inTransaction(s -> {
GeneratedIdInCallback entity = new GeneratedIdInCallback();
s.persist(entity);
assertTrue(entity.success);
assertNotNull(entity.uuid);
});
}
@Entity(name = "GeneratedIdInCallback")
static | PrePersistIdTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/query/NativeQueryResultTypeAutoDiscoveryTest.java | {
"start": 22172,
"end": 22333
} | class ____ extends TestedEntity<Clob> {
public Clob getTestedProperty() {
return testedProperty;
}
}
@Entity(name = "blobEntity")
public static | ClobEntity |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/observers/duplicate/bindings/DuplicateBindingsResolutionTest.java | {
"start": 679,
"end": 1458
} | class ____ {
@RegisterExtension
public ArcTestContainer container = new ArcTestContainer(BindingTypeA.class, BindingTypeA.BindingTypeABinding.class,
AnEventType.class, AnObserver.class);
@Test
public void testDuplicateBindingTypesWhenResolvingFails() {
try {
CDI.current().getBeanManager().resolveObserverMethods(new AnEventType(),
new BindingTypeA.BindingTypeABinding("a1"), new BindingTypeA.BindingTypeABinding("a2"));
Assertions.fail(
"BM#resolveObserverMethods should throw IllegalArgumentException if supplied with duplicate bindings");
} catch (IllegalArgumentException iae) {
// expected
}
}
public static | DuplicateBindingsResolutionTest |
java | spring-projects__spring-boot | core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringEnvironmentPropertySource.java | {
"start": 891,
"end": 1671
} | class ____ implements PropertySource {
/**
* System properties take precedence followed by properties in Log4j properties files.
*/
private static final int PRIORITY = -100;
private volatile @Nullable Environment environment;
@Override
public int getPriority() {
return PRIORITY;
}
@Override
public @Nullable String getProperty(String key) {
Environment environment = this.environment;
return (environment != null) ? environment.getProperty(key) : null;
}
@Override
public boolean containsProperty(String key) {
Environment environment = this.environment;
return environment != null && environment.containsProperty(key);
}
void setEnvironment(@Nullable Environment environment) {
this.environment = environment;
}
}
| SpringEnvironmentPropertySource |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/bean/MyResponse.java | {
"start": 852,
"end": 906
} | class ____ {
int id;
String response;
}
| MyResponse |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/polymorphism/BidirectionalOneToOnePolymorphismTest.java | {
"start": 3866,
"end": 4104
} | class ____ extends Level2 {
@OneToOne
private Level1 level1;
public Level1 getLevel1() {
return level1;
}
public void setLevel1(Level1 level1) {
this.level1 = level1;
}
}
@Entity(name = "Level3")
static | DerivedLevel2 |
java | micronaut-projects__micronaut-core | inject/src/main/java/io/micronaut/inject/annotation/DefaultAnnotationMetadata.java | {
"start": 2359,
"end": 9330
} | class ____ extends AbstractAnnotationMetadata implements AnnotationMetadata, Cloneable, EnvironmentAnnotationMetadata {
@Nullable
Map<String, Map<CharSequence, Object>> declaredAnnotations;
@Nullable
Map<String, Map<CharSequence, Object>> allAnnotations;
@Nullable
Map<String, Map<CharSequence, Object>> declaredStereotypes;
@Nullable
Map<String, Map<CharSequence, Object>> allStereotypes;
@Nullable
Map<String, List<String>> annotationsByStereotype;
private final Map<String, List> annotationValuesByType = new ConcurrentHashMap<>(2);
private final boolean hasPropertyExpressions;
private final boolean hasEvaluatedExpressions;
/**
* Constructs empty annotation metadata.
*/
@Internal
protected DefaultAnnotationMetadata() {
hasPropertyExpressions = false;
hasEvaluatedExpressions = false;
}
/**
* This constructor is designed to be used by compile time produced subclasses.
*
* @param declaredAnnotations The directly declared annotations
* @param declaredStereotypes The directly declared stereotypes
* @param allStereotypes All stereotypes
* @param allAnnotations All annotations
* @param annotationsByStereotype The annotations by stereotype
*/
@Internal
@UsedByGeneratedCode
public DefaultAnnotationMetadata(
@Nullable Map<String, Map<CharSequence, Object>> declaredAnnotations,
@Nullable Map<String, Map<CharSequence, Object>> declaredStereotypes,
@Nullable Map<String, Map<CharSequence, Object>> allStereotypes,
@Nullable Map<String, Map<CharSequence, Object>> allAnnotations,
@Nullable Map<String, List<String>> annotationsByStereotype) {
this(declaredAnnotations, declaredStereotypes, allStereotypes, allAnnotations, annotationsByStereotype, true);
}
/**
* This constructor is designed to be used by compile time produced subclasses.
*
* @param declaredAnnotations The directly declared annotations
* @param declaredStereotypes The directly declared stereotypes
* @param allStereotypes All stereotypes
* @param allAnnotations All annotations
* @param annotationsByStereotype The annotations by stereotype
* @param hasPropertyExpressions Whether property expressions exist in the metadata
*/
@Internal
@UsedByGeneratedCode
public DefaultAnnotationMetadata(
@Nullable Map<String, Map<CharSequence, Object>> declaredAnnotations,
@Nullable Map<String, Map<CharSequence, Object>> declaredStereotypes,
@Nullable Map<String, Map<CharSequence, Object>> allStereotypes,
@Nullable Map<String, Map<CharSequence, Object>> allAnnotations,
@Nullable Map<String, List<String>> annotationsByStereotype,
boolean hasPropertyExpressions) {
this(declaredAnnotations, declaredStereotypes, allStereotypes, allAnnotations, annotationsByStereotype, hasPropertyExpressions, false);
}
/**
* This constructor is designed to be used by compile time produced subclasses.
*
* @param declaredAnnotations The directly declared annotations
* @param declaredStereotypes The directly declared stereotypes
* @param allStereotypes All stereotypes
* @param allAnnotations All annotations
* @param annotationsByStereotype The annotations by stereotype
* @param hasPropertyExpressions Whether property expressions exist in the metadata
* @param hasEvaluatedExpressions Whether evaluated expressions exist in the metadata
*/
@Internal
@UsedByGeneratedCode
public DefaultAnnotationMetadata(
@Nullable Map<String, Map<CharSequence, Object>> declaredAnnotations,
@Nullable Map<String, Map<CharSequence, Object>> declaredStereotypes,
@Nullable Map<String, Map<CharSequence, Object>> allStereotypes,
@Nullable Map<String, Map<CharSequence, Object>> allAnnotations,
@Nullable Map<String, List<String>> annotationsByStereotype,
boolean hasPropertyExpressions,
boolean hasEvaluatedExpressions) {
this.declaredAnnotations = declaredAnnotations;
this.declaredStereotypes = declaredStereotypes;
this.allStereotypes = allStereotypes;
this.allAnnotations = allAnnotations;
this.annotationsByStereotype = annotationsByStereotype;
this.hasPropertyExpressions = hasPropertyExpressions;
this.hasEvaluatedExpressions = hasEvaluatedExpressions;
}
@NonNull
@Override
public AnnotationMetadata getDeclaredMetadata() {
return new DefaultAnnotationMetadata(
this.declaredAnnotations,
this.declaredStereotypes,
null,
null,
annotationsByStereotype,
hasPropertyExpressions
);
}
@Override
public boolean hasPropertyExpressions() {
return hasPropertyExpressions;
}
@Override
public boolean hasEvaluatedExpressions() {
return hasEvaluatedExpressions;
}
@NonNull
@Override
public Map<CharSequence, Object> getDefaultValues(@NonNull String annotation) {
ArgumentUtils.requireNonNull("annotation", annotation);
return AnnotationMetadataSupport.getDefaultValues(annotation);
}
@Override
public boolean isPresent(@NonNull String annotation, @NonNull String member) {
if (allAnnotations == null || StringUtils.isEmpty(annotation)) {
return false;
}
Map<CharSequence, Object> values = allAnnotations.get(annotation);
if (values != null) {
return values.containsKey(member);
}
if (allStereotypes != null) {
values = allStereotypes.get(annotation);
if (values != null) {
return values.containsKey(member);
}
}
return false;
}
@Override
public <E extends Enum<E>> Optional<E> enumValue(@NonNull String annotation, Class<E> enumType) {
return enumValue(annotation, VALUE_MEMBER, enumType, null);
}
@Override
public <E extends Enum<E>> Optional<E> enumValue(@NonNull String annotation, @NonNull String member, Class<E> enumType) {
return enumValue(annotation, member, enumType, null);
}
@Override
public <E extends Enum<E>> Optional<E> enumValue(@NonNull Class<? extends Annotation> annotation, Class<E> enumType) {
return enumValue(annotation, VALUE_MEMBER, enumType);
}
@Override
public <E extends Enum<E>> Optional<E> enumValue(@NonNull Class<? extends Annotation> annotation, @NonNull String member, Class<E> enumType) {
return enumValue(annotation, member, enumType, null);
}
/**
* Retrieve the | DefaultAnnotationMetadata |
java | apache__camel | components/camel-jms/src/test/java/org/apache/camel/component/jms/MapJmsMessageTest.java | {
"start": 1442,
"end": 3198
} | class ____ extends AbstractJMSTest {
@Order(2)
@RegisterExtension
public static CamelContextExtension camelContextExtension = new DefaultCamelContextExtension();
protected CamelContext context;
protected ProducerTemplate template;
protected ConsumerTemplate consumer;
@Override
protected String getComponentName() {
return "activemq";
}
@Test
public void testTextMessage() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(TextMessage.class);
template.sendBody("activemq:queue:MapJmsMessageTest", "Hello World");
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testBytesMessage() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(BytesMessage.class);
template.sendBody("activemq:queue:MapJmsMessageTest", "Hello World".getBytes());
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from("activemq:queue:MapJmsMessageTest?mapJmsMessage=false").to("mock:result");
}
};
}
@Override
public CamelContextExtension getCamelContextExtension() {
return camelContextExtension;
}
@BeforeEach
void setUpRequirements() {
context = camelContextExtension.getContext();
template = camelContextExtension.getProducerTemplate();
consumer = camelContextExtension.getConsumerTemplate();
}
}
| MapJmsMessageTest |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/function/array/AbstractArrayPositionFunction.java | {
"start": 1111,
"end": 2486
} | class ____ extends AbstractSqmSelfRenderingFunctionDescriptor {
public AbstractArrayPositionFunction(TypeConfiguration typeConfiguration) {
super(
"array_position",
new ArgumentTypesValidator(
StandardArgumentsValidators.composite(
StandardArgumentsValidators.between( 2, 3 ),
ArrayAndElementArgumentValidator.DEFAULT_INSTANCE
),
FunctionParameterType.ANY,
FunctionParameterType.ANY,
FunctionParameterType.INTEGER
),
StandardFunctionReturnTypeResolvers.invariant( typeConfiguration.standardBasicTypeForJavaType( Integer.class ) ),
new AbstractFunctionArgumentTypeResolver() {
@Override
public @Nullable MappingModelExpressible<?> resolveFunctionArgumentType(List<? extends SqmTypedNode<?>> arguments, int argumentIndex, SqmToSqlAstConverter converter) {
if ( argumentIndex == 2 ) {
return converter.getCreationContext()
.getTypeConfiguration()
.standardBasicTypeForJavaType( Integer.class );
}
else {
return ArrayAndElementArgumentTypeResolver.DEFAULT_INSTANCE.resolveFunctionArgumentType(
arguments,
argumentIndex,
converter
);
}
}
}
);
}
@Override
public String getArgumentListSignature() {
return "(ARRAY array, OBJECT element[, INTEGER startPosition])";
}
}
| AbstractArrayPositionFunction |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java | {
"start": 2240,
"end": 3278
} | class ____ {
@Captor @Mock ArgumentCaptor<List> missingGenericsField;
}
@Test
public void shouldScreamWhenMoreThanOneMockitoAnnotation() {
try {
MockitoAnnotations.openMocks(new ToManyAnnotations());
fail();
} catch (MockitoException e) {
assertThat(e)
.hasMessageContaining("missingGenericsField")
.hasMessageContaining("multiple Mockito annotations");
}
}
@Test
public void shouldScreamWhenInitializingCaptorsForNullClass() throws Exception {
try {
MockitoAnnotations.openMocks(null);
fail();
} catch (MockitoException e) {
}
}
@Test
public void shouldLookForAnnotatedCaptorsInSuperClasses() throws Exception {
Sub sub = new Sub();
MockitoAnnotations.openMocks(sub);
assertNotNull(sub.getCaptor());
assertNotNull(sub.getBaseCaptor());
assertNotNull(sub.getSuperBaseCaptor());
}
| ToManyAnnotations |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ssl/SSLConfigurationReloader.java | {
"start": 4818,
"end": 6413
} | class ____ implements FileChangesListener {
private final List<SslConfiguration> sslConfigurations;
private final Consumer<SslConfiguration> reloadConsumer;
private ChangeListener(List<SslConfiguration> sslConfigurations, Consumer<SslConfiguration> reloadConsumer) {
this.sslConfigurations = sslConfigurations;
this.reloadConsumer = reloadConsumer;
}
@Override
public void onFileCreated(Path file) {
onFileChanged(file);
}
@Override
public void onFileDeleted(Path file) {
onFileChanged(file);
}
@Override
public void onFileChanged(Path file) {
final long reloadedNanos = System.nanoTime();
final List<String> settingPrefixes = new ArrayList<>(sslConfigurations.size());
for (SslConfiguration sslConfiguration : sslConfigurations) {
if (sslConfiguration.getDependentFiles().contains(file)) {
reloadConsumer.accept(sslConfiguration);
settingPrefixes.add(sslConfiguration.settingPrefix());
}
}
if (settingPrefixes.isEmpty() == false) {
logger.info(
"updated {} ssl contexts in {}ms for prefix names {} using file [{}]",
settingPrefixes.size(),
TimeValue.timeValueNanos(System.nanoTime() - reloadedNanos).millisFrac(),
settingPrefixes,
file
);
}
}
}
}
| ChangeListener |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.