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 | quarkusio__quarkus | integration-tests/main/src/test/java/io/quarkus/it/main/ReflectiveBeanTest.java | {
"start": 197,
"end": 482
} | class ____ {
@Test
public void testReflectiveAccess() {
RestAssured.when().get("/reflective-bean/proxy").then()
.body(is("42"));
RestAssured.when().get("/reflective-bean/subclass").then()
.body(is("42"));
}
}
| ReflectiveBeanTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/fielddata/ordinals/OrdinalsBuilder.java | {
"start": 830,
"end": 1039
} | class ____ build document ID <-> ordinal mapping. Note: Ordinals are
* {@code 1} based monotonically increasing positive integers. {@code 0}
* donates the missing value in this context.
*/
public final | to |
java | spring-projects__spring-boot | module/spring-boot-health/src/test/java/org/springframework/boot/health/autoconfigure/registry/HealthContributorNameGeneratorTests.java | {
"start": 874,
"end": 2857
} | class ____ {
@Test
void withoutStandardSuffixesWhenNameDoesNotEndWithSuffixReturnsName() {
assertThat(HealthContributorNameGenerator.withoutStandardSuffixes().generateContributorName("test"))
.isEqualTo("test");
}
@Test
void withoutStandardSuffixesWhenNameEndsWithSuffixReturnsNewName() {
assertThat(
HealthContributorNameGenerator.withoutStandardSuffixes().generateContributorName("testHealthIndicator"))
.isEqualTo("test");
assertThat(HealthContributorNameGenerator.withoutStandardSuffixes()
.generateContributorName("testHealthContributor")).isEqualTo("test");
}
@Test
void withoutStandardSuffixesWhenNameEndsWithSuffixInDifferentReturnsNewName() {
assertThat(
HealthContributorNameGenerator.withoutStandardSuffixes().generateContributorName("testHEALTHindicator"))
.isEqualTo("test");
assertThat(HealthContributorNameGenerator.withoutStandardSuffixes()
.generateContributorName("testHEALTHcontributor")).isEqualTo("test");
}
@Test
void withoutStandardSuffixesWhenNameContainsSuffixReturnsName() {
assertThat(HealthContributorNameGenerator.withoutStandardSuffixes()
.generateContributorName("testHealthIndicatorTest")).isEqualTo("testHealthIndicatorTest");
assertThat(HealthContributorNameGenerator.withoutStandardSuffixes()
.generateContributorName("testHealthContributorTest")).isEqualTo("testHealthContributorTest");
}
@Test
void withoutSuffixesStripsSuffix() {
HealthContributorNameGenerator generator = HealthContributorNameGenerator.withoutSuffixes("spring", "boot");
assertThat(generator.generateContributorName("testspring")).isEqualTo("test");
assertThat(generator.generateContributorName("tEsTsPrInG")).isEqualTo("tEsT");
assertThat(generator.generateContributorName("springboot")).isEqualTo("spring");
assertThat(generator.generateContributorName("springspring")).isEqualTo("spring");
assertThat(generator.generateContributorName("test")).isEqualTo("test");
}
}
| HealthContributorNameGeneratorTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/SelfSetTest.java | {
"start": 1259,
"end": 1805
} | class ____ {
private void test(TestProtoMessage rhs) {
TestProtoMessage.Builder lhs = TestProtoMessage.newBuilder();
// BUG: Diagnostic contains:
lhs.setMessage(lhs.getMessage());
}
}
""")
.doTest();
}
@Test
public void negativeCase() {
compilationHelper
.addSourceLines(
"Test.java",
"""
import com.google.errorprone.bugpatterns.proto.ProtoTest.TestProtoMessage;
final | Test |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/util/EndConsumerHelper.java | {
"start": 4020,
"end": 5045
} | class ____ the consumer to have a personalized
* error message if the upstream already contains a non-cancelled Subscription.
* @return true if successful, false if the upstream was non null
*/
public static boolean validate(Subscription upstream, Subscription next, Class<?> subscriber) {
Objects.requireNonNull(next, "next is null");
if (upstream != null) {
next.cancel();
if (upstream != SubscriptionHelper.CANCELLED) {
reportDoubleSubscription(subscriber);
}
return false;
}
return true;
}
/**
* Atomically updates the target upstream AtomicReference from null to the non-null
* next Subscription, otherwise cancels next and reports a ProtocolViolationException
* if the AtomicReference doesn't contain the shared cancelled indicator.
* @param upstream the target AtomicReference to update
* @param next the Subscription to set on it atomically
* @param subscriber the | of |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/overloading/ParameterOrderingViolation.java | {
"start": 1585,
"end": 3212
} | class ____ {
abstract Builder setMethodTree(MethodTree methodTree);
abstract Builder setActual(ImmutableList<ParameterTree> actual);
abstract Builder setExpected(ImmutableList<ParameterTree> expected);
abstract ParameterOrderingViolation autoBuild();
public ParameterOrderingViolation build() {
ParameterOrderingViolation orderingViolation = autoBuild();
int actualParametersCount = orderingViolation.actual().size();
int expectedParameterCount = orderingViolation.expected().size();
Preconditions.checkState(actualParametersCount == expectedParameterCount);
return orderingViolation;
}
}
static ParameterOrderingViolation.Builder builder() {
return new AutoBuilder_ParameterOrderingViolation_Builder();
}
/**
* Provides a violation description with suggested parameter ordering.
*
* <p>An automated {@link SuggestedFix} is not returned with the description because it is not
* safe: reordering the parameters can break the build (if we are lucky) or - in case of
* reordering parameters with the same types - break runtime behaviour of the program.
*/
public String getDescription() {
return "The parameters of this method are inconsistent with other overloaded versions."
+ " A consistent order would be: "
+ getSuggestedSignature();
}
private String getSuggestedSignature() {
return String.format("%s(%s)", methodTree().getName(), getSuggestedParameters());
}
private String getSuggestedParameters() {
return expected().stream().map(ParameterTree::toString).collect(joining(", "));
}
}
| Builder |
java | elastic__elasticsearch | libs/entitlement/src/main/java/org/elasticsearch/entitlement/initialization/EntitlementInitialization.java | {
"start": 2939,
"end": 4639
} | class ____
*/
public static void initialize(Instrumentation inst) {
try {
// the checker _MUST_ be set before _any_ instrumentation is done
checker = initChecker(initializeArgs.policyManager());
initInstrumentation(inst);
} catch (Exception e) {
// exceptions thrown within the agent will be swallowed, so capture it here
// instead so that it can be retrieved by bootstrap
error.set(new RuntimeException("Failed to initialize entitlements", e));
}
}
/**
* Arguments to {@link #initialize}. Since that's called in a static context from the agent,
* we have no way to pass arguments directly, so we stuff them in here.
*
* @param pathLookup
* @param suppressFailureLogPackages
* @param policyManager
*/
public record InitializeArgs(PathLookup pathLookup, Set<Package> suppressFailureLogPackages, PolicyManager policyManager) {
public InitializeArgs {
requireNonNull(pathLookup);
requireNonNull(suppressFailureLogPackages);
requireNonNull(policyManager);
}
}
private static PolicyCheckerImpl createPolicyChecker(PolicyManager policyManager) {
return new PolicyCheckerImpl(
initializeArgs.suppressFailureLogPackages(),
ENTITLEMENTS_MODULE,
policyManager,
initializeArgs.pathLookup()
);
}
/**
* If bytecode verification is enabled, ensure these classes get loaded before transforming/retransforming them.
* For these classes, the order in which we transform and verify them matters. Verification during | instance |
java | apache__camel | components/camel-coap/src/generated/java/org/apache/camel/coap/CoAPEndpointUriFactory.java | {
"start": 504,
"end": 3021
} | class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory {
private static final String BASE = "coaps+tcp:uri";
private static final String[] SCHEMES = new String[]{"coap", "coaps", "coap+tcp", "coaps+tcp"};
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<>(18);
props.add("advancedCertificateVerifier");
props.add("advancedPskStore");
props.add("alias");
props.add("bridgeErrorHandler");
props.add("cipherSuites");
props.add("clientAuthentication");
props.add("coapMethodRestrict");
props.add("exceptionHandler");
props.add("exchangePattern");
props.add("lazyStartProducer");
props.add("notify");
props.add("observable");
props.add("observe");
props.add("privateKey");
props.add("publicKey");
props.add("recommendedCipherSuitesOnly");
props.add("sslContextParameters");
props.add("uri");
PROPERTY_NAMES = Collections.unmodifiableSet(props);
Set<String> secretProps = new HashSet<>(1);
secretProps.add("privateKey");
SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps);
MULTI_VALUE_PREFIXES = Collections.emptyMap();
}
@Override
public boolean isEnabled(String scheme) {
for (String s : SCHEMES) {
if (s.equals(scheme)) {
return true;
}
}
return false;
}
@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, "uri", null, false, 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;
}
}
| CoAPEndpointUriFactory |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/transport/TestTransportChannels.java | {
"start": 723,
"end": 1462
} | class ____ {
public static TcpTransportChannel newFakeTcpTransportChannel(
String nodeName,
TcpChannel channel,
ThreadPool threadPool,
String action,
long requestId,
TransportVersion version
) {
BytesRefRecycler recycler = new BytesRefRecycler(PageCacheRecycler.NON_RECYCLING_INSTANCE);
return new TcpTransportChannel(
new OutboundHandler(nodeName, version, new StatsTracker(), threadPool, recycler, new HandlingTimeTracker(), false),
channel,
action,
requestId,
version,
null,
ResponseStatsConsumer.NONE,
false,
() -> {}
);
}
}
| TestTransportChannels |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng3723ConcreteParentProjectTest.java | {
"start": 1466,
"end": 2260
} | class ____ extends AbstractMavenIntegrationTestCase {
@Test
public void testitMNG3723() throws Exception {
// The testdir is computed from the location of this
// file.
File testDir = extractResources("/mng-3723");
File pluginDir = new File(testDir, "maven-mng3723-plugin");
File projectDir = new File(testDir, "projects");
Verifier verifier;
verifier = newVerifier(pluginDir.getAbsolutePath());
verifier.addCliArgument("install");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier = newVerifier(projectDir.getAbsolutePath());
verifier.addCliArgument("validate");
verifier.execute();
verifier.verifyErrorFreeLog();
}
}
| MavenITmng3723ConcreteParentProjectTest |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/uniquekey/NaturalIdCachingTest.java | {
"start": 2518,
"end": 2872
} | class ____ implements Serializable {
@Id
private Integer id;
@NaturalId
private Integer code;
@NaturalId
private Integer item;
private String description = "A description ...";
protected Property(){}
public Property(Integer id, Integer code, Integer item) {
this.id = id;
this.code = code;
this.item = item;
}
}
}
| Property |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/core/convert/support/StringToNumberConverterFactory.java | {
"start": 1449,
"end": 1698
} | class ____ implements ConverterFactory<String, Number> {
@Override
public <T extends Number> Converter<String, T> getConverter(Class<T> targetType) {
return new StringToNumber<>(targetType);
}
private static final | StringToNumberConverterFactory |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/context/properties/Jackson2BeanSerializer.java | {
"start": 5280,
"end": 5915
} | class ____ extends JacksonAnnotationIntrospector {
@Override
public Object findFilterId(Annotated a) {
Object id = super.findFilterId(a);
return (id != null) ? id : CONFIGURATION_PROPERTIES_FILTER_ID;
}
}
/**
* {@link SimpleBeanPropertyFilter} for serialization of
* {@link ConfigurationProperties @ConfigurationProperties} beans. The filter hides:
*
* <ul>
* <li>Properties that have a name starting with '$$'.
* <li>Properties that are self-referential.
* <li>Properties that throw an exception when retrieving their value.
* </ul>
*/
private static final | ConfigurationPropertiesAnnotationIntrospector |
java | apache__flink | flink-core-api/src/main/java/org/apache/flink/api/java/tuple/builder/Tuple14Builder.java | {
"start": 1268,
"end": 1815
} | class ____ {@link Tuple14}.
*
* @param <T0> The type of field 0
* @param <T1> The type of field 1
* @param <T2> The type of field 2
* @param <T3> The type of field 3
* @param <T4> The type of field 4
* @param <T5> The type of field 5
* @param <T6> The type of field 6
* @param <T7> The type of field 7
* @param <T8> The type of field 8
* @param <T9> The type of field 9
* @param <T10> The type of field 10
* @param <T11> The type of field 11
* @param <T12> The type of field 12
* @param <T13> The type of field 13
*/
@Public
public | for |
java | apache__camel | components/camel-azure/camel-azure-storage-queue/src/test/java/org/apache/camel/component/azure/storage/queue/integration/StorageQueueConsumerIT.java | {
"start": 1297,
"end": 3082
} | class ____ extends StorageQueueBase {
@EndpointInject("mock:result")
private MockEndpoint result;
private String resultName = "mock:result";
@BeforeAll
public void setup() {
serviceClient.getQueueClient(queueName).sendMessage("test-message-1");
serviceClient.getQueueClient(queueName).sendMessage("test-message-2");
serviceClient.getQueueClient(queueName).sendMessage("test-message-3");
}
@Test
public void testPollingMessages() throws InterruptedException {
result.expectedMessageCount(3);
result.assertIsSatisfied();
final List<Exchange> exchanges = result.getExchanges();
result.message(0).exchangeProperty(Exchange.BATCH_INDEX).isEqualTo(0);
result.message(1).exchangeProperty(Exchange.BATCH_INDEX).isEqualTo(1);
result.message(2).exchangeProperty(Exchange.BATCH_INDEX).isEqualTo(2);
result.expectedPropertyReceived(Exchange.BATCH_SIZE, 3);
assertEquals("test-message-1", convertToString(exchanges.get(0)));
assertEquals("test-message-2", convertToString(exchanges.get(1)));
assertEquals("test-message-3", convertToString(exchanges.get(2)));
}
private String convertToString(Exchange exchange) {
InputStream is = exchange.getMessage().getBody(InputStream.class);
assertNotNull(is);
return exchange.getContext().getTypeConverter().convertTo(String.class, is);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("azure-storage-queue://cameldev/" + queueName + "?maxMessages=5")
.to(resultName);
}
};
}
}
| StorageQueueConsumerIT |
java | spring-projects__spring-boot | module/spring-boot-cassandra/src/main/java/org/springframework/boot/cassandra/autoconfigure/CassandraProperties.java | {
"start": 4738,
"end": 5258
} | class ____ {
/**
* Whether to enable SSL support.
*/
private @Nullable Boolean enabled;
/**
* SSL bundle name.
*/
private @Nullable String bundle;
public boolean isEnabled() {
return (this.enabled != null) ? this.enabled : this.bundle != null;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
public static | Ssl |
java | google__truth | core/src/test/java/com/google/common/truth/GraphMatchingTest.java | {
"start": 5483,
"end": 10143
} | class ____ {
/** Generates a test instance with an empty bipartite graph. */
static TestInstance empty() {
return new TestInstance(ImmutableListMultimap.of());
}
/**
* Generates a test instance with a fully-connected bipartite graph where there are {@code
* lhsSize} elements in one set of vertices (which we call the LHS) and {@code rhsSize} elements
* in the other (the RHS).
*/
static TestInstance fullyConnected(int lhsSize, int rhsSize) {
ImmutableListMultimap.Builder<String, String> edges = ImmutableListMultimap.builder();
for (int lhs = 0; lhs < lhsSize; lhs++) {
for (int rhs = 0; rhs < rhsSize; rhs++) {
edges.put("L" + lhs, "R" + rhs);
}
}
return new TestInstance(edges.build());
}
/**
* Generates a test instance with a bipartite graph where there are {@code lhsSize} elements in
* one set of vertices (which we call the LHS) and {@code rhsSize} elements in the other (the
* RHS) and whether or not each of the {@code lhsSize * rhsSize} possible edges is included or
* not according to whether one of the first {@code lhsSize * rhsSize} bits of {@code bits} is
* set or not.
*/
static TestInstance fromBits(int lhsSize, int rhsSize, BitSet bits) {
ImmutableListMultimap.Builder<String, String> edges = ImmutableListMultimap.builder();
for (int lhs = 0; lhs < lhsSize; lhs++) {
for (int rhs = 0; rhs < rhsSize; rhs++) {
if (bits.get(lhs * rhsSize + rhs)) {
edges.put("L" + lhs, "R" + rhs);
}
}
}
return new TestInstance(edges.build());
}
private final ImmutableListMultimap<String, String> edges;
private final ImmutableList<String> lhsVertices;
private TestInstance(ImmutableListMultimap<String, String> edges) {
this.edges = edges;
this.lhsVertices = edges.keySet().asList();
}
/**
* Finds the maximum bipartite matching using the method under test and asserts both that it is
* actually a matching of this bipartite graph and that it has the same size as a maximum
* bipartite matching found by a brute-force approach.
*/
void testAgainstBruteForce() {
ImmutableBiMap<String, String> actual = maximumCardinalityBipartiteMatching(edges);
for (Map.Entry<String, String> entry : actual.entrySet()) {
assertWithMessage(
"The returned bimap <%s> was not a matching of the bipartite graph <%s>",
actual, edges)
.that(edges)
.containsEntry(entry.getKey(), entry.getValue());
}
ImmutableBiMap<String, String> expected = bruteForceMaximalMatching();
assertWithMessage(
"The returned matching for the bipartite graph <%s> was not the same size as "
+ "the brute-force maximal matching <%s>",
edges, expected)
.that(actual)
.hasSize(expected.size());
}
/**
* Finds the maximum bipartite matching using the method under test and asserts both that it is
* actually a matching of this bipartite graph and that it has the expected size.
*/
void testAgainstKnownSize(int expectedSize) {
ImmutableBiMap<String, String> actual = maximumCardinalityBipartiteMatching(edges);
for (Map.Entry<String, String> entry : actual.entrySet()) {
assertWithMessage(
"The returned bimap <%s> was not a matching of the bipartite graph <%s>",
actual, edges)
.that(edges)
.containsEntry(entry.getKey(), entry.getValue());
}
assertWithMessage(
"The returned matching for the bipartite graph <%s> had the wrong size", edges)
.that(actual)
.hasSize(expectedSize);
}
/**
* Returns a maximal bipartite matching of the bipartite graph, performing a brute force
* evaluation of every possible matching.
*/
private ImmutableBiMap<String, String> bruteForceMaximalMatching() {
ImmutableBiMap<String, String> best = ImmutableBiMap.of();
Matching candidate = new Matching();
while (candidate.valid()) {
if (candidate.size() > best.size()) {
best = candidate.asBiMap();
}
candidate.advance();
}
return best;
}
/**
* Mutable representation of a non-empty matching over the graph. This is a cursor which can be
* advanced through the possible matchings in a fixed sequence. When advanced past the last
* matching in the sequence, this cursor is considered invalid.
*/
private | TestInstance |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/search/query/ThrowingQueryBuilder.java | {
"start": 1224,
"end": 4957
} | class ____ extends AbstractQueryBuilder<ThrowingQueryBuilder> {
public static final String NAME = "throw";
private final long randomUID;
private final RuntimeException failure;
private final int shardId;
private final String index;
/**
* Creates a {@link ThrowingQueryBuilder} with the provided <code>randomUID</code>.
*
* @param randomUID used solely for identification
* @param failure what exception to throw
* @param shardId what shardId to throw the exception. If shardId is less than 0, it will throw for all shards.
*/
public ThrowingQueryBuilder(long randomUID, RuntimeException failure, int shardId) {
super();
this.randomUID = randomUID;
this.failure = failure;
this.shardId = shardId;
this.index = null;
}
/**
* Creates a {@link ThrowingQueryBuilder} with the provided <code>randomUID</code>.
*
* @param randomUID used solely for identification
* @param failure what exception to throw
* @param index what index to throw the exception against (all shards of that index)
*/
public ThrowingQueryBuilder(long randomUID, RuntimeException failure, String index) {
super();
this.randomUID = randomUID;
this.failure = failure;
this.shardId = Integer.MAX_VALUE;
this.index = index;
}
public ThrowingQueryBuilder(StreamInput in) throws IOException {
super(in);
this.randomUID = in.readLong();
this.failure = in.readException();
this.shardId = in.readVInt();
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_10_X)) {
this.index = in.readOptionalString();
} else {
this.index = null;
}
}
@Override
protected void doWriteTo(StreamOutput out) throws IOException {
out.writeLong(randomUID);
out.writeException(failure);
out.writeVInt(shardId);
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_10_X)) {
out.writeOptionalString(index);
}
}
@Override
protected void doXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject(NAME);
builder.endObject();
}
@Override
protected Query doToQuery(SearchExecutionContext context) {
final Query delegate = Queries.newMatchAllQuery();
return new Query() {
@Override
public Weight createWeight(IndexSearcher searcher, ScoreMode scoreMode, float boost) throws IOException {
if (context.getShardId() == shardId || shardId < 0 || context.index().getName().equals(index)) {
throw failure;
}
return delegate.createWeight(searcher, scoreMode, boost);
}
@Override
public String toString(String field) {
return delegate.toString(field);
}
@Override
public boolean equals(Object obj) {
return false;
}
@Override
public int hashCode() {
return 0;
}
@Override
public void visit(QueryVisitor visitor) {
visitor.visitLeaf(this);
}
};
}
@Override
protected boolean doEquals(ThrowingQueryBuilder other) {
return false;
}
@Override
protected int doHashCode() {
return 0;
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public TransportVersion getMinimalSupportedVersion() {
return TransportVersion.zero();
}
}
| ThrowingQueryBuilder |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeDetachTest.java | {
"start": 1144,
"end": 4658
} | class ____ extends RxJavaTest {
@Test
public void doubleSubscribe() {
TestHelper.checkDoubleOnSubscribeMaybe(new Function<Maybe<Object>, MaybeSource<Object>>() {
@Override
public MaybeSource<Object> apply(Maybe<Object> m) throws Exception {
return m.onTerminateDetach();
}
});
}
@Test
public void dispose() {
TestHelper.checkDisposed(PublishProcessor.create().singleElement().onTerminateDetach());
}
@Test
public void onError() {
Maybe.error(new TestException())
.onTerminateDetach()
.test()
.assertFailure(TestException.class);
}
@Test
public void onComplete() {
Maybe.empty()
.onTerminateDetach()
.test()
.assertResult();
}
@Test
public void cancelDetaches() throws Exception {
Disposable d = Disposable.empty();
final WeakReference<Disposable> wr = new WeakReference<>(d);
TestObserver<Object> to = new Maybe<Object>() {
@Override
protected void subscribeActual(MaybeObserver<? super Object> observer) {
observer.onSubscribe(wr.get());
};
}
.onTerminateDetach()
.test();
d = null;
to.dispose();
System.gc();
Thread.sleep(200);
to.assertEmpty();
assertNull(wr.get());
}
@Test
public void completeDetaches() throws Exception {
Disposable d = Disposable.empty();
final WeakReference<Disposable> wr = new WeakReference<>(d);
TestObserver<Integer> to = new Maybe<Integer>() {
@Override
protected void subscribeActual(MaybeObserver<? super Integer> observer) {
observer.onSubscribe(wr.get());
observer.onComplete();
observer.onComplete();
};
}
.onTerminateDetach()
.test();
d = null;
System.gc();
Thread.sleep(200);
to.assertResult();
assertNull(wr.get());
}
@Test
public void errorDetaches() throws Exception {
Disposable d = Disposable.empty();
final WeakReference<Disposable> wr = new WeakReference<>(d);
TestObserver<Integer> to = new Maybe<Integer>() {
@Override
protected void subscribeActual(MaybeObserver<? super Integer> observer) {
observer.onSubscribe(wr.get());
observer.onError(new TestException());
observer.onError(new IOException());
};
}
.onTerminateDetach()
.test();
d = null;
System.gc();
Thread.sleep(200);
to.assertFailure(TestException.class);
assertNull(wr.get());
}
@Test
public void successDetaches() throws Exception {
Disposable d = Disposable.empty();
final WeakReference<Disposable> wr = new WeakReference<>(d);
TestObserver<Integer> to = new Maybe<Integer>() {
@Override
protected void subscribeActual(MaybeObserver<? super Integer> observer) {
observer.onSubscribe(wr.get());
observer.onSuccess(1);
observer.onSuccess(2);
};
}
.onTerminateDetach()
.test();
d = null;
System.gc();
Thread.sleep(200);
to.assertResult(1);
assertNull(wr.get());
}
}
| MaybeDetachTest |
java | spring-projects__spring-boot | buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/build/BuilderMetadata.java | {
"start": 1542,
"end": 5669
} | class ____ extends MappedObject {
private static final String LABEL_NAME = "io.buildpacks.builder.metadata";
private static final String[] EMPTY_MIRRORS = {};
private final Stack stack;
private final List<RunImage> runImages;
private final Lifecycle lifecycle;
private final CreatedBy createdBy;
private final List<BuildpackMetadata> buildpacks;
BuilderMetadata(JsonNode node) {
super(node, MethodHandles.lookup());
this.stack = extractStack();
this.runImages = childrenAt("/images", RunImage::new);
this.lifecycle = extractLifecycle();
this.createdBy = extractCreatedBy();
this.buildpacks = extractBuildpacks(getNode().at("/buildpacks"));
}
private CreatedBy extractCreatedBy() {
CreatedBy result = valueAt("/createdBy", CreatedBy.class);
Assert.state(result != null, "'result' must not be null");
return result;
}
private Lifecycle extractLifecycle() {
Lifecycle result = valueAt("/lifecycle", Lifecycle.class);
Assert.state(result != null, "'result' must not be null");
return result;
}
private Stack extractStack() {
Stack result = valueAt("/stack", Stack.class);
Assert.state(result != null, "'result' must not be null");
return result;
}
private List<BuildpackMetadata> extractBuildpacks(JsonNode node) {
if (node.isEmpty()) {
return Collections.emptyList();
}
List<BuildpackMetadata> entries = new ArrayList<>();
node.forEach((child) -> entries.add(BuildpackMetadata.fromJson(child)));
return entries;
}
/**
* Return stack metadata.
* @return the stack metadata
*/
Stack getStack() {
return this.stack;
}
/**
* Return run images metadata.
* @return the run images metadata
*/
List<RunImage> getRunImages() {
return this.runImages;
}
/**
* Return lifecycle metadata.
* @return the lifecycle metadata
*/
Lifecycle getLifecycle() {
return this.lifecycle;
}
/**
* Return information about who created the builder.
* @return the created by metadata
*/
CreatedBy getCreatedBy() {
return this.createdBy;
}
/**
* Return the buildpacks that are bundled in the builder.
* @return the buildpacks
*/
List<BuildpackMetadata> getBuildpacks() {
return this.buildpacks;
}
/**
* Create an updated copy of this metadata.
* @param update consumer to apply updates
* @return an updated metadata instance
*/
BuilderMetadata copy(Consumer<Update> update) {
return new Update(this).run(update);
}
/**
* Attach this metadata to the given update callback.
* @param update the update used to attach the metadata
*/
void attachTo(ImageConfig.Update update) {
try {
String json = SharedJsonMapper.get().writeValueAsString(getNode());
update.withLabel(LABEL_NAME, json);
}
catch (JacksonException ex) {
throw new IllegalStateException(ex);
}
}
/**
* Factory method to extract {@link BuilderMetadata} from an image.
* @param image the source image
* @return the builder metadata
* @throws IOException on IO error
*/
static BuilderMetadata fromImage(Image image) throws IOException {
Assert.notNull(image, "'image' must not be null");
return fromImageConfig(image.getConfig());
}
/**
* Factory method to extract {@link BuilderMetadata} from image config.
* @param imageConfig the image config
* @return the builder metadata
* @throws IOException on IO error
*/
static BuilderMetadata fromImageConfig(ImageConfig imageConfig) throws IOException {
Assert.notNull(imageConfig, "'imageConfig' must not be null");
String json = imageConfig.getLabels().get(LABEL_NAME);
Assert.state(json != null, () -> "No '" + LABEL_NAME + "' label found in image config labels '"
+ StringUtils.collectionToCommaDelimitedString(imageConfig.getLabels().keySet()) + "'");
return fromJson(json);
}
/**
* Factory method create {@link BuilderMetadata} from some JSON.
* @param json the source JSON
* @return the builder metadata
* @throws IOException on IO error
*/
static BuilderMetadata fromJson(String json) throws IOException {
return new BuilderMetadata(SharedJsonMapper.get().readTree(json));
}
/**
* Stack metadata.
*/
| BuilderMetadata |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/StatementSwitchToExpressionSwitchTest.java | {
"start": 136508,
"end": 137482
} | class ____ {
public int foo(Suit suit) {
int x = 0;
x +=
switch (suit) {
case HEART, DIAMOND -> (((x + 1) * (x * x)) << 1);
case SPADE -> throw new RuntimeException();
case CLUB -> throw new NullPointerException();
};
return x;
}
}
""")
.setArgs(
"-XepOpt:StatementSwitchToExpressionSwitch:EnableAssignmentSwitchConversion",
"-XepOpt:StatementSwitchToExpressionSwitch:EnableDirectConversion=false")
.setFixChooser(StatementSwitchToExpressionSwitchTest::assertOneFixAndChoose)
.doTest();
}
@Test
public void switchByEnum_groupedComments_error() {
// Verify compound assignments (here, *=) with grouped comments
refactoringHelper
.addInputLines(
"Test.java",
"""
| Test |
java | apache__camel | components/camel-platform-http-vertx/src/test/java/org/apache/camel/component/platform/http/vertx/PlatformHttpRestOpenApiConsumerRestDslTest.java | {
"start": 1374,
"end": 10127
} | class ____ {
@Test
public void testRestOpenApi() throws Exception {
final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
try {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
rest().openApi().specification("openapi-v3.json").missingOperation("ignore");
from("direct:getPetById")
.process(e -> {
assertEquals("123", e.getMessage().getHeader("petId"));
})
.setBody().constant("{\"pet\": \"tony the tiger\"}");
}
});
context.start();
given()
.when()
.get("/api/v3/pet/123")
.then()
.statusCode(200)
.body(equalTo("{\"pet\": \"tony the tiger\"}"));
} finally {
context.stop();
}
}
@Test
public void testRestOpenApiDevMode() throws Exception {
final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
// run in developer mode
context.getCamelContextExtension().setProfile("dev");
try {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
rest().openApi("openapi-v3.json");
from("direct:getPetById")
.setBody().constant("{\"pet\": \"tony the tiger\"}");
}
});
context.start();
given()
.when()
.get("/api/v3/pet/123")
.then()
.statusCode(200)
.body(equalTo("{\"pet\": \"tony the tiger\"}"));
} finally {
context.stop();
}
}
@Test
public void testRestOpenApiMock() throws Exception {
final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
try {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
rest().openApi().specification("openapi-v3.json").missingOperation("mock");
from("direct:getPetById")
.setBody().constant("{\"pet\": \"tony the tiger\"}");
}
});
context.start();
given()
.when()
.get("/api/v3/pet/123")
.then()
.statusCode(200)
.body(equalTo("{\"pet\": \"tony the tiger\"}"));
// mocked gives empty response
given()
.when()
.get("/api/v3/pet/findByTags")
.then()
.statusCode(204)
.body(equalTo(""));
} finally {
context.stop();
}
}
@Test
public void testRestOpenApiMissingOperation() throws Exception {
final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
try {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
rest().openApi("openapi-v3.json");
from("direct:getPetById")
.setBody().constant("{\"pet\": \"tony the tiger\"}");
}
});
context.start();
fail();
} catch (IllegalArgumentException e) {
Assertions.assertTrue(
e.getMessage().startsWith("OpenAPI specification has 18 unmapped operations to corresponding routes"));
} finally {
context.stop();
}
}
@Test
public void testRestOpenApiNotFound() throws Exception {
final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
try {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
rest().openApi().specification("openapi-v3.json").missingOperation("ignore");
from("direct:getPetById")
.setBody().constant("{\"pet\": \"tony the tiger\"}");
}
});
context.start();
given()
.when()
.get("/api/v3/pet/123/unknown")
.then()
.statusCode(404);
} finally {
context.stop();
}
}
@Test
public void testRestOpenApiNotAllowed() throws Exception {
final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
try {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
rest().openApi().specification("openapi-v3.json").missingOperation("ignore");
from("direct:getPetById")
.setBody().constant("{\"pet\": \"tony the tiger\"}");
}
});
context.start();
given()
.when()
.put("/api/v3/pet/123")
.then()
.statusCode(405);
} finally {
context.stop();
}
}
@Test
public void testRestOpenApiValidate() throws Exception {
final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
try {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
rest().clientRequestValidation(true).openApi().specification("openapi-v3.json").missingOperation("ignore");
from("direct:updatePet")
.setBody().constant("{\"pet\": \"tony the tiger\"}");
}
});
context.start();
given()
.when()
.put("/api/v3/pet")
.then()
.statusCode(400); // no request body
} finally {
context.stop();
}
}
@Test
public void testRestOpenApiMockData() throws Exception {
final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
try {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
rest().openApi().specification("openapi-v3.json").missingOperation("mock");
}
});
context.start();
given()
.when()
.contentType("application/json")
.get("/api/v3/pet/444")
.then()
.statusCode(200)
.body(equalToCompressingWhiteSpace(
"""
{
"pet": "donald the dock"
}"""));
} finally {
context.stop();
}
}
@Test
public void testRestOpenApiContextPath() throws Exception {
final CamelContext context = VertxPlatformHttpEngineTest.createCamelContext();
try {
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
rest().openApi()
.specification("openapi-v3.json")
.apiContextPath("api-doc")
.missingOperation("ignore");
from("direct:getPetById")
.setBody().constant("{\"pet\": \"tony the tiger\"}");
}
});
context.start();
given()
.when()
.get("/api/v3/pet/123")
.then()
.statusCode(200)
.body(equalTo("{\"pet\": \"tony the tiger\"}"));
String spec = IOHelper.loadText(new FileInputStream("src/test/resources/openapi-v3.json"));
given()
.when()
.get("/api/v3/api-doc")
.then()
.statusCode(200)
.contentType("application/json")
.body(equalTo(spec));
} finally {
context.stop();
}
}
}
| PlatformHttpRestOpenApiConsumerRestDslTest |
java | redisson__redisson | redisson/src/main/java/org/redisson/config/ConfigSupport.java | {
"start": 11356,
"end": 14764
} | class ____ extends Property {
private final Method getter;
private final Method setter;
MethodProperty(String name, Method getter, Method setter) {
super(name, getType(getter, setter));
this.getter = getter;
this.setter = setter;
if (getter != null) {
getter.setAccessible(true);
}
if (setter != null) {
setter.setAccessible(true);
}
}
private static Class<?> getType(Method getter, Method setter) {
if (getter != null) {
return getter.getReturnType();
}
if (setter != null) {
return setter.getParameterTypes()[0];
}
return Object.class;
}
@Override
public Class<?>[] getActualTypeArguments() {
if (getter != null) {
Type returnType = getter.getGenericReturnType();
if (returnType instanceof ParameterizedType) {
Type[] types = ((ParameterizedType) returnType).getActualTypeArguments();
Class<?>[] classes = new Class<?>[types.length];
for (int i = 0; i < types.length; i++) {
if (types[i] instanceof Class) {
classes[i] = (Class<?>) types[i];
} else {
classes[i] = Object.class;
}
}
return classes;
}
}
return new Class<?>[0];
}
@Override
public void set(Object object, Object value) throws Exception {
if (setter != null) {
setter.invoke(object, value);
}
}
@Override
public Object get(Object object) {
if (getter != null) {
try {
return getter.invoke(object);
} catch (Exception e) {
throw new IllegalStateException("Failed to get property: " + getName() + " from " + object.getClass(), e);
}
}
return null;
}
@Override
public List<java.lang.annotation.Annotation> getAnnotations() {
List<java.lang.annotation.Annotation> annotations = new ArrayList<>();
if (getter != null) {
annotations.addAll(Arrays.asList(getter.getAnnotations()));
}
if (setter != null) {
annotations.addAll(Arrays.asList(setter.getAnnotations()));
}
return annotations;
}
@Override
public <A extends java.lang.annotation.Annotation> A getAnnotation(Class<A> annotationType) {
if (getter != null) {
A annotation = getter.getAnnotation(annotationType);
if (annotation != null) {
return annotation;
}
}
if (setter != null) {
return setter.getAnnotation(annotationType);
}
return null;
}
@Override
public boolean isWritable() {
return setter != null;
}
@Override
public boolean isReadable() {
return getter != null;
}
}
private static | MethodProperty |
java | quarkusio__quarkus | integration-tests/main/src/test/java/io/quarkus/it/main/JaxRsConstructorPropertiesTestCase.java | {
"start": 307,
"end": 1266
} | class ____ {
@Test
public void testReturnedDirectly() {
when().get("/constructorproperties/direct").then()
.body("name", is("direct"),
"value", is("directvalue"));
}
@Test
public void testConvertedWithJsonbAndReturnedAsString() {
when().get("/constructorproperties/jsonb").then()
.body("name", is("jsonb"),
"value", is("jsonbvalue"));
}
@Test
public void testWrappedInResponse() {
when().get("/constructorproperties/response").then()
.body("name", is("response"),
"value", is("responsevalue"));
}
@Test
public void testWrappedInServerSentEventMessage() {
when().get("/constructorproperties/sse").then().body(containsString("ssevalue"));
}
private static RequestSender when() {
return RestAssured.when();
}
}
| JaxRsConstructorPropertiesTestCase |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/flush/HibernateAutoFlushTest.java | {
"start": 1712,
"end": 2019
} | class ____ {
@Id
@GeneratedValue
private Long id;
private String name;
public Person() {}
public Person(String name) {
this.name = name;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
}
@Entity(name = "Advertisement")
public static | Person |
java | apache__avro | lang/java/perf/src/main/java/org/apache/avro/perf/test/basic/SmallLongTest.java | {
"start": 1314,
"end": 2168
} | class ____ {
@Benchmark
@OperationsPerInvocation(BasicState.BATCH_SIZE)
public void encode(final TestStateEncode state) throws Exception {
final Encoder e = state.encoder;
for (int i = 0; i < state.getBatchSize(); i += 4) {
e.writeLong(state.testData[i + 0]);
e.writeLong(state.testData[i + 1]);
e.writeLong(state.testData[i + 2]);
e.writeLong(state.testData[i + 3]);
}
}
@Benchmark
@OperationsPerInvocation(BasicState.BATCH_SIZE)
public int decode(final TestStateDecode state) throws Exception {
final Decoder d = state.decoder;
int total = 0;
for (int i = 0; i < state.getBatchSize(); i += 4) {
total += d.readLong();
total += d.readLong();
total += d.readLong();
total += d.readLong();
}
return total;
}
@State(Scope.Thread)
public static | SmallLongTest |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeOnErrorNext.java | {
"start": 3524,
"end": 4415
} | class ____<T> implements MaybeObserver<T> {
final MaybeObserver<? super T> downstream;
final AtomicReference<Disposable> upstream;
NextMaybeObserver(MaybeObserver<? super T> actual, AtomicReference<Disposable> d) {
this.downstream = actual;
this.upstream = d;
}
@Override
public void onSubscribe(Disposable d) {
DisposableHelper.setOnce(this.upstream, d);
}
@Override
public void onSuccess(T value) {
downstream.onSuccess(value);
}
@Override
public void onError(Throwable e) {
downstream.onError(e);
}
@Override
public void onComplete() {
downstream.onComplete();
}
}
}
}
| NextMaybeObserver |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ExplicitColumnNamingTest.java | {
"start": 826,
"end": 1031
} | class ____ {
@Id
private Integer id;
private String sku;
private String name;
@Column(name = "NOTES")
private String description;
}
//end::basic-annotation-explicit-column-example[]
}
| Product |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/records/RecordCreatorWithAnySetterTest.java | {
"start": 579,
"end": 2806
} | class ____
extends DatabindTestUtil
{
record RecordWithAnySetterCtor562(int id,
Map<String, Integer> additionalProperties) {
@JsonCreator
public RecordWithAnySetterCtor562(@JsonProperty("regular") int id,
@JsonAnySetter Map<String, Integer> additionalProperties
) {
this.id = id;
this.additionalProperties = additionalProperties;
}
}
record TestRecord3439(
@JsonProperty String field,
@JsonAnySetter Map<String, Object> anySetter
) {}
/*
/**********************************************************************
/* Test methods, alternate constructors
/**********************************************************************
*/
private final ObjectMapper MAPPER = newJsonMapper();
// [databind#562]
@Test
public void testRecordWithAnySetterCtor() throws Exception
{
// First, only regular property mapped
RecordWithAnySetterCtor562 result = MAPPER.readValue(a2q("{'regular':13}"),
RecordWithAnySetterCtor562.class);
assertEquals(13, result.id);
assertEquals(0, result.additionalProperties.size());
// Then with unknown properties
result = MAPPER.readValue(a2q("{'regular':13, 'unknown':99, 'extra':-1}"),
RecordWithAnySetterCtor562.class);
assertEquals(13, result.id);
assertEquals(Integer.valueOf(99), result.additionalProperties.get("unknown"));
assertEquals(Integer.valueOf(-1), result.additionalProperties.get("extra"));
assertEquals(2, result.additionalProperties.size());
}
// [databind#3439]
@Test
public void testJsonAnySetterOnRecord() throws Exception {
String json = """
{
"field": "value",
"unmapped1": "value1",
"unmapped2": "value2"
}
""";
TestRecord3439 result = MAPPER.readValue(json, TestRecord3439.class);
assertEquals("value", result.field());
assertEquals(Map.of("unmapped1", "value1", "unmapped2", "value2"),
result.anySetter());
}
}
| RecordCreatorWithAnySetterTest |
java | apache__commons-lang | src/test/java/org/apache/commons/lang3/ValidateTest.java | {
"start": 33597,
"end": 34135
} | class ____ {
@Test
void shouldNotThrowExceptionWhenStringMatchesPattern() {
Validate.matchesPattern("hi", "[a-z]*", "MSG");
}
@Test
void shouldThrowIllegalArgumentExceptionWhenStringDoesNotMatchPattern() {
final IllegalArgumentException ex = assertIllegalArgumentException(() -> Validate.matchesPattern("hi", "[0-9]*", "MSG"));
assertEquals("MSG", ex.getMessage());
}
}
@Nested
final | WithMessage |
java | apache__spark | examples/src/main/java/org/apache/spark/examples/JavaHdfsLR.java | {
"start": 2454,
"end": 2745
} | class ____ implements Function2<double[], double[], double[]> {
@Override
public double[] call(double[] a, double[] b) {
double[] result = new double[D];
for (int j = 0; j < D; j++) {
result[j] = a[j] + b[j];
}
return result;
}
}
static | VectorSum |
java | resilience4j__resilience4j | resilience4j-rxjava2/src/test/java/io/github/resilience4j/circuitbreaker/operator/CompletableCircuitBreakerTest.java | {
"start": 549,
"end": 2662
} | class ____ extends BaseCircuitBreakerTest {
@Test
public void shouldSubscribeToCompletable() {
given(circuitBreaker.tryAcquirePermission()).willReturn(true);
given(circuitBreaker.getCurrentTimestamp()).willReturn(System.nanoTime());
given(circuitBreaker.getTimestampUnit()).willReturn(TimeUnit.NANOSECONDS);
Completable.complete()
.compose(CircuitBreakerOperator.of(circuitBreaker))
.test()
.assertSubscribed()
.assertComplete();
then(circuitBreaker).should().onSuccess(anyLong(), any(TimeUnit.class));
then(circuitBreaker).should(never())
.onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
}
@Test
public void shouldPropagateAndMarkError() {
given(circuitBreaker.tryAcquirePermission()).willReturn(true);
given(circuitBreaker.getCurrentTimestamp()).willReturn(System.nanoTime());
given(circuitBreaker.getTimestampUnit()).willReturn(TimeUnit.NANOSECONDS);
Completable.error(new IOException("BAM!"))
.compose(CircuitBreakerOperator.of(circuitBreaker))
.test()
.assertSubscribed()
.assertError(IOException.class)
.assertNotComplete();
then(circuitBreaker).should()
.onError(anyLong(), any(TimeUnit.class), any(IOException.class));
then(circuitBreaker).should(never()).onSuccess(anyLong(), any(TimeUnit.class));
}
@Test
public void shouldEmitErrorWithCallNotPermittedException() {
given(circuitBreaker.tryAcquirePermission()).willReturn(false);
Completable.complete()
.compose(CircuitBreakerOperator.of(circuitBreaker))
.test()
.assertSubscribed()
.assertError(CallNotPermittedException.class)
.assertNotComplete();
then(circuitBreaker).should(never()).onSuccess(anyLong(), any(TimeUnit.class));
then(circuitBreaker).should(never())
.onError(anyLong(), any(TimeUnit.class), any(Throwable.class));
}
}
| CompletableCircuitBreakerTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/OnCompletionTest.java | {
"start": 1259,
"end": 3343
} | class ____ extends ContextTestSupport {
@Test
public void testSynchronizeComplete() throws Exception {
getMockEndpoint("mock:sync").expectedBodiesReceived("Bye World");
getMockEndpoint("mock:sync").expectedPropertyReceived(Exchange.ON_COMPLETION, true);
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Bye World");
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Test
public void testSynchronizeFailure() throws Exception {
getMockEndpoint("mock:sync").expectedMessageCount(1);
getMockEndpoint("mock:sync").expectedPropertyReceived(Exchange.ON_COMPLETION, true);
getMockEndpoint("mock:sync").message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT)
.isInstanceOf(IllegalArgumentException.class);
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMessageCount(0);
try {
template.sendBody("direct:start", "Kaboom");
fail("Should throw exception");
} catch (CamelExecutionException e) {
assertEquals("Kaboom", e.getCause().getMessage());
}
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
// START SNIPPET: e1
from("direct:start").onCompletion()
// this route is only invoked when the original route is
// complete as a kind
// of completion callback
.to("log:sync").to("mock:sync")
// must use end to denote the end of the onCompletion route
.end()
// here the original route contiues
.process(new MyProcessor()).to("mock:result");
// END SNIPPET: e1
}
};
}
public static | OnCompletionTest |
java | micronaut-projects__micronaut-core | test-suite/src/test/java/io/micronaut/docs/context/events/application/SampleEventListenerSpec.java | {
"start": 920,
"end": 1453
} | class ____ {
@Test
void testEventListenerIsNotified() {
try (ApplicationContext context = ApplicationContext.run()) {
SampleEventEmitterBean emitter = context.getBean(SampleEventEmitterBean.class);
SampleEventListener listener = context.getBean(SampleEventListener.class);
assertEquals(0, listener.getInvocationCounter());
emitter.publishSampleEvent();
assertEquals(1, listener.getInvocationCounter());
}
}
}
// end::class[]
| SampleEventListenerSpec |
java | quarkusio__quarkus | extensions/smallrye-reactive-messaging/deployment/src/main/java/io/quarkus/smallrye/reactivemessaging/deployment/items/OrphanChannelBuildItem.java | {
"start": 234,
"end": 315
} | class ____ channels that should be managed by connectors.
*/
public final | represents |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/component/proxy/PersonId.java | {
"start": 205,
"end": 618
} | class ____ implements Serializable {
private int id;
private int clientId;
public PersonId() {
}
public PersonId(int aId, int aClientId) {
setId( aId );
setClientId( aClientId );
}
public int getId() {
return id;
}
public void setId(int aId) {
this.id = aId;
}
public int getClientId() {
return clientId;
}
public void setClientId(int aClientId) {
clientId = aClientId;
}
}
| PersonId |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/plugin/EsqlPlugin.java | {
"start": 5097,
"end": 15983
} | class ____ extends Plugin implements ActionPlugin, ExtensiblePlugin, SearchPlugin {
public static final String ESQL_WORKER_THREAD_POOL_NAME = "esql_worker";
public static final Setting<Boolean> QUERY_ALLOW_PARTIAL_RESULTS = Setting.boolSetting(
"esql.query.allow_partial_results",
true,
Setting.Property.NodeScope,
Setting.Property.Dynamic
);
public static final Setting<TimeValue> ESQL_QUERYLOG_THRESHOLD_WARN_SETTING = Setting.timeSetting(
"esql.querylog.threshold.warn",
TimeValue.timeValueMillis(-1),
TimeValue.timeValueMillis(-1),
TimeValue.timeValueMillis(Integer.MAX_VALUE),
Setting.Property.NodeScope,
Setting.Property.Dynamic
);
public static final Setting<TimeValue> ESQL_QUERYLOG_THRESHOLD_INFO_SETTING = Setting.timeSetting(
"esql.querylog.threshold.info",
TimeValue.timeValueMillis(-1),
TimeValue.timeValueMillis(-1),
TimeValue.timeValueMillis(Integer.MAX_VALUE),
Setting.Property.NodeScope,
Setting.Property.Dynamic
);
public static final Setting<TimeValue> ESQL_QUERYLOG_THRESHOLD_DEBUG_SETTING = Setting.timeSetting(
"esql.querylog.threshold.debug",
TimeValue.timeValueMillis(-1),
TimeValue.timeValueMillis(-1),
TimeValue.timeValueMillis(Integer.MAX_VALUE),
Setting.Property.NodeScope,
Setting.Property.Dynamic
);
public static final Setting<TimeValue> ESQL_QUERYLOG_THRESHOLD_TRACE_SETTING = Setting.timeSetting(
"esql.querylog.threshold.trace",
TimeValue.timeValueMillis(-1),
TimeValue.timeValueMillis(-1),
TimeValue.timeValueMillis(Integer.MAX_VALUE),
Setting.Property.NodeScope,
Setting.Property.Dynamic
);
public static final Setting<Boolean> ESQL_QUERYLOG_INCLUDE_USER_SETTING = Setting.boolSetting(
"esql.querylog.include.user",
false,
Setting.Property.NodeScope,
Setting.Property.Dynamic
);
/**
* Tuning parameter for deciding when to use the "merge" stored field loader.
* Think of it as "how similar to a sequential block of documents do I have to
* be before I'll use the merge reader?" So a value of {@code 1} means I have to
* be <strong>exactly</strong> a sequential block, like {@code 0, 1, 2, 3, .. 1299, 1300}.
* A value of {@code .2} means we'll use the sequential reader even if we only
* need one in ten documents.
* <p>
* The default value of this was experimentally derived using a
* <a href="https://gist.github.com/nik9000/ac6857de10745aad210b6397915ff846">script</a>.
* And a little paranoia. A lower default value was looking good locally, but
* I'm concerned about the implications of effectively using this all the time.
* </p>
*/
public static final Setting<Double> STORED_FIELDS_SEQUENTIAL_PROPORTION = Setting.doubleSetting(
"index.esql.stored_fields_sequential_proportion",
0.20,
0,
1,
Setting.Property.IndexScope,
Setting.Property.Dynamic
);
private final List<PlanCheckerProvider> extraCheckerProviders = new ArrayList<>();
@Override
public Collection<?> createComponents(PluginServices services) {
CircuitBreaker circuitBreaker = services.indicesService().getBigArrays().breakerService().getBreaker("request");
Objects.requireNonNull(circuitBreaker, "request circuit breaker wasn't set");
Settings settings = services.clusterService().getSettings();
ByteSizeValue maxPrimitiveArrayBlockSize = settings.getAsBytesSize(
BlockFactory.MAX_BLOCK_PRIMITIVE_ARRAY_SIZE_SETTING,
BlockFactory.DEFAULT_MAX_BLOCK_PRIMITIVE_ARRAY_SIZE
);
BigArrays bigArrays = services.indicesService().getBigArrays().withCircuitBreaking();
var blockFactoryProvider = blockFactoryProvider(circuitBreaker, bigArrays, maxPrimitiveArrayBlockSize);
List<BiConsumer<LogicalPlan, Failures>> extraCheckers = extraCheckerProviders.stream()
.flatMap(p -> p.checkers(services.projectResolver(), services.clusterService()).stream())
.toList();
return List.of(
new PlanExecutor(
new IndexResolver(services.client()),
services.telemetryProvider().getMeterRegistry(),
getLicenseState(),
new EsqlQueryLog(services.clusterService().getClusterSettings(), services.slowLogFieldProvider()),
extraCheckers
),
new ExchangeService(
services.clusterService().getSettings(),
services.threadPool(),
ThreadPool.Names.SEARCH,
blockFactoryProvider.blockFactory()
),
blockFactoryProvider
);
}
protected BlockFactoryProvider blockFactoryProvider(CircuitBreaker breaker, BigArrays bigArrays, ByteSizeValue maxPrimitiveArraySize) {
return new BlockFactoryProvider(new BlockFactory(breaker, bigArrays, maxPrimitiveArraySize));
}
// to be overriden by tests
protected XPackLicenseState getLicenseState() {
return XPackPlugin.getSharedLicenseState();
}
/**
* The settings defined by the ESQL plugin.
*
* @return the settings
*/
@Override
public List<Setting<?>> getSettings() {
return List.of(
AnalyzerSettings.QUERY_RESULT_TRUNCATION_DEFAULT_SIZE,
AnalyzerSettings.QUERY_RESULT_TRUNCATION_MAX_SIZE,
AnalyzerSettings.QUERY_TIMESERIES_RESULT_TRUNCATION_DEFAULT_SIZE,
AnalyzerSettings.QUERY_TIMESERIES_RESULT_TRUNCATION_MAX_SIZE,
QUERY_ALLOW_PARTIAL_RESULTS,
ESQL_QUERYLOG_THRESHOLD_TRACE_SETTING,
ESQL_QUERYLOG_THRESHOLD_DEBUG_SETTING,
ESQL_QUERYLOG_THRESHOLD_INFO_SETTING,
ESQL_QUERYLOG_THRESHOLD_WARN_SETTING,
ESQL_QUERYLOG_INCLUDE_USER_SETTING,
PlannerSettings.DEFAULT_DATA_PARTITIONING,
PlannerSettings.VALUES_LOADING_JUMBO_SIZE,
PlannerSettings.LUCENE_TOPN_LIMIT,
PlannerSettings.INTERMEDIATE_LOCAL_RELATION_MAX_SIZE,
PlannerSettings.REDUCTION_LATE_MATERIALIZATION,
STORED_FIELDS_SEQUENTIAL_PROPORTION,
EsqlFlags.ESQL_STRING_LIKE_ON_INDEX,
EsqlFlags.ESQL_ROUNDTO_PUSHDOWN_THRESHOLD
);
}
@Override
public List<ActionHandler> getActions() {
return List.of(
new ActionHandler(EsqlQueryAction.INSTANCE, TransportEsqlQueryAction.class),
new ActionHandler(EsqlAsyncGetResultAction.INSTANCE, TransportEsqlAsyncGetResultsAction.class),
new ActionHandler(EsqlStatsAction.INSTANCE, TransportEsqlStatsAction.class),
new ActionHandler(XPackUsageFeatureAction.ESQL, EsqlUsageTransportAction.class),
new ActionHandler(XPackInfoFeatureAction.ESQL, EsqlInfoTransportAction.class),
new ActionHandler(EsqlResolveFieldsAction.TYPE, EsqlResolveFieldsAction.class),
new ActionHandler(EsqlSearchShardsAction.TYPE, EsqlSearchShardsAction.class),
new ActionHandler(EsqlAsyncStopAction.INSTANCE, TransportEsqlAsyncStopAction.class),
new ActionHandler(EsqlListQueriesAction.INSTANCE, TransportEsqlListQueriesAction.class),
new ActionHandler(EsqlGetQueryAction.INSTANCE, TransportEsqlGetQueryAction.class)
);
}
@Override
public List<RestHandler> getRestHandlers(
Settings settings,
NamedWriteableRegistry namedWriteableRegistry,
RestController restController,
ClusterSettings clusterSettings,
IndexScopedSettings indexScopedSettings,
SettingsFilter settingsFilter,
IndexNameExpressionResolver indexNameExpressionResolver,
Supplier<DiscoveryNodes> nodesInCluster,
Predicate<NodeFeature> clusterSupportsFeature
) {
return List.of(
new RestEsqlQueryAction(),
new RestEsqlAsyncQueryAction(),
new RestEsqlGetAsyncResultAction(),
new RestEsqlStopAsyncAction(),
new RestEsqlDeleteAsyncResultAction(),
new RestEsqlListQueriesAction()
);
}
@Override
public List<NamedWriteableRegistry.Entry> getNamedWriteables() {
List<NamedWriteableRegistry.Entry> entries = new ArrayList<>();
entries.add(DriverStatus.ENTRY);
entries.add(AbstractPageMappingOperator.Status.ENTRY);
entries.add(AbstractPageMappingToIteratorOperator.Status.ENTRY);
entries.add(AggregationOperator.Status.ENTRY);
entries.add(EsqlQueryStatus.ENTRY);
entries.add(ExchangeSinkOperator.Status.ENTRY);
entries.add(ExchangeSourceOperator.Status.ENTRY);
entries.add(HashAggregationOperator.Status.ENTRY);
entries.add(LimitOperator.Status.ENTRY);
entries.add(LuceneOperator.Status.ENTRY);
entries.add(TopNOperatorStatus.ENTRY);
entries.add(MvExpandOperator.Status.ENTRY);
entries.add(ValuesSourceReaderOperatorStatus.ENTRY);
entries.add(SingleValueQuery.ENTRY);
entries.add(AsyncOperator.Status.ENTRY);
entries.add(EnrichLookupOperator.Status.ENTRY);
entries.add(LookupFromIndexOperator.Status.ENTRY);
entries.add(SampleOperator.Status.ENTRY);
entries.add(LinearScoreEvalOperator.Status.ENTRY);
entries.add(ExpressionQueryBuilder.ENTRY);
entries.add(PlanStreamWrapperQueryBuilder.ENTRY);
entries.addAll(ExpressionWritables.getNamedWriteables());
entries.addAll(PlanWritables.getNamedWriteables());
return entries;
}
public List<ExecutorBuilder<?>> getExecutorBuilders(Settings settings) {
final int allocatedProcessors = EsExecutors.allocatedProcessors(settings);
return List.of(
// TODO: Maybe have two types of threadpools for workers: one for CPU-bound and one for I/O-bound tasks.
// And we should also reduce the number of threads of the CPU-bound threadpool to allocatedProcessors.
new FixedExecutorBuilder(
settings,
ESQL_WORKER_THREAD_POOL_NAME,
ThreadPool.searchOrGetThreadPoolSize(allocatedProcessors),
1000,
ESQL_WORKER_THREAD_POOL_NAME,
EsExecutors.TaskTrackingConfig.DEFAULT
)
);
}
@Override
public void loadExtensions(ExtensionLoader loader) {
extraCheckerProviders.addAll(loader.loadExtensions(PlanCheckerProvider.class));
}
@Override
public List<SearchPlugin.GenericNamedWriteableSpec> getGenericNamedWriteables() {
return ExpressionWritables.getGenericNamedWriteables();
}
}
| EsqlPlugin |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/where/annotations/LazyElementCollectionBasicNonUniqueIdWhereTest.java | {
"start": 7149,
"end": 8513
} | class ____ {
private int id;
private String name;
private Set<String> sizesFromCombined = new HashSet<>();
private List<String> mediumOrHighRatingsFromCombined = new ArrayList<>();
private Set<String> ratings = new HashSet<>();
@Id
@Column( name = "ID" )
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column( name = "NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ElementCollection
@CollectionTable(
name = "COLLECTION_TABLE",
joinColumns = { @JoinColumn( name = "MAIN_ID" ) }
)
@Column( name="VAL")
@SQLRestriction("MAIN_CODE='MATERIAL' AND VALUE_CODE='SIZE'")
@Immutable
public Set<String> getSizesFromCombined() {
return sizesFromCombined;
}
public void setSizesFromCombined(Set<String> sizesFromCombined) {
this.sizesFromCombined = sizesFromCombined;
}
@ElementCollection
@CollectionTable(
name = "MATERIAL_RATINGS",
joinColumns = { @JoinColumn( name = "MATERIAL_ID" ) }
)
@Column( name="RATING")
@Immutable
public Set<String> getRatings() {
return ratings;
}
public void setRatings(Set<String> ratings) {
this.ratings = ratings;
}
}
@Entity( name = "Building" )
@Table( name = "MAIN_TABLE" )
@SQLRestriction("CODE = 'BUILDING'" )
public static | Material |
java | spring-projects__spring-boot | module/spring-boot-flyway/src/test/java/org/springframework/boot/flyway/autoconfigure/FlywayAutoConfigurationTests.java | {
"start": 42088,
"end": 42430
} | class ____ {
@Bean
FlywayMigrationInitializer flywayMigrationInitializer(Flyway flyway) {
FlywayMigrationInitializer initializer = new FlywayMigrationInitializer(flyway);
initializer.setOrder(Ordered.HIGHEST_PRECEDENCE);
return initializer;
}
}
@Configuration(proxyBeanMethods = false)
static | CustomFlywayMigrationInitializer |
java | apache__camel | components/camel-opentelemetry-metrics/src/test/java/org/apache/camel/opentelemetry/metrics/integration/messagehistory/ManagedMessageHistoryAutoConfigIT.java | {
"start": 2318,
"end": 6763
} | class ____ extends CamelTestSupport {
@BeforeAll
public static void init() {
// Open telemetry autoconfiguration using an exporter that writes to the console via logging.
// Other possible exporters include 'logging-otlp' and 'otlp'.
System.setProperty("otel.java.global-autoconfigure.enabled", "true");
System.setProperty("otel.metrics.exporter", "console");
System.setProperty("otel.traces.exporter", "none");
System.setProperty("otel.logs.exporter", "none");
System.setProperty("otel.propagators", "tracecontext");
System.setProperty("otel.metric.export.interval", "300");
}
@Override
protected CamelContext createCamelContext() throws Exception {
CamelContext context = super.createCamelContext();
OpenTelemetryMessageHistoryFactory factory = new OpenTelemetryMessageHistoryFactory();
context.setMessageHistoryFactory(factory);
return context;
}
@Test
public void testMessageHistory() throws Exception {
Logger logger = Logger.getLogger(LoggingMetricExporter.class.getName());
MemoryLogHandler handler = new MemoryLogHandler();
logger.addHandler(handler);
int count = 10;
getMockEndpoint("mock:foo").expectedMessageCount(count / 2);
getMockEndpoint("mock:bar").expectedMessageCount(count / 2);
getMockEndpoint("mock:baz").expectedMessageCount(count / 2);
for (int i = 0; i < count; i++) {
if (i % 2 == 0) {
template.sendBody("seda:foo", "Hello " + i);
} else {
template.sendBody("seda:bar", "Hello " + i);
}
}
MockEndpoint.assertIsSatisfied(context);
await().atMost(Duration.ofMillis(1000L)).until(handler::hasLogs);
List<LogRecord> logs = new ArrayList<>(handler.getLogs());
assertFalse(logs.isEmpty(), "No metrics were exported");
int dataCount = 0;
for (LogRecord log : logs) {
if (log.getParameters() != null && log.getParameters().length > 0) {
MetricData metricData = (MetricData) log.getParameters()[0];
assertEquals(DEFAULT_CAMEL_MESSAGE_HISTORY_METER_NAME, metricData.getName());
HistogramPointData hpd = getPointDataForRouteId(metricData, "route1");
assertEquals(count / 2, hpd.getCount());
assertTrue(verifyMetricDataHasNodeId(metricData, "route1", "foo"));
assertTrue(verifyMetricDataHasNodeId(metricData, "route2", "bar"));
assertTrue(verifyMetricDataHasNodeId(metricData, "route2", "baz"));
dataCount++;
}
}
assertTrue(dataCount > 0, "No metric data found");
}
private boolean verifyMetricDataHasNodeId(MetricData metricData, String routeId, String nodeId) {
return metricData.getData().getPoints().stream()
.filter(point -> routeId.equals(getRouteId(point)))
.anyMatch(point -> nodeId.equals(point.getAttributes().get(AttributeKey.stringKey("nodeId"))));
}
private HistogramPointData getPointDataForRouteId(MetricData metricData, String routeId) {
List<PointData> pdList = metricData.getData().getPoints().stream()
.filter(point -> routeId.equals(getRouteId(point)))
.collect(Collectors.toList());
assertEquals(1, pdList.size(), "Should have one metric for routeId " + routeId);
PointData pd = pdList.get(0);
assertInstanceOf(HistogramPointData.class, pd);
return (HistogramPointData) pd;
}
protected String getRouteId(PointData pd) {
Map<AttributeKey<?>, Object> m = pd.getAttributes().asMap();
assertTrue(m.containsKey(AttributeKey.stringKey(ROUTE_ID_ATTRIBUTE)));
return (String) m.get(AttributeKey.stringKey(ROUTE_ID_ATTRIBUTE));
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("seda:foo")
.routeId("route1")
.to("mock:foo").id("foo");
from("seda:bar")
.routeId("route2")
.to("mock:bar").id("bar")
.to("mock:baz").id("baz");
}
};
}
}
| ManagedMessageHistoryAutoConfigIT |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/dynamic/support/ParentTypeAwareTypeInformation.java | {
"start": 269,
"end": 2200
} | class ____<S> extends TypeDiscoverer<S> {
private final TypeDiscoverer<?> parent;
private int hashCode;
/**
* Creates a new {@link ParentTypeAwareTypeInformation}.
*
* @param type must not be {@code null}.
* @param parent must not be {@code null}.
* @param map must not be {@code null}.
*/
protected ParentTypeAwareTypeInformation(Type type, TypeDiscoverer<?> parent, Map<TypeVariable<?>, Type> map) {
super(type, mergeMaps(parent, map));
this.parent = parent;
}
/**
* Merges the type variable maps of the given parent with the new map.
*
* @param parent must not be {@code null}.
* @param map must not be {@code null}.
* @return
*/
private static Map<TypeVariable<?>, Type> mergeMaps(TypeDiscoverer<?> parent, Map<TypeVariable<?>, Type> map) {
Map<TypeVariable<?>, Type> typeVariableMap = new HashMap<TypeVariable<?>, Type>();
typeVariableMap.putAll(map);
typeVariableMap.putAll(parent.getTypeVariableMap());
return typeVariableMap;
}
@Override
protected TypeInformation<?> createInfo(Type fieldType) {
if (parent.getType().equals(fieldType)) {
return parent;
}
return super.createInfo(fieldType);
}
@Override
public boolean equals(Object obj) {
if (!super.equals(obj)) {
return false;
}
if (!this.getClass().equals(obj.getClass())) {
return false;
}
ParentTypeAwareTypeInformation<?> that = (ParentTypeAwareTypeInformation<?>) obj;
return this.parent == null ? that.parent == null : this.parent.equals(that.parent);
}
@Override
public int hashCode() {
if (this.hashCode == 0) {
this.hashCode = super.hashCode() + 31 * parent.hashCode();
}
return this.hashCode;
}
}
| ParentTypeAwareTypeInformation |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy-client/deployment/src/test/java/io/quarkus/restclient/configuration/RestClientProfilesConfigTest.java | {
"start": 292,
"end": 969
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(EchoResource.class,
EchoClient.class, EchoClientWithConfigKey.class))
.withConfigurationResource("profiles-application.properties");
@RestClient
EchoClient echoClient;
@RestClient
EchoClientWithConfigKey shortNameClient;
@Test
public void shouldRespond() {
Assertions.assertEquals("Hello", echoClient.echo("Hello"));
Assertions.assertEquals("Hello", shortNameClient.echo("Hello"));
}
}
| RestClientProfilesConfigTest |
java | apache__camel | components/camel-pqc/src/main/java/org/apache/camel/component/pqc/crypto/kem/PQCDefaultCMCEMaterial.java | {
"start": 1179,
"end": 2690
} | class ____ {
public static final KeyPair keyPair;
public static final KeyGenerator keyGenerator;
public static final KeyPairGenerator generator;
static {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
if (Security.getProvider(BouncyCastlePQCProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastlePQCProvider());
}
try {
generator = prepareKeyPair();
keyPair = generator.generateKeyPair();
keyGenerator = prepareKeyGenerator();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
protected static KeyPairGenerator prepareKeyPair()
throws NoSuchAlgorithmException, NoSuchProviderException, InvalidAlgorithmParameterException {
KeyPairGenerator kpg = KeyPairGenerator.getInstance(PQCKeyEncapsulationAlgorithms.CMCE.getAlgorithm(),
PQCKeyEncapsulationAlgorithms.CMCE.getBcProvider());
kpg.initialize(CMCEParameterSpec.mceliece8192128f, new SecureRandom());
return kpg;
}
protected static KeyGenerator prepareKeyGenerator() throws NoSuchAlgorithmException, NoSuchProviderException {
KeyGenerator kg = KeyGenerator.getInstance(PQCKeyEncapsulationAlgorithms.CMCE.getAlgorithm(),
PQCKeyEncapsulationAlgorithms.CMCE.getBcProvider());
return kg;
}
}
| PQCDefaultCMCEMaterial |
java | quarkusio__quarkus | extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/cors/CORSSecurityTestCase.java | {
"start": 695,
"end": 6035
} | class ____ {
private static final String APP_PROPS = "" +
"quarkus.http.cors.enabled=true\n" +
"quarkus.http.cors.origins=*\n" +
"quarkus.http.cors.methods=GET,OPTIONS,POST\n" +
"quarkus.http.auth.basic=true\n" +
"quarkus.http.auth.policy.r1.roles-allowed=test\n" +
"quarkus.http.auth.permission.roles1.paths=/test\n" +
"quarkus.http.auth.permission.roles1.policy=r1\n";
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(TestIdentityProvider.class, TestIdentityController.class, PathHandler.class)
.addAsResource(new StringAsset(APP_PROPS), "application.properties");
}
});
@BeforeAll
public static void setup() {
TestIdentityController.resetRoles().add("test", "test", "test").add("user", "user", "user");
}
@Test
@DisplayName("Handles a preflight CORS request correctly")
public void corsPreflightTest() {
String origin = "http://custom.origin.quarkus";
String headers = "X-Custom";
given().header("Origin", origin)
.header("Access-Control-Request-Method", "GET")
.header("Access-Control-Request-Headers", headers)
.when()
.options("/test").then()
.statusCode(200)
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Methods", "GET,OPTIONS,POST")
.header("Access-Control-Allow-Headers", headers);
given().header("Origin", origin)
.header("Access-Control-Request-Method", "POST")
.header("Access-Control-Request-Headers", headers)
.when()
.auth().basic("test", "test")
.options("/test").then()
.statusCode(200)
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Methods", "GET,OPTIONS,POST")
.header("Access-Control-Allow-Headers", headers);
given().header("Origin", origin)
.header("Access-Control-Request-Method", "GET")
.header("Access-Control-Request-Headers", headers)
.when()
.auth().basic("test", "wrongpassword")
.options("/test").then()
.statusCode(200)
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Methods", "GET,OPTIONS,POST")
.header("Access-Control-Allow-Headers", headers);
given().header("Origin", origin)
.header("Access-Control-Request-Method", "POST")
.header("Access-Control-Request-Headers", headers)
.when()
.auth().basic("user", "user")
.options("/test").then()
.statusCode(200)
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Methods", "GET,OPTIONS,POST")
.header("Access-Control-Allow-Headers", headers);
given().header("Origin", origin)
.header("Access-Control-Request-Method", "PUT")
.header("Access-Control-Request-Headers", headers)
.when()
.auth().basic("user", "user")
.options("/test").then()
.statusCode(200)
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Methods", "GET,OPTIONS,POST")
.header("Access-Control-Allow-Headers", headers);
}
@Test
@DisplayName("Handles a direct CORS request correctly")
public void corsNoPreflightTest() {
String origin = "http://custom.origin.quarkus";
given().header("Origin", origin)
.when()
.get("/test").then()
.statusCode(401)
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Methods", "GET,OPTIONS,POST");
given().header("Origin", origin)
.when()
.auth().basic("test", "test")
.get("/test").then()
.statusCode(200)
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Methods", "GET,OPTIONS,POST")
.body(Matchers.equalTo("test:/test"));
given().header("Origin", origin)
.when()
.auth().basic("test", "wrongpassword")
.get("/test").then()
.statusCode(401)
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Methods", "GET,OPTIONS,POST");
given().header("Origin", origin)
.when()
.auth().basic("user", "user")
.get("/test").then()
.statusCode(403)
.header("Access-Control-Allow-Origin", origin)
.header("Access-Control-Allow-Methods", "GET,OPTIONS,POST");
}
}
| CORSSecurityTestCase |
java | apache__camel | components/camel-ignite/src/main/java/org/apache/camel/component/ignite/compute/IgniteComputeProducer.java | {
"start": 11838,
"end": 12917
} | class ____ implements IgniteInClosure<IgniteFuture<Object>> {
private static final long serialVersionUID = 7486030906412223384L;
private Exchange exchange;
private AsyncCallback callback;
private static IgniteInCamelClosure create(Exchange exchange, AsyncCallback callback) {
IgniteInCamelClosure answer = new IgniteInCamelClosure();
answer.exchange = exchange;
answer.callback = callback;
return answer;
}
@Override
public void apply(IgniteFuture<Object> future) {
Message in = exchange.getIn();
Message out = exchange.getOut();
MessageHelper.copyHeaders(in, out, true);
Object result = null;
try {
result = future.get();
} catch (Exception e) {
exchange.setException(e);
callback.done(false);
return;
}
exchange.getOut().setBody(result);
callback.done(false);
}
}
}
| IgniteInCamelClosure |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/search/aggregations/bucket/sampler/InternalSampler.java | {
"start": 797,
"end": 1804
} | class ____ extends InternalSingleBucketAggregation {
public static final String NAME = "mapped_sampler";
// InternalSampler and UnmappedSampler share the same parser name, so we use this when identifying the aggregation type
public static final String PARSER_NAME = "sampler";
InternalSampler(String name, long docCount, InternalAggregations subAggregations, Map<String, Object> metadata) {
super(name, docCount, subAggregations, metadata);
}
/**
* Read from a stream.
*/
public InternalSampler(StreamInput in) throws IOException {
super(in);
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public String getType() {
return PARSER_NAME;
}
@Override
protected InternalSingleBucketAggregation newAggregation(String name, long docCount, InternalAggregations subAggregations) {
return new InternalSampler(name, docCount, subAggregations, metadata);
}
}
| InternalSampler |
java | apache__dubbo | dubbo-plugin/dubbo-rest-openapi/src/main/java/org/apache/dubbo/rpc/protocol/tri/rest/support/swagger/WebjarHelper.java | {
"start": 1245,
"end": 2819
} | class ____ {
public static final boolean ENABLED = ClassUtils.isPresent("org.webjars.WebJarVersionLocator");
private static volatile WebjarHelper INSTANCE;
private final WebJarVersionLocator locator = new WebJarVersionLocator();
public static WebjarHelper getInstance() {
if (INSTANCE == null) {
synchronized (WebjarHelper.class) {
if (INSTANCE == null) {
INSTANCE = new WebjarHelper();
}
}
}
return INSTANCE;
}
public HttpResult<?> handleAssets(String webjar, String path) {
try {
byte[] bytes = getWebjarResource(webjar, path);
if (bytes != null) {
return HttpResult.builder()
.header("Cache-Control", "public, max-age=604800")
.body(bytes)
.build();
}
} catch (IOException ignored) {
}
throw new HttpStatusException(HttpStatus.NOT_FOUND.getCode());
}
public boolean hasWebjar(String webjar) {
return locator.version(webjar) != null;
}
private byte[] getWebjarResource(String webjar, String exactPath) throws IOException {
String fullPath = locator.fullPath(webjar, exactPath);
if (fullPath != null) {
InputStream is = WebJarVersionLocator.class.getClassLoader().getResourceAsStream(fullPath);
if (is != null) {
return StreamUtils.readBytes(is);
}
}
return null;
}
}
| WebjarHelper |
java | netty__netty | handler/src/main/java/io/netty/handler/ssl/ReferenceCountedOpenSslEngine.java | {
"start": 120757,
"end": 120998
} | interface ____ package-private
if (!(o instanceof OpenSslInternalSession)) {
return false;
}
return sessionId().equals(((OpenSslInternalSession) o).sessionId());
}
}
private | is |
java | spring-projects__spring-framework | spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DefaultServerRequestTests.java | {
"start": 3274,
"end": 9353
} | class ____ {
private final List<HttpMessageReader<?>> messageReaders = Arrays.asList(
new DecoderHttpMessageReader<>(new JacksonJsonDecoder()),
new DecoderHttpMessageReader<>(StringDecoder.allMimeTypes()));
@Test
void method() {
HttpMethod method = HttpMethod.HEAD;
DefaultServerRequest request = new DefaultServerRequest(
MockServerWebExchange.from(MockServerHttpRequest.method(method, "https://example.com")),
this.messageReaders);
assertThat(request.method()).isEqualTo(method);
}
@Test
void uri() {
URI uri = URI.create("https://example.com");
DefaultServerRequest request = new DefaultServerRequest(
MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, uri)),
this.messageReaders);
assertThat(request.uri()).isEqualTo(uri);
}
@Test
void uriBuilder() throws URISyntaxException {
URI uri = new URI("http", "localhost", "/path", "a=1", null);
DefaultServerRequest request = new DefaultServerRequest(
MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, uri)),
this.messageReaders);
URI result = request.uriBuilder().build();
assertThat(result.getScheme()).isEqualTo("http");
assertThat(result.getHost()).isEqualTo("localhost");
assertThat(result.getPort()).isEqualTo(-1);
assertThat(result.getPath()).isEqualTo("/path");
assertThat(result.getQuery()).isEqualTo("a=1");
}
@Test
void attribute() {
MockServerWebExchange exchange = MockServerWebExchange.from(
MockServerHttpRequest.method(HttpMethod.GET, "https://example.com"));
exchange.getAttributes().put("foo", "bar");
DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders);
assertThat(request.attribute("foo")).contains("bar");
}
@Test
void queryParams() {
DefaultServerRequest request = new DefaultServerRequest(
MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, "https://example.com?foo=bar")),
this.messageReaders);
assertThat(request.queryParam("foo")).contains("bar");
}
@Test
void emptyQueryParam() {
DefaultServerRequest request = new DefaultServerRequest(
MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, "https://example.com?foo")),
this.messageReaders);
assertThat(request.queryParam("foo")).contains("");
}
@Test
void absentQueryParam() {
DefaultServerRequest request = new DefaultServerRequest(
MockServerWebExchange.from(MockServerHttpRequest.method(HttpMethod.GET, "https://example.com?foo")),
this.messageReaders);
assertThat(request.queryParam("bar")).isNotPresent();
}
@Test
void pathVariable() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("https://example.com"));
Map<String, String> pathVariables = Collections.singletonMap("foo", "bar");
exchange.getAttributes().put(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE, pathVariables);
DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders);
assertThat(request.pathVariable("foo")).isEqualTo("bar");
}
@Test
void pathVariableNotFound() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("https://example.com"));
Map<String, String> pathVariables = Collections.singletonMap("foo", "bar");
exchange.getAttributes().put(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE, pathVariables);
DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders);
assertThatIllegalArgumentException().isThrownBy(() ->
request.pathVariable("baz"));
}
@Test
void pathVariables() {
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("https://example.com"));
Map<String, String> pathVariables = Collections.singletonMap("foo", "bar");
exchange.getAttributes().put(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE, pathVariables);
DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders);
assertThat(request.pathVariables()).isEqualTo(pathVariables);
}
@Test
void header() {
HttpHeaders httpHeaders = new HttpHeaders();
List<MediaType> accept =
Collections.singletonList(MediaType.APPLICATION_JSON);
httpHeaders.setAccept(accept);
List<Charset> acceptCharset = Collections.singletonList(StandardCharsets.UTF_8);
httpHeaders.setAcceptCharset(acceptCharset);
long contentLength = 42L;
httpHeaders.setContentLength(contentLength);
MediaType contentType = MediaType.TEXT_PLAIN;
httpHeaders.setContentType(contentType);
InetSocketAddress host = InetSocketAddress.createUnresolved("localhost", 80);
httpHeaders.setHost(host);
List<HttpRange> range = Collections.singletonList(HttpRange.createByteRange(0, 42));
httpHeaders.setRange(range);
DefaultServerRequest request = new DefaultServerRequest(
MockServerWebExchange.from(MockServerHttpRequest
.method(HttpMethod.GET, "https://example.com?foo=bar")
.headers(httpHeaders)),
this.messageReaders);
ServerRequest.Headers headers = request.headers();
assertThat(headers.accept()).isEqualTo(accept);
assertThat(headers.acceptCharset()).isEqualTo(acceptCharset);
assertThat(headers.contentLength()).isEqualTo(OptionalLong.of(contentLength));
assertThat(headers.contentType()).contains(contentType);
assertThat(headers.header(HttpHeaders.CONTENT_TYPE)).containsExactly(MediaType.TEXT_PLAIN_VALUE);
assertThat(headers.firstHeader(HttpHeaders.CONTENT_TYPE)).isEqualTo(MediaType.TEXT_PLAIN_VALUE);
assertThat(headers.asHttpHeaders()).isEqualTo(httpHeaders);
}
@Test
void cookies() {
HttpCookie cookie = new HttpCookie("foo", "bar");
MockServerWebExchange exchange = MockServerWebExchange.from(
MockServerHttpRequest.method(HttpMethod.GET, "https://example.com").cookie(cookie));
DefaultServerRequest request = new DefaultServerRequest(exchange, messageReaders);
MultiValueMap<String, HttpCookie> expected = new LinkedMultiValueMap<>();
expected.add("foo", cookie);
assertThat(request.cookies()).isEqualTo(expected);
}
@Nested
| DefaultServerRequestTests |
java | quarkusio__quarkus | extensions/spring-di/deployment/src/test/java/io/quarkus/spring/di/deployment/SpringDiDisabledTest.java | {
"start": 854,
"end": 940
} | class ____ {
@Inject
Bar bar;
}
@Component
public static | Foo |
java | apache__spark | sql/hive-thriftserver/src/main/java/org/apache/hive/service/cli/operation/GetSchemasOperation.java | {
"start": 1544,
"end": 3730
} | class ____ extends MetadataOperation {
private final String catalogName;
private final String schemaName;
private static final TableSchema RESULT_SET_SCHEMA = new TableSchema()
.addStringColumn("TABLE_SCHEM", "Schema name.")
.addStringColumn("TABLE_CATALOG", "Catalog name.");
protected RowSet rowSet;
protected GetSchemasOperation(HiveSession parentSession,
String catalogName, String schemaName) {
super(parentSession, OperationType.GET_SCHEMAS);
this.catalogName = catalogName;
this.schemaName = schemaName;
this.rowSet = RowSetFactory.create(RESULT_SET_SCHEMA, getProtocolVersion(), false);
}
@Override
public void runInternal() throws HiveSQLException {
setState(OperationState.RUNNING);
if (isAuthV2Enabled()) {
String cmdStr = "catalog : " + catalogName + ", schemaPattern : " + schemaName;
authorizeMetaGets(HiveOperationType.GET_SCHEMAS, null, cmdStr);
}
try {
IMetaStoreClient metastoreClient = getParentSession().getMetaStoreClient();
String schemaPattern = convertSchemaPattern(schemaName);
for (String dbName : metastoreClient.getDatabases(schemaPattern)) {
rowSet.addRow(new Object[] {dbName, DEFAULT_HIVE_CATALOG});
}
setState(OperationState.FINISHED);
} catch (Exception e) {
setState(OperationState.ERROR);
throw new HiveSQLException(e);
}
}
/* (non-Javadoc)
* @see org.apache.hive.service.cli.Operation#getResultSetSchema()
*/
@Override
public TTableSchema getResultSetSchema() throws HiveSQLException {
assertState(OperationState.FINISHED);
return RESULT_SET_SCHEMA.toTTableSchema();
}
/* (non-Javadoc)
* @see org.apache.hive.service.cli.Operation#getNextRowSet(org.apache.hive.service.cli.FetchOrientation, long)
*/
@Override
public TRowSet getNextRowSet(FetchOrientation orientation, long maxRows) throws HiveSQLException {
assertState(OperationState.FINISHED);
validateDefaultFetchOrientation(orientation);
if (orientation.equals(FetchOrientation.FETCH_FIRST)) {
rowSet.setStartOffset(0);
}
return rowSet.extractSubset((int)maxRows).toTRowSet();
}
}
| GetSchemasOperation |
java | spring-projects__spring-boot | module/spring-boot-cloudfoundry/src/test/java/org/springframework/boot/cloudfoundry/autoconfigure/actuate/endpoint/servlet/SecurityServiceTests.java | {
"start": 2367,
"end": 9666
} | class ____ {
private static final String CLOUD_CONTROLLER = "https://my-cloud-controller.com";
private static final String CLOUD_CONTROLLER_PERMISSIONS = CLOUD_CONTROLLER + "/v2/apps/my-app-id/permissions";
private static final String UAA_URL = "https://my-uaa.com";
private SecurityService securityService;
private MockRestServiceServer server;
@BeforeEach
void setup() {
MockServerRestTemplateCustomizer mockServerCustomizer = new MockServerRestTemplateCustomizer();
RestTemplateBuilder builder = new RestTemplateBuilder(mockServerCustomizer);
this.securityService = new SecurityService(builder, CLOUD_CONTROLLER, false);
this.server = mockServerCustomizer.getServer();
}
@Test
void skipSslValidationWhenTrue() {
RestTemplateBuilder builder = new RestTemplateBuilder();
this.securityService = new SecurityService(builder, CLOUD_CONTROLLER, true);
RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate");
assertThat(restTemplate).isNotNull();
assertThat(restTemplate.getRequestFactory()).isInstanceOf(SkipSslVerificationHttpRequestFactory.class);
}
@Test
void doNotSkipSslValidationWhenFalse() {
RestTemplateBuilder builder = new RestTemplateBuilder();
this.securityService = new SecurityService(builder, CLOUD_CONTROLLER, false);
RestTemplate restTemplate = (RestTemplate) ReflectionTestUtils.getField(this.securityService, "restTemplate");
assertThat(restTemplate).isNotNull();
assertThat(restTemplate.getRequestFactory()).isNotInstanceOf(SkipSslVerificationHttpRequestFactory.class);
}
@Test
void getAccessLevelWhenSpaceDeveloperShouldReturnFull() {
String responseBody = "{\"read_sensitive_data\": true,\"read_basic_data\": true}";
this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS))
.andExpect(header("Authorization", "bearer my-access-token"))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", "my-app-id");
this.server.verify();
assertThat(accessLevel).isEqualTo(AccessLevel.FULL);
}
@Test
void getAccessLevelWhenNotSpaceDeveloperShouldReturnRestricted() {
String responseBody = "{\"read_sensitive_data\": false,\"read_basic_data\": true}";
this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS))
.andExpect(header("Authorization", "bearer my-access-token"))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
AccessLevel accessLevel = this.securityService.getAccessLevel("my-access-token", "my-app-id");
this.server.verify();
assertThat(accessLevel).isEqualTo(AccessLevel.RESTRICTED);
}
@Test
void getAccessLevelWhenTokenIsNotValidShouldThrowException() {
this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS))
.andExpect(header("Authorization", "bearer my-access-token"))
.andRespond(withUnauthorizedRequest());
assertThatExceptionOfType(CloudFoundryAuthorizationException.class)
.isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id"))
.satisfies(reasonRequirement(Reason.INVALID_TOKEN));
}
@Test
void getAccessLevelWhenForbiddenShouldThrowException() {
this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS))
.andExpect(header("Authorization", "bearer my-access-token"))
.andRespond(withStatus(HttpStatus.FORBIDDEN));
assertThatExceptionOfType(CloudFoundryAuthorizationException.class)
.isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id"))
.satisfies(reasonRequirement(Reason.ACCESS_DENIED));
}
@Test
void getAccessLevelWhenCloudControllerIsNotReachableThrowsException() {
this.server.expect(requestTo(CLOUD_CONTROLLER_PERMISSIONS))
.andExpect(header("Authorization", "bearer my-access-token"))
.andRespond(withServerError());
assertThatExceptionOfType(CloudFoundryAuthorizationException.class)
.isThrownBy(() -> this.securityService.getAccessLevel("my-access-token", "my-app-id"))
.satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE));
}
@Test
void fetchTokenKeysWhenSuccessfulShouldReturnListOfKeysFromUAA() {
this.server.expect(requestTo(CLOUD_CONTROLLER + "/info"))
.andRespond(withSuccess("{\"token_endpoint\":\"https://my-uaa.com\"}", MediaType.APPLICATION_JSON));
String tokenKeyValue = """
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0m59l2u9iDnMbrXHfqkO
rn2dVQ3vfBJqcDuFUK03d+1PZGbVlNCqnkpIJ8syFppW8ljnWweP7+LiWpRoz0I7
fYb3d8TjhV86Y997Fl4DBrxgM6KTJOuE/uxnoDhZQ14LgOU2ckXjOzOdTsnGMKQB
LCl0vpcXBtFLMaSbpv1ozi8h7DJyVZ6EnFQZUWGdgTMhDrmqevfx95U/16c5WBDO
kqwIn7Glry9n9Suxygbf8g5AzpWcusZgDLIIZ7JTUldBb8qU2a0Dl4mvLZOn4wPo
jfj9Cw2QICsc5+Pwf21fP+hzf+1WSRHbnYv8uanRO0gZ8ekGaghM/2H6gqJbo2nI
JwIDAQAB
-----END PUBLIC KEY-----""";
String responseBody = "{\"keys\" : [ {\"kid\":\"test-key\",\"value\" : \"" + tokenKeyValue.replace("\n", "\\n")
+ "\"} ]}";
this.server.expect(requestTo(UAA_URL + "/token_keys"))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
Map<String, String> tokenKeys = this.securityService.fetchTokenKeys();
this.server.verify();
assertThat(tokenKeys).containsEntry("test-key", tokenKeyValue);
}
@Test
void fetchTokenKeysWhenNoKeysReturnedFromUAA() {
this.server.expect(requestTo(CLOUD_CONTROLLER + "/info"))
.andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON));
String responseBody = "{\"keys\": []}";
this.server.expect(requestTo(UAA_URL + "/token_keys"))
.andRespond(withSuccess(responseBody, MediaType.APPLICATION_JSON));
Map<String, String> tokenKeys = this.securityService.fetchTokenKeys();
this.server.verify();
assertThat(tokenKeys).isEmpty();
}
@Test
void fetchTokenKeysWhenUnsuccessfulShouldThrowException() {
this.server.expect(requestTo(CLOUD_CONTROLLER + "/info"))
.andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON));
this.server.expect(requestTo(UAA_URL + "/token_keys")).andRespond(withServerError());
assertThatExceptionOfType(CloudFoundryAuthorizationException.class)
.isThrownBy(() -> this.securityService.fetchTokenKeys())
.satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE));
}
@Test
void getUaaUrlShouldCallCloudControllerInfoOnlyOnce() {
this.server.expect(requestTo(CLOUD_CONTROLLER + "/info"))
.andRespond(withSuccess("{\"token_endpoint\":\"" + UAA_URL + "\"}", MediaType.APPLICATION_JSON));
String uaaUrl = this.securityService.getUaaUrl();
this.server.verify();
assertThat(uaaUrl).isEqualTo(UAA_URL);
// Second call should not need to hit server
uaaUrl = this.securityService.getUaaUrl();
assertThat(uaaUrl).isEqualTo(UAA_URL);
}
@Test
void getUaaUrlWhenCloudControllerUrlIsNotReachableShouldThrowException() {
this.server.expect(requestTo(CLOUD_CONTROLLER + "/info")).andRespond(withServerError());
assertThatExceptionOfType(CloudFoundryAuthorizationException.class)
.isThrownBy(() -> this.securityService.getUaaUrl())
.satisfies(reasonRequirement(Reason.SERVICE_UNAVAILABLE));
}
private Consumer<CloudFoundryAuthorizationException> reasonRequirement(Reason reason) {
return (ex) -> assertThat(ex.getReason()).isEqualTo(reason);
}
}
| SecurityServiceTests |
java | apache__camel | components/camel-ai/camel-langchain4j-agent-api/src/main/java/org/apache/camel/component/langchain4j/agent/api/AgentFactory.java | {
"start": 956,
"end": 1230
} | interface ____ creating AI agent instances within the Apache Camel LangChain4j integration.
*
* <p>
* This factory provides a standardized way to create and manage AI agents, supporting both agents with memory
* capabilities and stateless agents. Implementations of this | for |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/issue_1400/Issue1486.java | {
"start": 234,
"end": 695
} | class ____ extends TestCase {
public void test_for_issue() throws Exception {
String json = "[{\"song_list\":[{\"val\":1,\"v_al\":2},{\"val\":2,\"v_al\":2},{\"val\":3,\"v_al\":2}],\"songlist\":\"v_al\"}]";
List<Value> parseObject = JSON.parseObject(json, new TypeReference<List<Value>>() {
});
for (Value value : parseObject) {
System.out.println(value.songList + " " );
}
}
public static | Issue1486 |
java | apache__flink | flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/catalog/listener/DropTableEvent.java | {
"start": 1169,
"end": 2200
} | interface ____ extends TableModificationEvent {
boolean ignoreIfNotExists();
static DropTableEvent createEvent(
final CatalogContext context,
final ObjectIdentifier identifier,
@Nullable final CatalogBaseTable table,
final boolean ignoreIfNotExists,
final boolean isTemporary) {
return new DropTableEvent() {
@Override
public boolean ignoreIfNotExists() {
return ignoreIfNotExists;
}
@Override
public ObjectIdentifier identifier() {
return identifier;
}
@Override
@Nullable
public CatalogBaseTable table() {
return table;
}
@Override
public boolean isTemporary() {
return isTemporary;
}
@Override
public CatalogContext context() {
return context;
}
};
}
}
| DropTableEvent |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java | {
"start": 69433,
"end": 69586
} | class ____ {
@Bean
public Repository<Object> genericRepo() {
return new GenericRepository<>();
}
}
public static | SpecificRepositoryConfiguration |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/googlevertexai/rerank/GoogleVertexAiRerankModelTests.java | {
"start": 699,
"end": 2245
} | class ____ extends ESTestCase {
public void testBuildUri() throws URISyntaxException {
var projectId = "project";
URI uri = GoogleVertexAiRerankModel.buildUri(projectId);
assertThat(
uri,
is(
new URI(
Strings.format(
"https://discoveryengine.googleapis.com/v1/projects/%s/locations/global/rankingConfigs/default_ranking_config:rank",
projectId
)
)
)
);
}
public static GoogleVertexAiRerankModel createModel(@Nullable String modelId, @Nullable Integer topN) {
return new GoogleVertexAiRerankModel(
"id",
TaskType.RERANK,
"service",
new GoogleVertexAiRerankServiceSettings(randomAlphaOfLength(10), modelId, null),
new GoogleVertexAiRerankTaskSettings(topN),
new GoogleVertexAiSecretSettings(randomSecureStringOfLength(8))
);
}
public static GoogleVertexAiRerankModel createModel(String url, @Nullable String modelId, @Nullable Integer topN) {
return new GoogleVertexAiRerankModel(
"id",
TaskType.RERANK,
"service",
url,
new GoogleVertexAiRerankServiceSettings(randomAlphaOfLength(10), modelId, null),
new GoogleVertexAiRerankTaskSettings(topN),
new GoogleVertexAiSecretSettings(randomSecureStringOfLength(8))
);
}
}
| GoogleVertexAiRerankModelTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/size/Student.java | {
"start": 413,
"end": 821
} | class ____ {
private Integer id;
private Teacher teacher;
@Id
@Column(name = "student_id")
@GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@ManyToOne(optional = false)
@JoinColumn(name = "teacher_fk_id")
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
}
| Student |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ActiveMQ6EndpointBuilderFactory.java | {
"start": 27084,
"end": 28310
} | class ____ is good enough as
* subscription name). Note that shared subscriptions may also be
* durable, so this flag can (and often will) be combined with
* subscriptionDurable as well. Only makes sense when listening to a
* topic (pub-sub domain), therefore this method switches the
* pubSubDomain flag as well. Requires a JMS 2.0 compatible message
* broker.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer
*
* @param subscriptionShared the value to set
* @return the dsl builder
*/
default ActiveMQ6EndpointConsumerBuilder subscriptionShared(boolean subscriptionShared) {
doSetProperty("subscriptionShared", subscriptionShared);
return this;
}
/**
* Set whether to make the subscription shared. The shared subscription
* name to be used can be specified through the subscriptionName
* property. Default is false. Set this to true to register a shared
* subscription, typically in combination with a subscriptionName value
* (unless your message listener | name |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/factories/TestUpdateDeleteTableFactory.java | {
"start": 26025,
"end": 28973
} | class ____ extends RichSinkFunction<RowData> {
private final String dataId;
private final RowData.FieldGetter[] primaryKeyFieldGetters;
private final RowData.FieldGetter[] allFieldGetters;
private final SupportsRowLevelDelete.RowLevelDeleteMode deleteMode;
private transient Collection<RowData> data;
private transient List<RowData> newData;
DeleteDataSinkFunction(
String dataId,
RowData.FieldGetter[] primaryKeyFieldGetters,
RowData.FieldGetter[] allFieldGetters,
SupportsRowLevelDelete.RowLevelDeleteMode deleteMode) {
this.dataId = dataId;
this.primaryKeyFieldGetters = primaryKeyFieldGetters;
this.allFieldGetters = allFieldGetters;
this.deleteMode = deleteMode;
}
@Override
public void open(OpenContext openContext) {
data = registeredRowData.get(dataId);
newData = new ArrayList<>();
}
@Override
public void invoke(RowData value, Context context) {
if (deleteMode == SupportsRowLevelDelete.RowLevelDeleteMode.DELETED_ROWS) {
consumeDeletedRows(value);
} else if (deleteMode == SupportsRowLevelDelete.RowLevelDeleteMode.REMAINING_ROWS) {
consumeRemainingRows(value);
} else {
throw new TableException(String.format("Unknown delete mode: %s.", deleteMode));
}
}
private void consumeDeletedRows(RowData deletedRow) {
Preconditions.checkState(
deletedRow.getRowKind() == RowKind.DELETE,
String.format(
"The RowKind for the coming rows should be %s in delete mode %s.",
RowKind.DELETE, DELETE_MODE));
data.removeIf(rowData -> equal(rowData, deletedRow, primaryKeyFieldGetters));
}
private void consumeRemainingRows(RowData remainingRow) {
Preconditions.checkState(
remainingRow.getRowKind() == RowKind.INSERT,
String.format(
"The RowKind for the coming rows should be %s in delete mode %s.",
RowKind.INSERT, DELETE_MODE));
// find the row that match the remaining row
for (RowData oldRow : data) {
if (equal(oldRow, remainingRow, primaryKeyFieldGetters)) {
newData.add(copyRowData(oldRow, allFieldGetters));
}
}
}
@Override
public void finish() {
if (deleteMode == SupportsRowLevelDelete.RowLevelDeleteMode.REMAINING_ROWS) {
registeredRowData.put(dataId, newData);
}
}
}
/** A sink that supports delete push down and row-level update. */
public static | DeleteDataSinkFunction |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/common/utils/AllowClassNotifyListener.java | {
"start": 872,
"end": 1180
} | interface ____ {
SerializeCheckStatus DEFAULT_STATUS = SerializeCheckStatus.STRICT;
void notifyPrefix(Set<String> allowedList, Set<String> disAllowedList);
void notifyCheckStatus(SerializeCheckStatus status);
void notifyCheckSerializable(boolean checkSerializable);
}
| AllowClassNotifyListener |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/android/RectIntersectReturnValueIgnoredTest.java | {
"start": 4212,
"end": 4736
} | class ____ {
int left;
int right;
int top;
int bottom;
boolean intersect(int aLeft, int aTop, int aRight, int aBottom) {
throw new RuntimeException("Not implemented");
}
}
void checkHomonym(Rect rect, int aLeft, int aTop, int aRight, int aBottom) {
rect.intersect(aLeft, aTop, aRight, aBottom);
}
}
| Rect |
java | apache__rocketmq | remoting/src/main/java/org/apache/rocketmq/remoting/protocol/header/CreateTopicRequestHeader.java | {
"start": 1673,
"end": 4848
} | class ____ extends TopicRequestHeader {
@CFNotNull
@RocketMQResource(ResourceType.TOPIC)
private String topic;
@CFNotNull
private String defaultTopic;
@CFNotNull
private Integer readQueueNums;
@CFNotNull
private Integer writeQueueNums;
@CFNotNull
private Integer perm;
@CFNotNull
private String topicFilterType;
private Integer topicSysFlag;
@CFNotNull
private Boolean order = false;
private String attributes;
@CFNullable
private Boolean force = false;
@Override
public void checkFields() throws RemotingCommandException {
try {
TopicFilterType.valueOf(this.topicFilterType);
} catch (Exception e) {
throw new RemotingCommandException("topicFilterType = [" + topicFilterType + "] value invalid", e);
}
}
public TopicFilterType getTopicFilterTypeEnum() {
return TopicFilterType.valueOf(this.topicFilterType);
}
public String getTopic() {
return topic;
}
public void setTopic(String topic) {
this.topic = topic;
}
public String getDefaultTopic() {
return defaultTopic;
}
public void setDefaultTopic(String defaultTopic) {
this.defaultTopic = defaultTopic;
}
public Integer getReadQueueNums() {
return readQueueNums;
}
public void setReadQueueNums(Integer readQueueNums) {
this.readQueueNums = readQueueNums;
}
public Integer getWriteQueueNums() {
return writeQueueNums;
}
public void setWriteQueueNums(Integer writeQueueNums) {
this.writeQueueNums = writeQueueNums;
}
public Integer getPerm() {
return perm;
}
public void setPerm(Integer perm) {
this.perm = perm;
}
public String getTopicFilterType() {
return topicFilterType;
}
public void setTopicFilterType(String topicFilterType) {
this.topicFilterType = topicFilterType;
}
public Integer getTopicSysFlag() {
return topicSysFlag;
}
public void setTopicSysFlag(Integer topicSysFlag) {
this.topicSysFlag = topicSysFlag;
}
public Boolean getOrder() {
return order;
}
public void setOrder(Boolean order) {
this.order = order;
}
public Boolean getForce() {
return force;
}
public void setForce(Boolean force) {
this.force = force;
}
public String getAttributes() {
return attributes;
}
public void setAttributes(String attributes) {
this.attributes = attributes;
}
@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("topic", topic)
.add("defaultTopic", defaultTopic)
.add("readQueueNums", readQueueNums)
.add("writeQueueNums", writeQueueNums)
.add("perm", perm)
.add("topicFilterType", topicFilterType)
.add("topicSysFlag", topicSysFlag)
.add("order", order)
.add("attributes", attributes)
.add("force", force)
.toString();
}
}
| CreateTopicRequestHeader |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/JobConf.java | {
"start": 26313,
"end": 26427
} | class ____ should be used to compress the
* map outputs.
* @throws IllegalArgumentException if the | that |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/processor/internals/ProcessorNodePunctuator.java | {
"start": 975,
"end": 1128
} | interface ____ {
void punctuate(ProcessorNode<?, ?, ?, ?> node, long timestamp, PunctuationType type, Punctuator punctuator);
}
| ProcessorNodePunctuator |
java | quarkusio__quarkus | extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/NonApplicationAndRootPathTest.java | {
"start": 2741,
"end": 2849
} | class ____ {
void test(@Observes String event) {
//Do Nothing
}
}
}
| MyObserver |
java | spring-projects__spring-boot | module/spring-boot-cassandra/src/main/java/org/springframework/boot/cassandra/autoconfigure/CqlSessionBuilderCustomizer.java | {
"start": 1067,
"end": 1274
} | interface ____ {
/**
* Customize the {@link CqlSessionBuilder}.
* @param cqlSessionBuilder the builder to customize
*/
void customize(CqlSessionBuilder cqlSessionBuilder);
}
| CqlSessionBuilderCustomizer |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/commons/util/AnnotationUtilsTests.java | {
"start": 27171,
"end": 27250
} | class ____ {
}
@Tag("a")
@Tag("b")
@Tag("c")
static | SingleComposedTaggedClass |
java | apache__camel | components/camel-fhir/camel-fhir-api/src/main/java/org/apache/camel/component/fhir/api/FhirTransaction.java | {
"start": 1225,
"end": 3380
} | class ____ {
private final IGenericClient client;
public FhirTransaction(IGenericClient client) {
this.client = client;
}
/**
* Use a list of resources as the transaction input
*
* @param resources resources to use in the transaction
* @param extraParameters see {@link ExtraParameters} for a full list of parameters that can be passed, may be NULL
* @return the {@link IBaseResource}s
*/
public List<IBaseResource> withResources(List<IBaseResource> resources, Map<ExtraParameters, Object> extraParameters) {
ITransactionTyped<List<IBaseResource>> transactionTyped = client.transaction().withResources(resources);
ExtraParameters.process(extraParameters, transactionTyped);
return transactionTyped.execute();
}
/**
* Use the given Bundle resource as the transaction input
*
* @param bundle bundle to use in the transaction
* @param extraParameters see {@link ExtraParameters} for a full list of parameters that can be passed, may be NULL
* @return the {@link IBaseBundle}
*/
public IBaseBundle withBundle(IBaseBundle bundle, Map<ExtraParameters, Object> extraParameters) {
ITransactionTyped<IBaseBundle> transactionTyped = client.transaction().withBundle(bundle);
ExtraParameters.process(extraParameters, transactionTyped);
return transactionTyped.execute();
}
/**
* Use the given raw text (should be a Bundle resource) as the transaction input
*
* @param stringBundle bundle to use in the transaction
* @param extraParameters see {@link ExtraParameters} for a full list of parameters that can be passed, may be NULL
* @return the {@link IBaseBundle} as string
*/
public String withBundle(String stringBundle, Map<ExtraParameters, Object> extraParameters) {
ITransactionTyped<String> transactionTyped = client.transaction().withBundle(stringBundle);
ExtraParameters.process(extraParameters, transactionTyped);
return transactionTyped.execute();
}
}
| FhirTransaction |
java | square__retrofit | retrofit-converters/wire/src/test/java/retrofit2/converter/wire/Phone.java | {
"start": 2314,
"end": 3766
} | class ____ extends ProtoAdapter<Phone> {
ProtoAdapter_Phone() {
super(FieldEncoding.LENGTH_DELIMITED, Phone.class);
}
@Override
public int encodedSize(Phone value) {
return (value.number != null ? ProtoAdapter.STRING.encodedSizeWithTag(1, value.number) : 0)
+ value.unknownFields().size();
}
@Override
public void encode(ProtoWriter writer, Phone value) throws IOException {
if (value.number != null) ProtoAdapter.STRING.encodeWithTag(writer, 1, value.number);
writer.writeBytes(value.unknownFields());
}
@Override
public Phone decode(ProtoReader reader) throws IOException {
Builder builder = new Builder();
long token = reader.beginMessage();
for (int tag; (tag = reader.nextTag()) != -1; ) {
switch (tag) {
case 1:
builder.number(ProtoAdapter.STRING.decode(reader));
break;
default:
{
FieldEncoding fieldEncoding = reader.peekFieldEncoding();
Object value = fieldEncoding.rawProtoAdapter().decode(reader);
builder.addUnknownField(tag, fieldEncoding, value);
}
}
}
reader.endMessage(token);
return builder.build();
}
@Override
public Phone redact(Phone value) {
Builder builder = value.newBuilder();
builder.clearUnknownFields();
return builder.build();
}
}
}
| ProtoAdapter_Phone |
java | quarkusio__quarkus | integration-tests/redis-devservices/src/test/java/io/quarkus/redis/devservices/continuoustesting/it/DevServicesDevModeTest.java | {
"start": 945,
"end": 9735
} | class ____ {
@RegisterExtension
public static QuarkusDevModeTest test = new QuarkusDevModeTest()
.setArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class)
.addClass(BundledResource.class)
.addAsResource(new StringAsset(""), "application.properties"))
.setTestArchiveProducer(() -> ShrinkWrap.create(JavaArchive.class).addClass(PlainQuarkusTest.class));
@Test
public void testDevModeServiceUpdatesContainersOnConfigChange() {
// Interacting with the app will force a refresh
// Note that driving continuous testing concurrently can sometimes cause 500s caused by containers not yet being available on slow machines
ping();
List<Container> started = getRedisContainers();
assertFalse(started.isEmpty());
Container container = started.get(0);
assertTrue(Arrays.stream(container.getPorts()).noneMatch(p -> p.getPublicPort() == 6377),
"Expected random port, but got: " + Arrays.toString(container.getPorts()));
int newPort = 6388;
test.modifyResourceFile("application.properties", s -> s + "quarkus.redis.devservices.port=" + newPort);
// Force another refresh
ping();
List<Container> newContainers = getRedisContainersExcludingExisting(started);
// We expect 1 new containers, since test was not refreshed.
// On some VMs that's what we get, but on others, a test-mode augmentation happens, and then we get two containers
assertEquals(1, newContainers.size(),
"There were " + newContainers.size() + " new containers, and should have been 1 or 2. New containers: "
+ prettyPrintContainerList(newContainers)
+ "\n Old containers: " + prettyPrintContainerList(started) + "\n All containers: "
+ prettyPrintContainerList(getAllContainers())); // this can be wrong
// We need to inspect the dev-mode container; we don't have a non-brittle way of distinguishing them, so just look in them all
boolean hasRightPort = newContainers.stream()
.anyMatch(newContainer -> hasPublicPort(newContainer, newPort));
assertTrue(hasRightPort,
"Expected port " + newPort + ", but got: "
+ newContainers.stream().map(c -> Arrays.toString(c.getPorts())).collect(Collectors.joining(", ")));
}
@Test
public void testDevModeServiceDoesNotRestartContainersOnCodeChange() {
ping();
List<Container> started = getRedisContainers();
assertFalse(started.isEmpty());
Container container = started.get(0);
assertTrue(Arrays.stream(container.getPorts()).noneMatch(p -> p.getPublicPort() == 6377),
"Expected random port 6377, but got: " + Arrays.toString(container.getPorts()));
// Make a change that shouldn't affect dev services
test.modifySourceFile(BundledResource.class, s -> s.replaceAll("OK", "poink"));
ping();
List<Container> newContainers = getRedisContainersExcludingExisting(started);
// No new containers should have spawned
assertEquals(0, newContainers.size(),
"New containers: " + newContainers + "\n Old containers: " + started + "\n All containers: "
+ getAllContainers()); // this can be wrong
}
@Test
public void testDevModeKeepsSameInstanceWhenRefreshedOnSecondChange() {
// Step 1: Ensure we have a dev service running
System.out.println("Step 1: Ensure we have a dev service running");
ping();
List<Container> step1Containers = getRedisContainers();
assertFalse(step1Containers.isEmpty());
Container container = step1Containers.get(0);
assertFalse(hasPublicPort(container, 6377));
// Step 2: Make a change that should affect dev services
System.out.println("Step 2: Make a change that should affect dev services");
int someFixedPort = 36377;
// Make a change that SHOULD affect dev services
test.modifyResourceFile("application.properties",
s -> s
+ "quarkus.redis.devservices.port=" + someFixedPort + "\n");
ping();
List<Container> step2Containers = getRedisContainersExcludingExisting(step1Containers);
// New containers should have spawned
assertEquals(1, step2Containers.size(),
"New containers: " + step2Containers + "\n Old containers: " + step1Containers + "\n All containers: "
+ getAllContainers());
assertTrue(hasPublicPort(step2Containers.get(0), someFixedPort));
// Step 3: Now change back to a random port, which should cause a new container to spawn
System.out.println("Step 3: Now change back to a random port, which should cause a new container to spawn");
test.modifyResourceFile("application.properties",
s -> s.replaceAll("quarkus.redis.devservices.port=" + someFixedPort, ""));
ping();
List<Container> step3Containers = getRedisContainersExcludingExisting(step2Containers);
// New containers should have spawned
assertEquals(1, step3Containers.size(),
"New containers: " + step3Containers + "\n Old containers: " + step2Containers + "\n All containers: "
+ getAllContainers());
// Step 4: Now make a change that should not affect dev services
System.out.println("Step 4: Now make a change that should not affect dev services");
test.modifySourceFile(BundledResource.class, s -> s.replaceAll("OK", "poink"));
ping();
List<Container> step4Containers = getRedisContainersExcludingExisting(step3Containers);
// No new containers should have spawned
assertEquals(0, step4Containers.size(),
"New containers: " + step4Containers + "\n Old containers: " + step3Containers + "\n All containers: "
+ getAllContainers()); // this can be wrong
// Step 5: Now make a change that should not affect dev services, but is not the same as the previous change
System.out.println(
"Step 5: Now make a change that should not affect dev services, but is not the same as the previous change");
test.modifySourceFile(BundledResource.class, s -> s.replaceAll("poink", "OK"));
ping();
List<Container> step5Containers = getRedisContainersExcludingExisting(step3Containers);
// No new containers should have spawned
assertEquals(0, step5Containers.size(),
"New containers: " + step5Containers + "\n Old containers: " + step5Containers + "\n All containers: "
+ getAllContainers()); // this can be wrong
}
private static List<Container> getAllContainers() {
return DockerClientFactory.lazyClient().listContainersCmd().exec().stream()
.filter(container -> isRedisContainer(container)).toList();
}
private static List<Container> getRedisContainers() {
return getAllContainers();
}
private static List<Container> getRedisContainersExcludingExisting(Collection<Container> existingContainers) {
return getRedisContainers().stream().filter(
container -> existingContainers.stream().noneMatch(existing -> existing.getId().equals(container.getId())))
.toList();
}
private static List<Container> getAllContainersExcludingExisting(Collection<Container> existingContainers) {
return getAllContainers().stream().filter(
container -> existingContainers.stream().noneMatch(existing -> existing.getId().equals(container.getId())))
.toList();
}
private static boolean isRedisContainer(Container container) {
// The output of getCommand() seems to vary by host OS (it's different on CI and mac), but the image name should be reliable
return container.getImage().contains("redis");
}
private static String prettyPrintContainerList(List<Container> newContainers) {
return newContainers.stream()
.map(c -> Arrays.toString(c.getPorts()) + " -- " + Arrays.toString(c.getNames()) + " -- " + c.getLabels())
.collect(Collectors.joining(", \n"));
}
private static boolean hasPublicPort(Container newContainer, int newPort) {
return Arrays.stream(newContainer.getPorts()).anyMatch(p -> p.getPublicPort() == newPort);
}
void ping() {
when().get("/bundled/ping").then()
.statusCode(200)
.body(is("PONG"));
}
}
| DevServicesDevModeTest |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy-client-jackson/deployment/src/test/java/io/quarkus/restclient/jackson/deployment/ClientResource.java | {
"start": 305,
"end": 764
} | class ____ {
@Inject
@RestClient
RestInterface restInterface;
@GET
@Path("/hello")
public String hello() {
DateDto dateDto = restInterface.get();
ZonedDateTime zonedDateTime = dateDto.getDate();
if (zonedDateTime.getMonth().equals(Month.NOVEMBER)
&& zonedDateTime.getZone().equals(ZoneId.of("Europe/London"))) {
return "OK";
}
return "INVALID";
}
}
| ClientResource |
java | elastic__elasticsearch | x-pack/plugin/esql/qa/server/multi-node/src/javaRestTest/java/org/elasticsearch/xpack/esql/qa/multi_node/EsqlSpecIT.java | {
"start": 557,
"end": 1293
} | class ____ extends EsqlSpecTestCase {
@ClassRule
public static ElasticsearchCluster cluster = Clusters.testCluster(spec -> spec.plugin("inference-service-test"));
@Override
protected String getTestRestCluster() {
return cluster.getHttpAddresses();
}
public EsqlSpecIT(String fileName, String groupName, String testName, Integer lineNumber, CsvTestCase testCase, String instructions) {
super(fileName, groupName, testName, lineNumber, testCase, instructions);
}
@Override
protected boolean enableRoundingDoubleValuesOnAsserting() {
return true;
}
@Override
protected boolean supportsSourceFieldMapping() throws IOException {
return false;
}
}
| EsqlSpecIT |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/HttpEndpointBuilderFactory.java | {
"start": 1579,
"end": 37646
} | interface ____
extends
EndpointProducerBuilder {
default AdvancedHttpEndpointBuilder advanced() {
return (AdvancedHttpEndpointBuilder) this;
}
/**
* Determines whether or not the raw input stream is cached or not. The
* Camel consumer (camel-servlet, camel-jetty etc.) will by default
* cache the input stream to support reading it multiple times to ensure
* it Camel can retrieve all data from the stream. However you can set
* this option to true when you for example need to access the raw
* stream, such as streaming it directly to a file or other persistent
* store. DefaultHttpBinding will copy the request input stream into a
* stream cache and put it into message body if this option is false to
* support reading the stream multiple times. If you use Servlet to
* bridge/proxy an endpoint then consider enabling this option to
* improve performance, in case you do not need to read the message
* payload multiple times. The producer (camel-http) will by default
* cache the response body stream. If setting this option to true, then
* the producers will not cache the response body stream but use the
* response stream as-is (the stream can only be read once) as the
* message body.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param disableStreamCache the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder disableStreamCache(boolean disableStreamCache) {
doSetProperty("disableStreamCache", disableStreamCache);
return this;
}
/**
* Determines whether or not the raw input stream is cached or not. The
* Camel consumer (camel-servlet, camel-jetty etc.) will by default
* cache the input stream to support reading it multiple times to ensure
* it Camel can retrieve all data from the stream. However you can set
* this option to true when you for example need to access the raw
* stream, such as streaming it directly to a file or other persistent
* store. DefaultHttpBinding will copy the request input stream into a
* stream cache and put it into message body if this option is false to
* support reading the stream multiple times. If you use Servlet to
* bridge/proxy an endpoint then consider enabling this option to
* improve performance, in case you do not need to read the message
* payload multiple times. The producer (camel-http) will by default
* cache the response body stream. If setting this option to true, then
* the producers will not cache the response body stream but use the
* response stream as-is (the stream can only be read once) as the
* message body.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: common
*
* @param disableStreamCache the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder disableStreamCache(String disableStreamCache) {
doSetProperty("disableStreamCache", disableStreamCache);
return this;
}
/**
* If the option is true, HttpProducer will ignore the Exchange.HTTP_URI
* header, and use the endpoint's URI for request. You may also set the
* option throwExceptionOnFailure to be false to let the HttpProducer
* send all the fault response back.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param bridgeEndpoint the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder bridgeEndpoint(boolean bridgeEndpoint) {
doSetProperty("bridgeEndpoint", bridgeEndpoint);
return this;
}
/**
* If the option is true, HttpProducer will ignore the Exchange.HTTP_URI
* header, and use the endpoint's URI for request. You may also set the
* option throwExceptionOnFailure to be false to let the HttpProducer
* send all the fault response back.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param bridgeEndpoint the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder bridgeEndpoint(String bridgeEndpoint) {
doSetProperty("bridgeEndpoint", bridgeEndpoint);
return this;
}
/**
* Specifies whether a Connection Close header must be added to HTTP
* Request. By default connectionClose is false.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param connectionClose the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder connectionClose(boolean connectionClose) {
doSetProperty("connectionClose", connectionClose);
return this;
}
/**
* Specifies whether a Connection Close header must be added to HTTP
* Request. By default connectionClose is false.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param connectionClose the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder connectionClose(String connectionClose) {
doSetProperty("connectionClose", connectionClose);
return this;
}
/**
* Configure the HTTP method to use. The HttpMethod header cannot
* override this option if set.
*
* The option is a:
* <code>org.apache.camel.http.common.HttpMethods</code> type.
*
* Group: producer
*
* @param httpMethod the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder httpMethod(org.apache.camel.http.common.HttpMethods httpMethod) {
doSetProperty("httpMethod", httpMethod);
return this;
}
/**
* Configure the HTTP method to use. The HttpMethod header cannot
* override this option if set.
*
* The option will be converted to a
* <code>org.apache.camel.http.common.HttpMethods</code> type.
*
* Group: producer
*
* @param httpMethod the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder httpMethod(String httpMethod) {
doSetProperty("httpMethod", httpMethod);
return this;
}
/**
* To enable logging HTTP request and response. You can use a custom
* LoggingHttpActivityListener as httpActivityListener to control
* logging options.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param logHttpActivity the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder logHttpActivity(boolean logHttpActivity) {
doSetProperty("logHttpActivity", logHttpActivity);
return this;
}
/**
* To enable logging HTTP request and response. You can use a custom
* LoggingHttpActivityListener as httpActivityListener to control
* logging options.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param logHttpActivity the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder logHttpActivity(String logHttpActivity) {
doSetProperty("logHttpActivity", logHttpActivity);
return this;
}
/**
* Whether to force using multipart/form-data for easy file uploads.
* This is only to be used for uploading the message body as a single
* entity form-data. For uploading multiple entries then use
* org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder to
* build the form.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param multipartUpload the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder multipartUpload(boolean multipartUpload) {
doSetProperty("multipartUpload", multipartUpload);
return this;
}
/**
* Whether to force using multipart/form-data for easy file uploads.
* This is only to be used for uploading the message body as a single
* entity form-data. For uploading multiple entries then use
* org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder to
* build the form.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param multipartUpload the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder multipartUpload(String multipartUpload) {
doSetProperty("multipartUpload", multipartUpload);
return this;
}
/**
* The name of the multipart/form-data when multipartUpload is enabled.
*
* The option is a: <code>java.lang.String</code> type.
*
* Default: data
* Group: producer
*
* @param multipartUploadName the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder multipartUploadName(String multipartUploadName) {
doSetProperty("multipartUploadName", multipartUploadName);
return this;
}
/**
* Whether to skip Camel control headers (CamelHttp... headers) to
* influence this endpoint. Control headers from previous HTTP
* components can influence how this Camel component behaves such as
* CamelHttpPath, CamelHttpQuery, etc.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param skipControlHeaders the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder skipControlHeaders(boolean skipControlHeaders) {
doSetProperty("skipControlHeaders", skipControlHeaders);
return this;
}
/**
* Whether to skip Camel control headers (CamelHttp... headers) to
* influence this endpoint. Control headers from previous HTTP
* components can influence how this Camel component behaves such as
* CamelHttpPath, CamelHttpQuery, etc.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param skipControlHeaders the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder skipControlHeaders(String skipControlHeaders) {
doSetProperty("skipControlHeaders", skipControlHeaders);
return this;
}
/**
* Whether to skip mapping the Camel headers as HTTP request headers.
* This is useful when you know that calling the HTTP service should not
* include any custom headers.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param skipRequestHeaders the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder skipRequestHeaders(boolean skipRequestHeaders) {
doSetProperty("skipRequestHeaders", skipRequestHeaders);
return this;
}
/**
* Whether to skip mapping the Camel headers as HTTP request headers.
* This is useful when you know that calling the HTTP service should not
* include any custom headers.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param skipRequestHeaders the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder skipRequestHeaders(String skipRequestHeaders) {
doSetProperty("skipRequestHeaders", skipRequestHeaders);
return this;
}
/**
* Whether to skip mapping all the HTTP response headers to Camel
* headers.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param skipResponseHeaders the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder skipResponseHeaders(boolean skipResponseHeaders) {
doSetProperty("skipResponseHeaders", skipResponseHeaders);
return this;
}
/**
* Whether to skip mapping all the HTTP response headers to Camel
* headers.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer
*
* @param skipResponseHeaders the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder skipResponseHeaders(String skipResponseHeaders) {
doSetProperty("skipResponseHeaders", skipResponseHeaders);
return this;
}
/**
* Option to disable throwing the HttpOperationFailedException in case
* of failed responses from the remote server. This allows you to get
* all responses regardless of the HTTP status code.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param throwExceptionOnFailure the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder throwExceptionOnFailure(boolean throwExceptionOnFailure) {
doSetProperty("throwExceptionOnFailure", throwExceptionOnFailure);
return this;
}
/**
* Option to disable throwing the HttpOperationFailedException in case
* of failed responses from the remote server. This allows you to get
* all responses regardless of the HTTP status code.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer
*
* @param throwExceptionOnFailure the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder throwExceptionOnFailure(String throwExceptionOnFailure) {
doSetProperty("throwExceptionOnFailure", throwExceptionOnFailure);
return this;
}
/**
* Proxy authentication domain to use with NTLM.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param proxyAuthDomain the value to set
* @return the dsl builder
*/
@Deprecated
default HttpEndpointBuilder proxyAuthDomain(String proxyAuthDomain) {
doSetProperty("proxyAuthDomain", proxyAuthDomain);
return this;
}
/**
* Proxy server host.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param proxyAuthHost the value to set
* @return the dsl builder
*/
@Deprecated
default HttpEndpointBuilder proxyAuthHost(String proxyAuthHost) {
doSetProperty("proxyAuthHost", proxyAuthHost);
return this;
}
/**
* Proxy authentication method to use (NTLM is deprecated).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param proxyAuthMethod the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder proxyAuthMethod(String proxyAuthMethod) {
doSetProperty("proxyAuthMethod", proxyAuthMethod);
return this;
}
/**
* Proxy authentication domain (workstation name) to use with NTLM.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param proxyAuthNtHost the value to set
* @return the dsl builder
*/
@Deprecated
default HttpEndpointBuilder proxyAuthNtHost(String proxyAuthNtHost) {
doSetProperty("proxyAuthNtHost", proxyAuthNtHost);
return this;
}
/**
* Proxy server password.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param proxyAuthPassword the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder proxyAuthPassword(String proxyAuthPassword) {
doSetProperty("proxyAuthPassword", proxyAuthPassword);
return this;
}
/**
* Proxy server port.
*
* The option is a: <code>int</code> type.
*
* Group: proxy
*
* @param proxyAuthPort the value to set
* @return the dsl builder
*/
@Deprecated
default HttpEndpointBuilder proxyAuthPort(int proxyAuthPort) {
doSetProperty("proxyAuthPort", proxyAuthPort);
return this;
}
/**
* Proxy server port.
*
* The option will be converted to a <code>int</code> type.
*
* Group: proxy
*
* @param proxyAuthPort the value to set
* @return the dsl builder
*/
@Deprecated
default HttpEndpointBuilder proxyAuthPort(String proxyAuthPort) {
doSetProperty("proxyAuthPort", proxyAuthPort);
return this;
}
/**
* Proxy server authentication protocol scheme to use.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param proxyAuthScheme the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder proxyAuthScheme(String proxyAuthScheme) {
doSetProperty("proxyAuthScheme", proxyAuthScheme);
return this;
}
/**
* Proxy server username.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param proxyAuthUsername the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder proxyAuthUsername(String proxyAuthUsername) {
doSetProperty("proxyAuthUsername", proxyAuthUsername);
return this;
}
/**
* Proxy server host.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: proxy
*
* @param proxyHost the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder proxyHost(String proxyHost) {
doSetProperty("proxyHost", proxyHost);
return this;
}
/**
* Proxy server port.
*
* The option is a: <code>int</code> type.
*
* Group: proxy
*
* @param proxyPort the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder proxyPort(int proxyPort) {
doSetProperty("proxyPort", proxyPort);
return this;
}
/**
* Proxy server port.
*
* The option will be converted to a <code>int</code> type.
*
* Group: proxy
*
* @param proxyPort the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder proxyPort(String proxyPort) {
doSetProperty("proxyPort", proxyPort);
return this;
}
/**
* Authentication bearer token.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param authBearerToken the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder authBearerToken(String authBearerToken) {
doSetProperty("authBearerToken", authBearerToken);
return this;
}
/**
* Authentication domain to use with NTLM.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param authDomain the value to set
* @return the dsl builder
*/
@Deprecated
default HttpEndpointBuilder authDomain(String authDomain) {
doSetProperty("authDomain", authDomain);
return this;
}
/**
* If this option is true, camel-http sends preemptive basic
* authentication to the server.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param authenticationPreemptive the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder authenticationPreemptive(boolean authenticationPreemptive) {
doSetProperty("authenticationPreemptive", authenticationPreemptive);
return this;
}
/**
* If this option is true, camel-http sends preemptive basic
* authentication to the server.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param authenticationPreemptive the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder authenticationPreemptive(String authenticationPreemptive) {
doSetProperty("authenticationPreemptive", authenticationPreemptive);
return this;
}
/**
* Authentication host to use with NTLM.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param authHost the value to set
* @return the dsl builder
*/
@Deprecated
default HttpEndpointBuilder authHost(String authHost) {
doSetProperty("authHost", authHost);
return this;
}
/**
* Authentication methods allowed to use as a comma separated list of
* values Basic, Bearer, or NTLM. (NTLM is deprecated).
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param authMethod the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder authMethod(String authMethod) {
doSetProperty("authMethod", authMethod);
return this;
}
/**
* Authentication password.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param authPassword the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder authPassword(String authPassword) {
doSetProperty("authPassword", authPassword);
return this;
}
/**
* Authentication username.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param authUsername the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder authUsername(String authUsername) {
doSetProperty("authUsername", authUsername);
return this;
}
/**
* Whether to use OAuth2 body authentication.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param oauth2BodyAuthentication the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2BodyAuthentication(boolean oauth2BodyAuthentication) {
doSetProperty("oauth2BodyAuthentication", oauth2BodyAuthentication);
return this;
}
/**
* Whether to use OAuth2 body authentication.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param oauth2BodyAuthentication the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2BodyAuthentication(String oauth2BodyAuthentication) {
doSetProperty("oauth2BodyAuthentication", oauth2BodyAuthentication);
return this;
}
/**
* Default expiration time for cached OAuth2 tokens, in seconds. Used if
* token response does not contain 'expires_in' field.
*
* The option is a: <code>long</code> type.
*
* Default: 3600
* Group: security
*
* @param oauth2CachedTokensDefaultExpirySeconds the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2CachedTokensDefaultExpirySeconds(long oauth2CachedTokensDefaultExpirySeconds) {
doSetProperty("oauth2CachedTokensDefaultExpirySeconds", oauth2CachedTokensDefaultExpirySeconds);
return this;
}
/**
* Default expiration time for cached OAuth2 tokens, in seconds. Used if
* token response does not contain 'expires_in' field.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 3600
* Group: security
*
* @param oauth2CachedTokensDefaultExpirySeconds the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2CachedTokensDefaultExpirySeconds(String oauth2CachedTokensDefaultExpirySeconds) {
doSetProperty("oauth2CachedTokensDefaultExpirySeconds", oauth2CachedTokensDefaultExpirySeconds);
return this;
}
/**
* Amount of time which is deducted from OAuth2 tokens expiry time to
* compensate for the time it takes OAuth2 Token Endpoint to send the
* token over http, in seconds. Set this parameter to high value if you
* OAuth2 Token Endpoint answers slowly or you tokens expire quickly. If
* you set this parameter to too small value, you can get 4xx http
* errors because camel will think that the received token is still
* valid, while in reality the token is expired for the Authentication
* server.
*
* The option is a: <code>long</code> type.
*
* Default: 5
* Group: security
*
* @param oauth2CachedTokensExpirationMarginSeconds the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2CachedTokensExpirationMarginSeconds(long oauth2CachedTokensExpirationMarginSeconds) {
doSetProperty("oauth2CachedTokensExpirationMarginSeconds", oauth2CachedTokensExpirationMarginSeconds);
return this;
}
/**
* Amount of time which is deducted from OAuth2 tokens expiry time to
* compensate for the time it takes OAuth2 Token Endpoint to send the
* token over http, in seconds. Set this parameter to high value if you
* OAuth2 Token Endpoint answers slowly or you tokens expire quickly. If
* you set this parameter to too small value, you can get 4xx http
* errors because camel will think that the received token is still
* valid, while in reality the token is expired for the Authentication
* server.
*
* The option will be converted to a <code>long</code> type.
*
* Default: 5
* Group: security
*
* @param oauth2CachedTokensExpirationMarginSeconds the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2CachedTokensExpirationMarginSeconds(String oauth2CachedTokensExpirationMarginSeconds) {
doSetProperty("oauth2CachedTokensExpirationMarginSeconds", oauth2CachedTokensExpirationMarginSeconds);
return this;
}
/**
* Whether to cache OAuth2 client tokens.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param oauth2CacheTokens the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2CacheTokens(boolean oauth2CacheTokens) {
doSetProperty("oauth2CacheTokens", oauth2CacheTokens);
return this;
}
/**
* Whether to cache OAuth2 client tokens.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: security
*
* @param oauth2CacheTokens the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2CacheTokens(String oauth2CacheTokens) {
doSetProperty("oauth2CacheTokens", oauth2CacheTokens);
return this;
}
/**
* OAuth2 client id.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param oauth2ClientId the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2ClientId(String oauth2ClientId) {
doSetProperty("oauth2ClientId", oauth2ClientId);
return this;
}
/**
* OAuth2 client secret.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param oauth2ClientSecret the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2ClientSecret(String oauth2ClientSecret) {
doSetProperty("oauth2ClientSecret", oauth2ClientSecret);
return this;
}
/**
* OAuth2 Token endpoint.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param oauth2ResourceIndicator the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2ResourceIndicator(String oauth2ResourceIndicator) {
doSetProperty("oauth2ResourceIndicator", oauth2ResourceIndicator);
return this;
}
/**
* OAuth2 scope.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param oauth2Scope the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2Scope(String oauth2Scope) {
doSetProperty("oauth2Scope", oauth2Scope);
return this;
}
/**
* OAuth2 Resource Indicator.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: security
*
* @param oauth2TokenEndpoint the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder oauth2TokenEndpoint(String oauth2TokenEndpoint) {
doSetProperty("oauth2TokenEndpoint", oauth2TokenEndpoint);
return this;
}
/**
* To configure security using SSLContextParameters. Important: Only one
* instance of org.apache.camel.util.jsse.SSLContextParameters is
* supported per HttpComponent. If you need to use 2 or more different
* instances, you need to define a new HttpComponent per instance you
* need.
*
* The option is a:
* <code>org.apache.camel.support.jsse.SSLContextParameters</code> type.
*
* Group: security
*
* @param sslContextParameters the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder sslContextParameters(org.apache.camel.support.jsse.SSLContextParameters sslContextParameters) {
doSetProperty("sslContextParameters", sslContextParameters);
return this;
}
/**
* To configure security using SSLContextParameters. Important: Only one
* instance of org.apache.camel.util.jsse.SSLContextParameters is
* supported per HttpComponent. If you need to use 2 or more different
* instances, you need to define a new HttpComponent per instance you
* need.
*
* The option will be converted to a
* <code>org.apache.camel.support.jsse.SSLContextParameters</code> type.
*
* Group: security
*
* @param sslContextParameters the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder sslContextParameters(String sslContextParameters) {
doSetProperty("sslContextParameters", sslContextParameters);
return this;
}
/**
* To use a custom X509HostnameVerifier such as DefaultHostnameVerifier
* or NoopHostnameVerifier.
*
* The option is a: <code>javax.net.ssl.HostnameVerifier</code> type.
*
* Group: security
*
* @param x509HostnameVerifier the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder x509HostnameVerifier(javax.net.ssl.HostnameVerifier x509HostnameVerifier) {
doSetProperty("x509HostnameVerifier", x509HostnameVerifier);
return this;
}
/**
* To use a custom X509HostnameVerifier such as DefaultHostnameVerifier
* or NoopHostnameVerifier.
*
* The option will be converted to a
* <code>javax.net.ssl.HostnameVerifier</code> type.
*
* Group: security
*
* @param x509HostnameVerifier the value to set
* @return the dsl builder
*/
default HttpEndpointBuilder x509HostnameVerifier(String x509HostnameVerifier) {
doSetProperty("x509HostnameVerifier", x509HostnameVerifier);
return this;
}
}
/**
* Advanced builder for endpoint for the HTTP component.
*/
public | HttpEndpointBuilder |
java | apache__kafka | clients/src/test/java/org/apache/kafka/common/requests/GetTelemetrySubscriptionsResponseTest.java | {
"start": 1106,
"end": 2058
} | class ____ {
@Test
public void testErrorCountsReturnsNoneWhenNoErrors() {
GetTelemetrySubscriptionsResponseData data = new GetTelemetrySubscriptionsResponseData()
.setErrorCode(Errors.NONE.code());
GetTelemetrySubscriptionsResponse response = new GetTelemetrySubscriptionsResponse(data);
assertEquals(Collections.singletonMap(Errors.NONE, 1), response.errorCounts());
}
@Test
public void testErrorCountsReturnsOneError() {
GetTelemetrySubscriptionsResponseData data = new GetTelemetrySubscriptionsResponseData()
.setErrorCode(Errors.CLUSTER_AUTHORIZATION_FAILED.code());
data.setErrorCode(Errors.INVALID_CONFIG.code());
GetTelemetrySubscriptionsResponse response = new GetTelemetrySubscriptionsResponse(data);
assertEquals(Collections.singletonMap(Errors.INVALID_CONFIG, 1), response.errorCounts());
}
}
| GetTelemetrySubscriptionsResponseTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ForOverrideCheckerTest.java | {
"start": 3843,
"end": 4218
} | class ____ extends test.ExtendMe {
public void googleyMethod() {
callMe();
}
}
""")
.doTest();
}
@Test
public void userInSamePackageCannotCallMethod() {
compilationHelper
.addSourceLines(
"test/Test.java",
"""
package test;
public | Test |
java | grpc__grpc-java | core/src/testFixtures/java/io/grpc/internal/WritableBufferTestBase.java | {
"start": 932,
"end": 2852
} | class ____ {
/**
* Returns a new buffer for every test case with
* at least 100 byte of capacity.
*/
protected abstract WritableBuffer buffer();
/**
* Bytes written to {@link #buffer()}.
*/
protected abstract byte[] writtenBytes();
@Test(expected = RuntimeException.class)
public void testWriteNegativeLength() {
buffer().write(new byte[1], 0, -1);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testWriteNegativeSrcIndex() {
buffer().write(new byte[1], -1, 0);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testWriteSrcIndexAndLengthExceedSrcLength() {
buffer().write(new byte[10], 1, 10);
}
@Test(expected = IndexOutOfBoundsException.class)
public void testWriteSrcIndexAndLengthExceedWritableBytes() {
buffer().write(new byte[buffer().writableBytes()], 1, buffer().writableBytes());
}
@Test
public void testWritableAndReadableBytes() {
int before = buffer().writableBytes();
buffer().write(new byte[10], 0, 5);
assertEquals(5, before - buffer().writableBytes());
assertEquals(5, buffer().readableBytes());
}
@Test
public void testWriteSrcIndex() {
byte[] b = new byte[10];
for (byte i = 5; i < 10; i++) {
b[i] = i;
}
buffer().write(b, 5, 5);
assertEquals(5, buffer().readableBytes());
byte[] writtenBytes = writtenBytes();
assertEquals(5, writtenBytes.length);
for (int i = 0; i < writtenBytes.length; i++) {
assertEquals(5 + i, writtenBytes[i]);
}
}
@Test
public void testMultipleWrites() {
byte[] b = new byte[100];
for (byte i = 0; i < b.length; i++) {
b[i] = i;
}
// Write in chunks of 10 bytes
for (int i = 0; i < 10; i++) {
buffer().write(b, 10 * i, 10);
assertEquals(10 * (i + 1), buffer().readableBytes());
}
assertArrayEquals(b, writtenBytes());
}
}
| WritableBufferTestBase |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/convert/converter/DefaultConversionServiceTests.java | {
"start": 40330,
"end": 40593
} | class ____ implements Converter<String, Color> {
@Override
public Color convert(String source) {
if (!source.startsWith("#")) {
source = "#" + source;
}
return Color.decode(source);
}
}
@SuppressWarnings("serial")
public static | ColorConverter |
java | grpc__grpc-java | services/src/generated/main/grpc/io/grpc/reflection/v1/ServerReflectionGrpc.java | {
"start": 9608,
"end": 11448
} | class ____<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_SERVER_REFLECTION_INFO:
return (io.grpc.stub.StreamObserver<Req>) serviceImpl.serverReflectionInfo(
(io.grpc.stub.StreamObserver<io.grpc.reflection.v1.ServerReflectionResponse>) responseObserver);
default:
throw new AssertionError();
}
}
}
public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getServerReflectionInfoMethod(),
io.grpc.stub.ServerCalls.asyncBidiStreamingCall(
new MethodHandlers<
io.grpc.reflection.v1.ServerReflectionRequest,
io.grpc.reflection.v1.ServerReflectionResponse>(
service, METHODID_SERVER_REFLECTION_INFO)))
.build();
}
private static abstract | MethodHandlers |
java | apache__camel | components/camel-pubnub/src/main/java/org/apache/camel/component/pubnub/PubNubProducer.java | {
"start": 1667,
"end": 10863
} | class ____ extends DefaultAsyncProducer {
private static final Logger LOG = LoggerFactory.getLogger(PubNubProducer.class);
private final PubNubEndpoint endpoint;
private final PubNubConfiguration pubnubConfiguration;
public PubNubProducer(PubNubEndpoint endpoint, PubNubConfiguration pubNubConfiguration) {
super(endpoint);
this.endpoint = endpoint;
this.pubnubConfiguration = pubNubConfiguration;
}
@Override
public boolean process(final Exchange exchange, final AsyncCallback callback) {
Operation operation = getOperation(exchange);
LOG.debug("Executing {} operation", operation);
try {
switch (operation) {
case PUBLISH: {
doPublish(exchange, callback);
break;
}
case FIRE: {
doFire(exchange, callback);
break;
}
case GETHISTORY: {
doGetHistory(exchange, callback);
break;
}
case GETSTATE: {
doGetState(exchange, callback);
break;
}
case HERENOW: {
doHereNow(exchange, callback);
break;
}
case SETSTATE: {
doSetState(exchange, callback);
break;
}
default:
throw new UnsupportedOperationException(operation.toString());
}
} catch (Exception e) {
exchange.setException(e);
callback.done(true);
return true;
}
return false;
}
private void doPublish(Exchange exchange, AsyncCallback callback) {
Object body = exchange.getIn().getBody();
if (ObjectHelper.isEmpty(body)) {
throw new RuntimeCamelException("Cannot publish empty message");
}
LOG.debug("Sending message [{}] to channel [{}]", body, getChannel(exchange));
endpoint.getPubnub()
.publish()
.message(body)
.channel(getChannel(exchange))
.usePOST(true)
.async((Result<PNPublishResult> result) -> {
LOG.debug("Got publish message [{}]", result);
if (result.isFailure()) {
PubNubException ex = result.exceptionOrNull();
if (ex != null) {
exchange.setException(ex);
}
callback.done(false);
} else {
PNPublishResult r = result.getOrNull();
if (r != null) {
exchange.getIn().setHeader(PubNubConstants.TIMETOKEN, r.getTimetoken());
}
processMessage(exchange, callback, null);
}
});
}
private void doFire(Exchange exchange, AsyncCallback callback) {
Object body = exchange.getIn().getBody();
if (ObjectHelper.isEmpty(body)) {
exchange.setException(new CamelException("Can not fire empty message"));
callback.done(true);
}
LOG.debug("Sending message [{}] to channel [{}]", body, getChannel(exchange));
endpoint.getPubnub()
.fire()
.message(body)
.channel(getChannel(exchange))
.async((Result<PNPublishResult> result) -> {
LOG.debug("Got fire message [{}]", result);
if (result.isFailure()) {
PubNubException ex = result.exceptionOrNull();
if (ex != null) {
exchange.setException(ex);
}
callback.done(false);
} else {
PNPublishResult r = result.getOrNull();
if (r != null) {
exchange.getIn().setHeader(PubNubConstants.TIMETOKEN, r.getTimetoken());
}
processMessage(exchange, callback, null);
}
});
}
private void doGetHistory(Exchange exchange, AsyncCallback callback) {
endpoint.getPubnub()
.history()
.channel(getChannel(exchange))
.async((Result<PNHistoryResult> result) -> {
LOG.debug("Got history message [{}]", result);
if (result.isFailure()) {
PubNubException ex = result.exceptionOrNull();
if (ex != null) {
exchange.setException(ex);
}
callback.done(false);
} else {
PNHistoryResult r = result.getOrNull();
processMessage(exchange, callback, r != null ? r.getMessages() : null);
}
});
}
private void doSetState(Exchange exchange, AsyncCallback callback) {
Object body = exchange.getIn().getBody();
if (ObjectHelper.isEmpty(body)) {
exchange.setException(new CamelException("Can not publish empty message"));
callback.done(true);
}
LOG.debug("Sending setState [{}] to channel [{}]", body, getChannel(exchange));
endpoint.getPubnub()
.setPresenceState()
.channels(List.of(getChannel(exchange)))
.state(body)
.uuid(getUUID(exchange))
.async((Result<PNSetStateResult> result) -> {
LOG.debug("Got setState response [{}]", result);
if (result.isFailure()) {
PubNubException ex = result.exceptionOrNull();
if (ex != null) {
exchange.setException(ex);
}
callback.done(false);
} else {
PNSetStateResult r = result.getOrNull();
processMessage(exchange, callback, r);
}
});
}
private void doGetState(Exchange exchange, AsyncCallback callback) {
endpoint.getPubnub()
.getPresenceState()
.channels(List.of(getChannel(exchange)))
.uuid(getUUID(exchange))
.async((Result<PNGetStateResult> result) -> {
LOG.debug("Got state [{}]", result);
if (result.isFailure()) {
PubNubException ex = result.exceptionOrNull();
if (ex != null) {
exchange.setException(ex);
}
callback.done(false);
} else {
PNGetStateResult r = result.getOrNull();
processMessage(exchange, callback, r);
}
});
}
private void doHereNow(Exchange exchange, AsyncCallback callback) {
endpoint.getPubnub()
.hereNow()
.channels(List.of(getChannel(exchange)))
.includeState(true)
.includeUUIDs(true)
.async((Result<PNHereNowResult> result) -> {
LOG.debug("Got herNow message [{}]", result);
if (result.isFailure()) {
PubNubException ex = result.exceptionOrNull();
if (ex != null) {
exchange.setException(ex);
}
callback.done(false);
} else {
PNHereNowResult r = result.getOrNull();
processMessage(exchange, callback, r);
}
});
}
private void processMessage(Exchange exchange, AsyncCallback callback, Object body) {
if (body != null) {
ExchangeHelper.setInOutBodyPatternAware(exchange, body);
}
// signal exchange completion
callback.done(false);
}
private Operation getOperation(Exchange exchange) {
String operation = exchange.getIn().getHeader(PubNubConstants.OPERATION, String.class);
if (operation == null) {
operation = pubnubConfiguration.getOperation();
}
return operation != null ? Operation.valueOf(operation.toUpperCase()) : Operation.PUBLISH;
}
private String getChannel(Exchange exchange) {
String channel = exchange.getIn().getHeader(PubNubConstants.CHANNEL, String.class);
return channel != null ? channel : pubnubConfiguration.getChannel();
}
private String getUUID(Exchange exchange) {
String uuid = exchange.getIn().getHeader(PubNubConstants.UUID, String.class);
return uuid != null ? uuid : pubnubConfiguration.getUuid();
}
private | PubNubProducer |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/configuration/ImportTests.java | {
"start": 10591,
"end": 10698
} | class ____ {
@Bean
ITestBean left() {
return new TestBean();
}
}
@Configuration
static | LeftConfig |
java | google__dagger | dagger-android-support/main/java/dagger/android/support/DaggerAppCompatActivity.java | {
"start": 1235,
"end": 1817
} | class ____ extends AppCompatActivity
implements HasAndroidInjector {
@Inject DispatchingAndroidInjector<Object> androidInjector;
public DaggerAppCompatActivity() {
super();
}
@ContentView
public DaggerAppCompatActivity(@LayoutRes int contentLayoutId) {
super(contentLayoutId);
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
}
@Override
public AndroidInjector<Object> androidInjector() {
return androidInjector;
}
}
| DaggerAppCompatActivity |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/functions/Functions.java | {
"start": 1171,
"end": 4887
} | class ____ {
/** Utility class. */
private Functions() {
throw new IllegalStateException("No instances!");
}
@NonNull
public static <T1, T2, R> Function<Object[], R> toFunction(@NonNull BiFunction<? super T1, ? super T2, ? extends R> f) {
return new Array2Func<>(f);
}
@NonNull
public static <T1, T2, T3, R> Function<Object[], R> toFunction(@NonNull Function3<T1, T2, T3, R> f) {
return new Array3Func<>(f);
}
@NonNull
public static <T1, T2, T3, T4, R> Function<Object[], R> toFunction(@NonNull Function4<T1, T2, T3, T4, R> f) {
return new Array4Func<>(f);
}
@NonNull
public static <T1, T2, T3, T4, T5, R> Function<Object[], R> toFunction(@NonNull Function5<T1, T2, T3, T4, T5, R> f) {
return new Array5Func<>(f);
}
@NonNull
public static <T1, T2, T3, T4, T5, T6, R> Function<Object[], R> toFunction(
@NonNull Function6<T1, T2, T3, T4, T5, T6, R> f) {
return new Array6Func<>(f);
}
@NonNull
public static <T1, T2, T3, T4, T5, T6, T7, R> Function<Object[], R> toFunction(
@NonNull Function7<T1, T2, T3, T4, T5, T6, T7, R> f) {
return new Array7Func<>(f);
}
@NonNull
public static <T1, T2, T3, T4, T5, T6, T7, T8, R> Function<Object[], R> toFunction(
@NonNull Function8<T1, T2, T3, T4, T5, T6, T7, T8, R> f) {
return new Array8Func<>(f);
}
@NonNull
public static <T1, T2, T3, T4, T5, T6, T7, T8, T9, R> Function<Object[], R> toFunction(
@NonNull Function9<T1, T2, T3, T4, T5, T6, T7, T8, T9, R> f) {
return new Array9Func<>(f);
}
/** A singleton identity function. */
static final Function<Object, Object> IDENTITY = new Identity();
/**
* Returns an identity function that simply returns its argument.
* @param <T> the input and output value type
* @return the identity function
*/
@SuppressWarnings("unchecked")
@NonNull
public static <T> Function<T, T> identity() {
return (Function<T, T>)IDENTITY;
}
public static final Runnable EMPTY_RUNNABLE = new EmptyRunnable();
public static final Action EMPTY_ACTION = new EmptyAction();
static final Consumer<Object> EMPTY_CONSUMER = new EmptyConsumer();
/**
* Returns an empty consumer that does nothing.
* @param <T> the consumed value type, the value is ignored
* @return an empty consumer that does nothing.
*/
@SuppressWarnings("unchecked")
public static <T> Consumer<T> emptyConsumer() {
return (Consumer<T>)EMPTY_CONSUMER;
}
public static final Consumer<Throwable> ERROR_CONSUMER = new ErrorConsumer();
/**
* Wraps the consumed Throwable into an OnErrorNotImplementedException and
* signals it to the plugin error handler.
*/
public static final Consumer<Throwable> ON_ERROR_MISSING = new OnErrorMissingConsumer();
public static final LongConsumer EMPTY_LONG_CONSUMER = new EmptyLongConsumer();
static final Predicate<Object> ALWAYS_TRUE = new TruePredicate();
static final Predicate<Object> ALWAYS_FALSE = new FalsePredicate();
static final Supplier<Object> NULL_SUPPLIER = new NullProvider();
@SuppressWarnings("unchecked")
@NonNull
public static <T> Predicate<T> alwaysTrue() {
return (Predicate<T>)ALWAYS_TRUE;
}
@SuppressWarnings("unchecked")
@NonNull
public static <T> Predicate<T> alwaysFalse() {
return (Predicate<T>)ALWAYS_FALSE;
}
@SuppressWarnings("unchecked")
@NonNull
public static <T> Supplier<T> nullSupplier() {
return (Supplier<T>)NULL_SUPPLIER;
}
static final | Functions |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/api/atomic/referencearray/AtomicReferenceArrayAssert_usingDefaultElementComparator_Test.java | {
"start": 971,
"end": 1486
} | class ____ extends AtomicReferenceArrayAssertBaseTest {
@Override
protected AtomicReferenceArrayAssert<Object> invoke_api_method() {
return assertions.usingElementComparator(alwaysEqual())
.usingDefaultElementComparator();
}
@Override
protected void verify_internal_effects() {
assertThat(getArrays(assertions).getComparator()).isNull();
assertThat(ObjectArrays.instance()).isSameAs(getArrays(assertions));
}
}
| AtomicReferenceArrayAssert_usingDefaultElementComparator_Test |
java | quarkusio__quarkus | integration-tests/spring-boot-properties/src/test/java/io/quarkus/it/spring/boot/DefaultPropertiesIT.java | {
"start": 114,
"end": 174
} | class ____ extends DefaultPropertiesTest {
}
| DefaultPropertiesIT |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/OrderedMethodTests.java | {
"start": 19185,
"end": 20085
} | class ____ {
@BeforeEach
void trackInvocations(TestInfo testInfo) {
callSequence.add(testInfo.getDisplayName());
threadNames.add(Thread.currentThread().getName());
}
@Test
@DisplayName("test8")
@Order(Integer.MAX_VALUE)
void maxInteger() {
}
@Test
@DisplayName("test7")
@Order(DEFAULT + 1)
void defaultOrderValuePlusOne() {
}
@Test
@DisplayName("test6")
// @Order(DEFAULT)
void defaultOrderValue() {
}
@Test
@DisplayName("test3")
@Order(3)
void $() {
}
@Test
@DisplayName("test5")
@Order(5)
void AAA() {
}
@TestFactory
@DisplayName("test4")
@Order(4)
DynamicTest aaa() {
return dynamicTest("test4", () -> {
});
}
@Test
@DisplayName("test1")
@Order(1)
void zzz() {
}
@RepeatedTest(value = 1, name = "{displayName}")
@DisplayName("test2")
@Order(2)
void ___() {
}
}
static | OrderAnnotationTestCase |
java | micronaut-projects__micronaut-core | http-server-tck/src/main/java/io/micronaut/http/server/tck/tests/FilterErrorTest.java | {
"start": 11555,
"end": 12012
} | class ____ implements Condition {
@Override
public boolean matches(ConditionContext context) {
return context.getProperty("spec.name", String.class)
.map(val -> val.equals(SPEC_NAME + "4") || val.equals(SPEC_NAME + "3") || val.equals(SPEC_NAME + "2") || val.equals(SPEC_NAME))
.orElse(false);
}
}
@Requires(condition = FilterCondition.class)
@Singleton
static | FilterCondition |
java | quarkusio__quarkus | integration-tests/bouncycastle-fips-jsse/src/main/java/io/quarkus/it/bouncycastle/BouncyCastleFipsJsseEndpoint.java | {
"start": 206,
"end": 460
} | class ____ {
@GET
@Path("listProviders")
public String listProviders() {
return Arrays.asList(Security.getProviders()).stream()
.map(p -> p.getName()).collect(Collectors.joining(","));
}
}
| BouncyCastleFipsJsseEndpoint |
java | quarkusio__quarkus | extensions/schema-registry/apicurio/json-schema/deployment/src/main/java/io/quarkus/apicurio/registry/jsonschema/ApicurioRegistryJsonSchemaProcessor.java | {
"start": 474,
"end": 2545
} | class ____ {
@BuildStep
FeatureBuildItem feature() {
return new FeatureBuildItem(Feature.APICURIO_REGISTRY_JSON_SCHEMA);
}
@BuildStep
public void apicurioRegistryJsonSchema(BuildProducer<ReflectiveClassBuildItem> reflectiveClass,
BuildProducer<ExtensionSslNativeSupportBuildItem> sslNativeSupport) {
reflectiveClass
.produce(ReflectiveClassBuildItem.builder("io.apicurio.registry.serde.jsonschema.JsonSchemaKafkaDeserializer",
"io.apicurio.registry.serde.jsonschema.JsonSchemaKafkaSerializer").methods().build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder("io.apicurio.registry.serde.strategy.SimpleTopicIdStrategy",
"io.apicurio.registry.serde.strategy.TopicIdStrategy",
"io.apicurio.registry.serde.strategy.QualifiedRecordIdStrategy",
"io.apicurio.registry.serde.strategy.RecordIdStrategy",
"io.apicurio.registry.serde.jsonschema.strategy.TopicRecordIdStrategy").methods().fields()
.build());
reflectiveClass.produce(ReflectiveClassBuildItem.builder("io.apicurio.registry.serde.DefaultIdHandler",
"io.apicurio.registry.serde.Legacy4ByteIdHandler",
"io.apicurio.registry.serde.fallback.DefaultFallbackArtifactProvider",
"io.apicurio.registry.serde.headers.DefaultHeadersHandler").methods().fields()
.build());
String defaultSchemaResolver = "io.apicurio.registry.serde.DefaultSchemaResolver";
if (QuarkusClassLoader.isClassPresentAtRuntime(defaultSchemaResolver)) {
// Class not present after 2.2.0.Final
reflectiveClass.produce(ReflectiveClassBuildItem.builder(defaultSchemaResolver).methods()
.fields().build());
}
}
@BuildStep
ExtensionSslNativeSupportBuildItem enableSslInNative() {
return new ExtensionSslNativeSupportBuildItem(Feature.APICURIO_REGISTRY_JSON_SCHEMA);
}
}
| ApicurioRegistryJsonSchemaProcessor |
java | apache__flink | flink-libraries/flink-state-processing-api/src/test/java/org/apache/flink/state/api/HashMapStateBackendReaderKeyedStateITCase.java | {
"start": 1146,
"end": 1526
} | class ____
extends SavepointReaderKeyedStateITCase<HashMapStateBackend> {
@Override
protected Tuple2<Configuration, HashMapStateBackend> getStateBackendTuple() {
return Tuple2.of(
new Configuration().set(StateBackendOptions.STATE_BACKEND, "hashmap"),
new HashMapStateBackend());
}
}
| HashMapStateBackendReaderKeyedStateITCase |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/WildcardImportTest.java | {
"start": 9917,
"end": 10199
} | class ____ {
Inner t;
}
}
""")
.doTest();
}
@Test
public void importSamePackage() {
testHelper
.addInputLines(
"test/A.java",
"""
package test;
public | Inner |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/routing/allocation/decider/ResizeAllocationDecider.java | {
"start": 1165,
"end": 6045
} | class ____ extends AllocationDecider {
public static final String NAME = "resize";
@Override
public Decision canAllocate(ShardRouting shardRouting, RoutingAllocation allocation) {
return canAllocate(shardRouting, null, allocation);
}
@Override
public Decision canAllocate(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
if (shardRouting.unassignedInfo() != null && shardRouting.recoverySource().getType() == RecoverySource.Type.LOCAL_SHARDS) {
// we only make decisions here if we have an unassigned info and we have to recover from another index ie. split / shrink
final IndexMetadata indexMetadata = allocation.metadata().indexMetadata(shardRouting.index());
final Index resizeSourceIndex = indexMetadata.getResizeSourceIndex();
assert resizeSourceIndex != null;
final IndexMetadata sourceIndexMetadata = allocation.metadata().projectFor(resizeSourceIndex).index(resizeSourceIndex);
if (sourceIndexMetadata == null) {
return allocation.decision(Decision.NO, NAME, "resize source index [%s] doesn't exists", resizeSourceIndex.toString());
}
if (indexMetadata.getNumberOfShards() < sourceIndexMetadata.getNumberOfShards()) {
// this only handles splits and clone so far.
return Decision.ALWAYS;
}
ShardId shardId = indexMetadata.getNumberOfShards() == sourceIndexMetadata.getNumberOfShards()
? IndexMetadata.selectCloneShard(shardRouting.id(), sourceIndexMetadata, indexMetadata.getNumberOfShards())
: IndexMetadata.selectSplitShard(shardRouting.id(), sourceIndexMetadata, indexMetadata.getNumberOfShards());
ShardRouting sourceShardRouting = allocation.routingNodes().activePrimary(shardId);
if (sourceShardRouting == null) {
return allocation.decision(Decision.NO, NAME, "source primary shard [%s] is not active", shardId);
}
if (node != null) { // we might get called from the 2 param canAllocate method..
if (sourceShardRouting.currentNodeId().equals(node.nodeId())) {
return allocation.decision(Decision.YES, NAME, "source primary is allocated on this node");
} else {
return allocation.decision(Decision.NO, NAME, "source primary is allocated on another node");
}
} else {
return allocation.decision(Decision.YES, NAME, "source primary is active");
}
}
return super.canAllocate(shardRouting, node, allocation);
}
@Override
public Decision canForceAllocatePrimary(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
assert shardRouting.primary() : "must not call canForceAllocatePrimary on a non-primary shard " + shardRouting;
return canAllocate(shardRouting, node, allocation);
}
@Override
public Decision canForceAllocateDuringReplace(ShardRouting shardRouting, RoutingNode node, RoutingAllocation allocation) {
return canAllocate(shardRouting, node, allocation);
}
@Override
public Optional<Set<String>> getForcedInitialShardAllocationToNodes(ShardRouting shardRouting, RoutingAllocation allocation) {
if (shardRouting.unassignedInfo() != null && shardRouting.recoverySource().getType() == RecoverySource.Type.LOCAL_SHARDS) {
Index index = shardRouting.index();
final ProjectMetadata project = allocation.metadata().projectFor(index);
var targetIndexMetadata = project.getIndexSafe(shardRouting.index());
var sourceIndexMetadata = project.index(targetIndexMetadata.getResizeSourceIndex());
if (sourceIndexMetadata == null) {
return Optional.of(Set.of());// source index not found
}
if (targetIndexMetadata.getNumberOfShards() < sourceIndexMetadata.getNumberOfShards()) {
return Optional.empty();
}
var shardId = targetIndexMetadata.getNumberOfShards() == sourceIndexMetadata.getNumberOfShards()
? IndexMetadata.selectCloneShard(shardRouting.id(), sourceIndexMetadata, targetIndexMetadata.getNumberOfShards())
: IndexMetadata.selectSplitShard(shardRouting.id(), sourceIndexMetadata, targetIndexMetadata.getNumberOfShards());
var activePrimary = allocation.routingNodes().activePrimary(shardId);
if (activePrimary == null) {
return Optional.of(Set.of());// primary is active
}
return Optional.of(Set.of(activePrimary.currentNodeId()));
}
return super.getForcedInitialShardAllocationToNodes(shardRouting, allocation);
}
}
| ResizeAllocationDecider |
java | apache__camel | components/camel-smb/src/test/java/org/apache/camel/component/smb/SmbConsumerMaxMessagesPerPollIT.java | {
"start": 1020,
"end": 2411
} | class ____ extends SmbServerTestSupport {
@Override
public void doPostSetup() throws Exception {
sendFile(getSmbUrl(), "Bye World", "bye.txt");
sendFile(getSmbUrl(), "Hello World", "hello.txt");
sendFile(getSmbUrl(), "Goodday World", "goodday.txt");
}
protected String getSmbUrl() {
return String.format(
"smb:%s/%s/poll?username=%s&password=%s&delete=true&sortBy=file:name&maxMessagesPerPoll=2&eagerMaxMessagesPerPoll=false",
service.address(), service.shareName(), service.userName(), service.password());
}
@Test
public void testMaxMessagesPerPoll() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedBodiesReceived("Bye World", "Goodday World");
mock.setResultWaitTime(4000);
mock.expectedPropertyReceived(Exchange.BATCH_SIZE, 2);
MockEndpoint.assertIsSatisfied(context);
mock.reset();
mock.expectedBodiesReceived("Hello World");
mock.expectedPropertyReceived(Exchange.BATCH_SIZE, 1);
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
from(getSmbUrl()).to("mock:result");
}
};
}
}
| SmbConsumerMaxMessagesPerPollIT |
java | spring-projects__spring-security | core/src/test/java/org/springframework/security/jackson2/SecurityJackson2ModulesTests.java | {
"start": 4286,
"end": 4355
} | interface ____ {
}
@NotJacksonAnnotation
static | NotJacksonAnnotation |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/bean/override/convention/TestBeanOverrideProcessor.java | {
"start": 5775,
"end": 6276
} | class ____ present in fully-qualified method name: " + methodName);
String methodNameToUse = methodName.substring(indexOfHash + 1).trim();
Assert.hasText(methodNameToUse, () -> "No method name present in fully-qualified method name: " + methodName);
Class<?> declaringClass;
try {
declaringClass = ClassUtils.forName(className, getClass().getClassLoader());
}
catch (ClassNotFoundException | LinkageError ex) {
throw new IllegalStateException(
"Failed to load | name |
java | apache__flink | flink-python/src/main/java/org/apache/flink/python/env/PythonDependencyInfo.java | {
"start": 1885,
"end": 8023
} | class ____ {
/**
* The python files uploaded by TableEnvironment#add_python_file() or command line option
* "-pyfs". The key is the path of the python file and the value is the corresponding origin
* file name.
*/
@Nonnull private final Map<String, String> pythonFiles;
/**
* The path of the requirements file specified by TableEnvironment#set_python_requirements() or
* command line option "-pyreq".
*/
@Nullable private final String requirementsFilePath;
/**
* The path of the requirements cached directory uploaded by
* TableEnvironment#set_python_requirements() or command line option "-pyreq". It is used to
* support installing python packages offline.
*/
@Nullable private final String requirementsCacheDir;
@Nullable private final String pythonPath;
/**
* The python archives uploaded by TableEnvironment#add_python_archive() or command line option
* "-pyarch". The key is the path of the archive file and the value is the name of the directory
* to extract to.
*/
@Nonnull private final Map<String, String> archives;
/**
* The path of the python interpreter (e.g. /usr/local/bin/python) specified by
* pyflink.table.TableConfig#set_python_executable() or command line option "-pyexec".
*/
@Nonnull private final String pythonExec;
/** Execution Mode. */
@Nonnull private final String executionMode;
public PythonDependencyInfo(
@Nonnull Map<String, String> pythonFiles,
@Nullable String requirementsFilePath,
@Nullable String requirementsCacheDir,
@Nonnull Map<String, String> archives,
@Nonnull String pythonExec) {
this(
pythonFiles,
requirementsFilePath,
requirementsCacheDir,
archives,
pythonExec,
PYTHON_EXECUTION_MODE.defaultValue(),
PYTHON_PATH.defaultValue());
}
public PythonDependencyInfo(
@Nonnull Map<String, String> pythonFiles,
@Nullable String requirementsFilePath,
@Nullable String requirementsCacheDir,
@Nonnull Map<String, String> archives,
@Nonnull String pythonExec,
@Nonnull String executionMode,
@Nullable String pythonPath) {
this.pythonFiles = Objects.requireNonNull(pythonFiles);
this.requirementsFilePath = requirementsFilePath;
this.requirementsCacheDir = requirementsCacheDir;
this.pythonExec = Objects.requireNonNull(pythonExec);
this.archives = Objects.requireNonNull(archives);
this.executionMode = Objects.requireNonNull(executionMode);
this.pythonPath = pythonPath;
}
public Map<String, String> getPythonFiles() {
return pythonFiles;
}
public Optional<String> getRequirementsFilePath() {
return Optional.ofNullable(requirementsFilePath);
}
public Optional<String> getRequirementsCacheDir() {
return Optional.ofNullable(requirementsCacheDir);
}
public String getPythonExec() {
return pythonExec;
}
public Map<String, String> getArchives() {
return archives;
}
public String getExecutionMode() {
return executionMode;
}
public Optional<String> getPythonPath() {
return Optional.ofNullable(pythonPath);
}
/**
* Creates PythonDependencyInfo from GlobalJobParameters and DistributedCache.
*
* @param config The config.
* @param distributedCache The DistributedCache object of current task.
* @return The PythonDependencyInfo object that contains whole information of python dependency.
*/
public static PythonDependencyInfo create(
ReadableConfig config, DistributedCache distributedCache) {
Map<String, String> pythonFiles = new LinkedHashMap<>();
for (Map.Entry<String, String> entry :
config.getOptional(PYTHON_FILES_DISTRIBUTED_CACHE_INFO)
.orElse(new HashMap<>())
.entrySet()) {
File pythonFile = distributedCache.getFile(entry.getKey());
String filePath = pythonFile.getAbsolutePath();
pythonFiles.put(filePath, entry.getValue());
}
String requirementsFilePath = null;
String requirementsCacheDir = null;
String requirementsFileName =
config.getOptional(PYTHON_REQUIREMENTS_FILE_DISTRIBUTED_CACHE_INFO)
.orElse(new HashMap<>())
.get(PythonDependencyUtils.FILE);
if (requirementsFileName != null) {
requirementsFilePath = distributedCache.getFile(requirementsFileName).getAbsolutePath();
String requirementsFileCacheDir =
config.getOptional(PYTHON_REQUIREMENTS_FILE_DISTRIBUTED_CACHE_INFO)
.orElse(new HashMap<>())
.get(PythonDependencyUtils.CACHE);
if (requirementsFileCacheDir != null) {
requirementsCacheDir =
distributedCache.getFile(requirementsFileCacheDir).getAbsolutePath();
}
}
Map<String, String> archives = new HashMap<>();
for (Map.Entry<String, String> entry :
config.getOptional(PYTHON_ARCHIVES_DISTRIBUTED_CACHE_INFO)
.orElse(new HashMap<>())
.entrySet()) {
String archiveFilePath = distributedCache.getFile(entry.getKey()).getAbsolutePath();
String targetPath = entry.getValue();
archives.put(archiveFilePath, targetPath);
}
String pythonExec = config.get(PYTHON_EXECUTABLE);
return new PythonDependencyInfo(
pythonFiles,
requirementsFilePath,
requirementsCacheDir,
archives,
pythonExec,
config.get(PYTHON_EXECUTION_MODE),
config.get(PYTHON_PATH));
}
}
| PythonDependencyInfo |
java | apache__avro | lang/java/mapred/src/test/java/org/apache/avro/mapred/TestReflectJob.java | {
"start": 2417,
"end": 2823
} | class ____ extends AvroMapper<Text, Pair<Text, Count>> {
@Override
public void map(Text text, AvroCollector<Pair<Text, Count>> collector, Reporter reporter) throws IOException {
StringTokenizer tokens = new StringTokenizer(text.toString());
while (tokens.hasMoreTokens())
collector.collect(new Pair<>(new Text(tokens.nextToken()), new Count(1L)));
}
}
public static | MapImpl |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/sql/ast/SQLExprComparor.java | {
"start": 73,
"end": 761
} | class ____ implements Comparator<SQLExpr> {
public static final SQLExprComparor instance = new SQLExprComparor();
@Override
public int compare(SQLExpr a, SQLExpr b) {
return compareTo(a, b);
}
public static int compareTo(SQLExpr a, SQLExpr b) {
if (a == null && b == null) {
return 0;
}
if (a == null) {
return -1;
}
if (b == null) {
return 1;
}
if (a.getClass() == b.getClass() && a instanceof Comparable) {
return ((Comparable) a).compareTo(b);
}
return a.getClass().getName().compareTo(b.getClass().getName());
}
}
| SQLExprComparor |
java | google__guava | android/guava-tests/test/com/google/common/primitives/DoubleArrayAsListTest.java | {
"start": 3404,
"end": 3743
} | class ____ extends TestDoubleListGenerator {
@Override
protected List<Double> create(Double[] elements) {
Double[] suffix = {Double.MIN_VALUE, Double.MAX_VALUE};
Double[] all = concat(elements, suffix);
return asList(all).subList(0, elements.length);
}
}
public static final | DoublesAsListHeadSubListGenerator |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/resource/basic/SubResourceInterfaceAndClientInterfaceTest.java | {
"start": 7480,
"end": 7575
} | interface ____ {
@GET
String getSomeField();
}
}
| SubResourceRestClientInterface |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.