language
stringclasses 1
value | repo
stringclasses 60
values | path
stringlengths 22
294
| class_span
dict | source
stringlengths 13
1.16M
| target
stringlengths 1
113
|
|---|---|---|---|---|---|
java
|
apache__camel
|
components/camel-nitrite/src/main/java/org/apache/camel/component/nitrite/NitriteComponent.java
|
{
"start": 4141,
"end": 5312
}
|
class ____ {
Nitrite database;
String collection;
String repositoryName;
Class<?> repositoryClass;
CollectionCacheKey(NitriteEndpoint endpoint) {
database = endpoint.getNitriteDatabase();
collection = endpoint.getCollection();
repositoryName = endpoint.getRepositoryName();
repositoryClass = endpoint.getRepositoryClass();
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
CollectionCacheKey that = (CollectionCacheKey) o;
return database.equals(that.database)
&& Objects.equals(collection, that.collection)
&& Objects.equals(repositoryName, that.repositoryName)
&& Objects.equals(repositoryClass, that.repositoryClass);
}
@Override
public int hashCode() {
return Objects.hash(database, collection, repositoryName, repositoryClass);
}
}
}
|
CollectionCacheKey
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/metrics/SystemMetricsPublisher.java
|
{
"start": 1404,
"end": 2157
}
|
interface ____ {
void appCreated(RMApp app, long createdTime);
void appLaunched(RMApp app, long launchTime);
void appACLsUpdated(RMApp app, String appViewACLs, long updatedTime);
void appUpdated(RMApp app, long updatedTime);
void appStateUpdated(RMApp app, YarnApplicationState appState,
long updatedTime);
void appFinished(RMApp app, RMAppState state, long finishedTime);
void appAttemptRegistered(RMAppAttempt appAttempt, long registeredTime);
void appAttemptFinished(RMAppAttempt appAttempt,
RMAppAttemptState appAttemtpState, RMApp app, long finishedTime);
void containerCreated(RMContainer container, long createdTime);
void containerFinished(RMContainer container, long finishedTime);
}
|
SystemMetricsPublisher
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapred/JobInfo.java
|
{
"start": 1290,
"end": 2381
}
|
class ____ implements Writable {
private org.apache.hadoop.mapreduce.JobID id;
private Text user;
private Path jobSubmitDir;
public JobInfo() {}
public JobInfo(org.apache.hadoop.mapreduce.JobID id,
Text user,
Path jobSubmitDir) {
this.id = id;
this.user = user;
this.jobSubmitDir = jobSubmitDir;
}
/**
* Get the job id.
*/
public org.apache.hadoop.mapreduce.JobID getJobID() {
return id;
}
/**
* Get the configured job's user-name.
*/
public Text getUser() {
return user;
}
/**
* Get the job submission directory
*/
public Path getJobSubmitDir() {
return this.jobSubmitDir;
}
public void readFields(DataInput in) throws IOException {
id = new org.apache.hadoop.mapreduce.JobID();
id.readFields(in);
user = new Text();
user.readFields(in);
jobSubmitDir = new Path(WritableUtils.readString(in));
}
public void write(DataOutput out) throws IOException {
id.write(out);
user.write(out);
WritableUtils.writeString(out, jobSubmitDir.toString());
}
}
|
JobInfo
|
java
|
alibaba__druid
|
core/src/main/java/com/alibaba/druid/sql/dialect/oracle/ast/expr/OracleAnalyticWindowing.java
|
{
"start": 2073,
"end": 2242
}
|
enum ____ {
ROWS, RANGE;
}
@Override
public List<SQLObject> getChildren() {
return Collections.<SQLObject>singletonList(this.expr);
}
}
|
Type
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/extension/TestInstancePostProcessorAndPreDestroyCallbackTests.java
|
{
"start": 5930,
"end": 6076
}
|
class ____ extends AbstractTestInstanceCallbacks {
protected BazTestInstanceCallbacks() {
super("baz");
}
}
static
|
BazTestInstanceCallbacks
|
java
|
junit-team__junit5
|
jupiter-tests/src/test/java/org/junit/jupiter/engine/NestedTestClassesTests.java
|
{
"start": 16075,
"end": 16206
}
|
interface ____ {
@SuppressWarnings({ "JUnitMalformedDeclaration", "NewClassNamingConvention" })
@Nested
|
InterfaceWithNestedClass
|
java
|
redisson__redisson
|
redisson-hibernate/redisson-hibernate-52/src/main/java/org/redisson/hibernate/strategy/ReadWriteEntityRegionAccessStrategy.java
|
{
"start": 1263,
"end": 3010
}
|
class ____ extends AbstractReadWriteAccessStrategy implements EntityRegionAccessStrategy {
public ReadWriteEntityRegionAccessStrategy(Settings settings, GeneralDataRegion region, RMapCache<Object, Object> mapCache) {
super(settings, region, mapCache);
}
@Override
public EntityRegion getRegion() {
return (EntityRegion) region;
}
@Override
public boolean insert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException {
return false;
}
@Override
public boolean afterInsert(SharedSessionContractImplementor session, Object key, Object value, Object version) throws CacheException {
region.put(session, key, value);
return true;
}
@Override
public boolean update(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion)
throws CacheException {
return false;
}
@Override
public boolean afterUpdate(SharedSessionContractImplementor session, Object key, Object value, Object currentVersion, Object previousVersion, SoftLock lock)
throws CacheException {
region.put(session, key, value);
return true;
}
@Override
public Object generateCacheKey(Object id, EntityPersister persister, SessionFactoryImplementor factory, String tenantIdentifier) {
return ((RedissonEntityRegion)region).getCacheKeysFactory().createEntityKey(id, persister, factory, tenantIdentifier);
}
@Override
public Object getCacheKeyId(Object cacheKey) {
return ((RedissonEntityRegion)region).getCacheKeysFactory().getEntityId(cacheKey);
}
}
|
ReadWriteEntityRegionAccessStrategy
|
java
|
FasterXML__jackson-databind
|
src/test/java/tools/jackson/databind/jsontype/ExistingPropertyTest.java
|
{
"start": 4931,
"end": 5010
}
|
class ____ extends Bean1635 {
public int value;
}
static
|
Bean1635A
|
java
|
apache__camel
|
dsl/camel-jbang/camel-jbang-it/src/test/java/org/apache/camel/dsl/jbang/it/DependencyListITCase.java
|
{
"start": 1129,
"end": 2517
}
|
class ____ extends JBangTestSupport {
@Test
@InVersion(includeSnapshot = false)
public void testDependencyList() {
checkCommandOutputs("dependency list", "org.apache.camel:camel-main:" + version());
checkCommandOutputs("dependency list --output=maven", "<dependency>\n" +
" <groupId>org.apache.camel</groupId>\n" +
" <artifactId>camel-main</artifactId>\n" +
" <version>" + version() + "</version>\n" +
"</dependency>");
checkCommandOutputs("dependency list --runtime=spring-boot",
"org.apache.camel.springboot:camel-spring-boot-starter:" + version());
}
@Test
@InVersion(includeSnapshot = false)
public void testCopyingJars() throws IOException {
Files.createDirectory(Path.of(getDataFolder() + "/deps"));
execute(String.format("dependency copy --output-directory=%s/deps", mountPoint()));
Assertions.assertThat(execInHost(String.format("ls %s/deps", getDataFolder())))
.as("deps directory should contain copied dependency jars")
.containsPattern("camel-.*" + version() + ".jar");
}
}
|
DependencyListITCase
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/alias/AbstractJavaKeyStoreProvider.java
|
{
"start": 1850,
"end": 2412
}
|
class ____ implementing credential providers that are based on
* Java Keystores as the underlying credential store.
*
* The password for the keystore is taken from the HADOOP_CREDSTORE_PASSWORD
* environment variable with a default of 'none'.
*
* It is expected that for access to credential protected resource to copy the
* creds from the original provider into the job's Credentials object, which is
* accessed via the UserProvider. Therefore, these providers won't be directly
* used by MapReduce tasks.
*/
@InterfaceAudience.Private
public abstract
|
for
|
java
|
google__error-prone
|
core/src/test/java/com/google/errorprone/bugpatterns/collectionincompatibletype/IncompatibleArgumentTypeTest.java
|
{
"start": 3446,
"end": 3526
}
|
class ____ {
void doSomething(@CompatibleWith("Y") Object x) {}
}
|
Bar
|
java
|
quarkusio__quarkus
|
extensions/hibernate-orm/runtime/src/main/java/io/quarkus/hibernate/orm/runtime/session/JTASessionOpener.java
|
{
"start": 454,
"end": 584
}
|
class ____ to cache session options when possible;
* if we didn't care about caching, we could just replace any call to
*/
public
|
is
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/iterables/Iterables_assertContainsSequence_Test.java
|
{
"start": 1889,
"end": 8332
}
|
class ____ extends IterablesBaseTest {
@Override
@BeforeEach
public void setUp() {
super.setUp();
actual = newArrayList("Yoda", "Luke", "Leia", "Obi-Wan");
}
@Test
void should_throw_error_if_sequence_is_null() {
assertThatNullPointerException().isThrownBy(() -> {
Object[] nullArray = null;
iterables.assertContainsSequence(someInfo(), actual, nullArray);
}).withMessage(valuesToLookForIsNull());
}
@Test
void should_pass_if_actual_and_given_values_are_empty() {
actual.clear();
iterables.assertContainsSequence(someInfo(), actual, array());
}
@Test
void should_fail_if_array_of_values_to_look_for_is_empty_and_actual_is_not() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> iterables.assertContainsSequence(someInfo(), actual,
emptyArray()));
}
@Test
void should_fail_if_actual_is_null() {
assertThatExceptionOfType(AssertionError.class).isThrownBy(() -> iterables.assertContainsSequence(someInfo(), null,
array("Yoda")))
.withMessage(actualIsNull());
}
@Test
void should_fail_if_sequence_is_bigger_than_actual() {
AssertionInfo info = someInfo();
Object[] sequence = { "Luke", "Leia", "Obi-Wan", "Han", "C-3PO", "R2-D2", "Anakin" };
Throwable error = catchThrowable(() -> iterables.assertContainsSequence(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verifyFailureThrownWhenSequenceNotFound(info, sequence);
}
@Test
void should_fail_if_actual_does_not_contain_whole_sequence() {
AssertionInfo info = someInfo();
Object[] sequence = { "Han", "C-3PO" };
Throwable error = catchThrowable(() -> iterables.assertContainsSequence(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verifyFailureThrownWhenSequenceNotFound(info, sequence);
}
@Test
void should_fail_if_actual_contains_first_elements_of_sequence_but_not_whole_sequence() {
AssertionInfo info = someInfo();
Object[] sequence = { "Luke", "Leia", "Han" };
Throwable error = catchThrowable(() -> iterables.assertContainsSequence(info, actual, sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verifyFailureThrownWhenSequenceNotFound(info, sequence);
}
private void verifyFailureThrownWhenSequenceNotFound(AssertionInfo info, Object[] sequence) {
verify(failures).failure(info, shouldContainSequence(actual, sequence));
}
@Test
void should_pass_if_actual_contains_sequence() {
iterables.assertContainsSequence(someInfo(), actual, array("Luke", "Leia"));
}
@Test
void should_pass_if_actual_and_sequence_are_equal() {
iterables.assertContainsSequence(someInfo(), actual, array("Yoda", "Luke", "Leia", "Obi-Wan"));
}
@Test
void should_pass_if_actual_contains_both_partial_and_complete_sequence() {
actual = newArrayList("Yoda", "Luke", "Yoda", "Obi-Wan");
iterables.assertContainsSequence(someInfo(), actual, array("Yoda", "Obi-Wan"));
}
@Test
void should_pass_if_actual_contains_sequence_that_specifies_multiple_times_the_same_value_bug_544() {
actual = newArrayList("a", "-", "b", "-", "c");
iterables.assertContainsSequence(someInfo(), actual, array("a", "-", "b", "-", "c"));
}
@Test
void should_pass_if_actual_is_an_infinite_sequence_and_contains_sequence() {
Iterable<String> actual = com.google.common.collect.Iterables.cycle("Leia", "Luke", "Yoda", "Obi-Wan");
iterables.assertContainsSequence(someInfo(), actual, array("Luke", "Yoda", "Obi-Wan", "Leia"));
iterables.assertContainsSequence(someInfo(), actual, array("Luke", "Yoda"));
iterables.assertContainsSequence(someInfo(), actual, array("Luke", "Yoda", "Obi-Wan", "Leia", "Luke", "Yoda"));
}
@Test
void should_pass_if_actual_is_a_singly_traversable_sequence_and_contains_sequence() {
Iterable<String> actual = SinglyIterableFactory.createSinglyIterable(list("Leia", "Luke", "Yoda", "Obi-Wan"));
iterables.assertContainsSequence(someInfo(), actual, array("Leia", "Luke", "Yoda", "Obi-Wan"));
}
// ------------------------------------------------------------------------------------------------------------------
// tests using a custom comparison strategy
// ------------------------------------------------------------------------------------------------------------------
@Test
void should_fail_if_actual_does_not_contain_whole_sequence_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
Object[] sequence = { "Han", "C-3PO" };
Throwable error = catchThrowable(() -> iterablesWithCaseInsensitiveComparisonStrategy.assertContainsSequence(info, actual,
sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainSequence(actual, sequence, comparisonStrategy));
}
@Test
void should_fail_if_actual_contains_first_elements_of_sequence_but_not_whole_sequence_according_to_custom_comparison_strategy() {
AssertionInfo info = someInfo();
Object[] sequence = { "Luke", "Leia", "Han" };
Throwable error = catchThrowable(() -> iterablesWithCaseInsensitiveComparisonStrategy.assertContainsSequence(info, actual,
sequence));
assertThat(error).isInstanceOf(AssertionError.class);
verify(failures).failure(info, shouldContainSequence(actual, sequence, comparisonStrategy));
}
@Test
void should_pass_if_actual_contains_sequence_according_to_custom_comparison_strategy() {
iterablesWithCaseInsensitiveComparisonStrategy.assertContainsSequence(someInfo(), actual, array("LUKe", "leia"));
}
@Test
void should_pass_if_actual_and_sequence_are_equal_according_to_custom_comparison_strategy() {
iterablesWithCaseInsensitiveComparisonStrategy.assertContainsSequence(someInfo(), actual,
array("YODA", "luke", "lEIA", "Obi-wan"));
}
}
|
Iterables_assertContainsSequence_Test
|
java
|
apache__camel
|
components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/InlineQueryResultGame.java
|
{
"start": 1191,
"end": 1532
}
|
class ____ extends InlineQueryResult {
private static final String TYPE = "game";
@JsonProperty("game_short_name")
private String gameShortName;
public InlineQueryResultGame() {
super(TYPE);
}
public static Builder builder() {
return new Builder();
}
public static final
|
InlineQueryResultGame
|
java
|
apache__kafka
|
jmh-benchmarks/src/main/java/org/apache/kafka/jmh/core/TestPurgatoryPerformance.java
|
{
"start": 17979,
"end": 18700
}
|
class ____ extends DelayedOperation {
final long completesAt;
final long latencyMs;
final CountDownLatch latch;
public FakeOperation(long delayMs, long latencyMs, CountDownLatch latch) {
super(delayMs);
this.latencyMs = latencyMs;
this.latch = latch;
completesAt = System.currentTimeMillis() + delayMs;
}
@Override
public void onExpiration() {
}
@Override
public void onComplete() {
latch.countDown();
}
@Override
public boolean tryComplete() {
return System.currentTimeMillis() >= completesAt && forceComplete();
}
}
}
|
FakeOperation
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/error/ElementsShouldMatch_create_Test.java
|
{
"start": 1111,
"end": 3296
}
|
class ____ {
@Test
void should_create_error_message_with_one_non_matching_element() {
// GIVEN
ErrorMessageFactory factory = elementsShouldMatch(list("Luke", "Yoda"), "Yoda", PredicateDescription.GIVEN);
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting all elements of:%n" +
" [\"Luke\", \"Yoda\"]%n" +
"to match given predicate but this element did not:%n" +
" \"Yoda\""));
}
@Test
void should_create_error_message_with_multiple_non_matching_elements() {
// GIVEN
ErrorMessageFactory factory = elementsShouldMatch(list("Luke", "Yoda"),
list("Luke", "Yoda"),
PredicateDescription.GIVEN);
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting all elements of:%n" +
" [\"Luke\", \"Yoda\"]%n" +
"to match given predicate but these elements did not:%n" +
" [\"Luke\", \"Yoda\"]"));
}
@Test
void should_create_error_message_with_custom_description() {
// GIVEN
ErrorMessageFactory factory = elementsShouldMatch(list("Luke", "Yoda"), "Yoda",
new PredicateDescription("custom"));
// WHEN
String message = factory.create(new TextDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(message).isEqualTo(format("[Test] %n" +
"Expecting all elements of:%n" +
" [\"Luke\", \"Yoda\"]%n" +
"to match 'custom' predicate but this element did not:%n" +
" \"Yoda\""));
}
}
|
ElementsShouldMatch_create_Test
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/ComponentBuilderTest.java
|
{
"start": 2119,
"end": 2482
}
|
class ____ {",
" @Provides String string() { return null; }",
"}");
Source componentFile =
CompilerTests.javaSource(
"test.TestComponent",
"package test;",
"",
"import dagger.Component;",
"",
"@Component(modules = TestModule.class)",
"
|
TestModule
|
java
|
apache__camel
|
core/camel-api/src/main/java/org/apache/camel/cloud/ServiceCallConstants.java
|
{
"start": 872,
"end": 1317
}
|
interface ____ {
String SERVICE_CALL_SCHEME = "CamelServiceCallScheme";
String SERVICE_CALL_URI = "CamelServiceCallUri";
String SERVICE_CALL_CONTEXT_PATH = "CamelServiceCallContextPath";
String SERVICE_NAME = "CamelServiceCallServiceName";
String SERVICE_META = "CamelServiceCallServiceMeta";
String SERVICE_HOST = "CamelServiceCallServiceHost";
String SERVICE_PORT = "CamelServiceCallServicePort";
}
|
ServiceCallConstants
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/aggregation/MaxIpAggregator.java
|
{
"start": 2251,
"end": 3425
}
|
class ____ implements GroupingAggregatorState {
private final BytesRef scratch = new BytesRef();
private final IpArrayState internalState;
private GroupingState(BigArrays bigArrays) {
this.internalState = new IpArrayState(bigArrays, INIT_VALUE);
}
public void add(int groupId, BytesRef value) {
if (isBetter(value, internalState.getOrDefault(groupId, scratch))) {
internalState.set(groupId, value);
}
}
@Override
public void toIntermediate(Block[] blocks, int offset, IntVector selected, DriverContext driverContext) {
internalState.toIntermediate(blocks, offset, selected, driverContext);
}
Block toBlock(IntVector selected, DriverContext driverContext) {
return internalState.toValuesBlock(selected, driverContext);
}
@Override
public void enableGroupIdTracking(SeenGroupIds seen) {
internalState.enableGroupIdTracking(seen);
}
@Override
public void close() {
Releasables.close(internalState);
}
}
public static
|
GroupingState
|
java
|
apache__flink
|
flink-table/flink-sql-parser/src/main/java/org/apache/flink/sql/parser/dml/SqlExecutePlan.java
|
{
"start": 1406,
"end": 2258
}
|
class ____ extends SqlCall {
public static final SqlSpecialOperator OPERATOR =
new SqlSpecialOperator("EXECUTE PLAN", SqlKind.OTHER);
private final SqlNode planFile;
public SqlExecutePlan(SqlParserPos pos, SqlNode planFile) {
super(pos);
this.planFile = planFile;
}
public String getPlanFile() {
return SqlParseUtils.extractString(planFile);
}
@Nonnull
@Override
public SqlOperator getOperator() {
return OPERATOR;
}
@Nonnull
@Override
public List<SqlNode> getOperandList() {
return Collections.emptyList();
}
@Override
public void unparse(SqlWriter writer, int leftPrec, int rightPrec) {
writer.keyword("EXECUTE");
writer.keyword("PLAN");
planFile.unparse(writer, leftPrec, rightPrec);
}
}
|
SqlExecutePlan
|
java
|
spring-projects__spring-boot
|
loader/spring-boot-loader-tools/src/main/java/org/springframework/boot/loader/tools/FileUtils.java
|
{
"start": 1091,
"end": 2949
}
|
class ____ {
/**
* Utility to remove duplicate files from an "output" directory if they already exist
* in an "origin". Recursively scans the origin directory looking for files (not
* directories) that exist in both places and deleting the copy.
* @param outputDirectory the output directory
* @param originDirectory the origin directory
*/
public static void removeDuplicatesFromOutputDirectory(File outputDirectory, File originDirectory) {
if (originDirectory.isDirectory()) {
String[] files = originDirectory.list();
Assert.state(files != null, "'files' must not be null");
for (String name : files) {
File targetFile = new File(outputDirectory, name);
if (targetFile.exists() && targetFile.canWrite()) {
if (!targetFile.isDirectory()) {
targetFile.delete();
}
else {
FileUtils.removeDuplicatesFromOutputDirectory(targetFile, new File(originDirectory, name));
}
}
}
}
}
/**
* Returns {@code true} if the given jar file has been signed.
* @param file the file to check
* @return if the file has been signed
* @throws IOException on IO error
*/
public static boolean isSignedJarFile(@Nullable File file) throws IOException {
if (file == null) {
return false;
}
try (JarFile jarFile = new JarFile(file)) {
if (hasDigestEntry(jarFile.getManifest())) {
return true;
}
}
return false;
}
private static boolean hasDigestEntry(@Nullable Manifest manifest) {
return (manifest != null) && manifest.getEntries().values().stream().anyMatch(FileUtils::hasDigestName);
}
private static boolean hasDigestName(Attributes attributes) {
return attributes.keySet().stream().anyMatch(FileUtils::isDigestName);
}
private static boolean isDigestName(Object name) {
return String.valueOf(name).toUpperCase(Locale.ROOT).endsWith("-DIGEST");
}
}
|
FileUtils
|
java
|
quarkusio__quarkus
|
extensions/grpc/api/src/main/java/io/quarkus/grpc/ExceptionHandler.java
|
{
"start": 177,
"end": 1282
}
|
class ____<ReqT, RespT> extends
ForwardingServerCallListener.SimpleForwardingServerCallListener<ReqT> {
private final ServerCall<ReqT, RespT> call;
private final Metadata metadata;
public ExceptionHandler(ServerCall.Listener<ReqT> listener, ServerCall<ReqT, RespT> call, Metadata metadata) {
super(listener);
this.metadata = metadata;
this.call = call;
}
protected abstract void handleException(Throwable t, ServerCall<ReqT, RespT> call, Metadata metadata);
@Override
public void onMessage(ReqT message) {
try {
super.onMessage(message);
} catch (Throwable t) {
handleException(t, call, metadata);
}
}
@Override
public void onHalfClose() {
try {
super.onHalfClose();
} catch (Throwable t) {
handleException(t, call, metadata);
}
}
@Override
public void onReady() {
try {
super.onReady();
} catch (Throwable t) {
handleException(t, call, metadata);
}
}
}
|
ExceptionHandler
|
java
|
elastic__elasticsearch
|
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/voyageai/embeddings/VoyageAIEmbeddingType.java
|
{
"start": 1600,
"end": 3910
}
|
class ____ {
private static final String FLOAT = "float";
private static final String INT8 = "int8";
private static final String BINARY = "binary";
}
private static final Map<DenseVectorFieldMapper.ElementType, VoyageAIEmbeddingType> ELEMENT_TYPE_TO_VOYAGE_EMBEDDING = Map.of(
DenseVectorFieldMapper.ElementType.FLOAT,
FLOAT,
DenseVectorFieldMapper.ElementType.BYTE,
BYTE,
DenseVectorFieldMapper.ElementType.BIT,
BIT
);
static final EnumSet<DenseVectorFieldMapper.ElementType> SUPPORTED_ELEMENT_TYPES = EnumSet.copyOf(
ELEMENT_TYPE_TO_VOYAGE_EMBEDDING.keySet()
);
private final DenseVectorFieldMapper.ElementType elementType;
private final String requestString;
VoyageAIEmbeddingType(DenseVectorFieldMapper.ElementType elementType, String requestString) {
this.elementType = elementType;
this.requestString = requestString;
}
@Override
public String toString() {
return name().toLowerCase(Locale.ROOT);
}
public String toRequestString() {
return requestString;
}
public static String toLowerCase(VoyageAIEmbeddingType type) {
return type.toString().toLowerCase(Locale.ROOT);
}
public static VoyageAIEmbeddingType fromString(String name) {
return valueOf(name.trim().toUpperCase(Locale.ROOT));
}
public static VoyageAIEmbeddingType fromElementType(DenseVectorFieldMapper.ElementType elementType) {
var embedding = ELEMENT_TYPE_TO_VOYAGE_EMBEDDING.get(elementType);
if (embedding == null) {
var validElementTypes = SUPPORTED_ELEMENT_TYPES.stream()
.map(value -> value.toString().toLowerCase(Locale.ROOT))
.toArray(String[]::new);
Arrays.sort(validElementTypes);
throw new IllegalArgumentException(
Strings.format(
"Element type [%s] does not map to a VoyageAI embedding value, must be one of [%s]",
elementType,
String.join(", ", validElementTypes)
)
);
}
return embedding;
}
public DenseVectorFieldMapper.ElementType toElementType() {
return elementType;
}
}
|
RequestConstants
|
java
|
spring-projects__spring-boot
|
core/spring-boot-test/src/main/java/org/springframework/boot/test/context/SpringBootContextLoader.java
|
{
"start": 19863,
"end": 20599
}
|
class ____
implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private final ContextCustomizer contextCustomizer;
private final MergedContextConfiguration mergedConfig;
ContextCustomizerAdapter(ContextCustomizer contextCustomizer, MergedContextConfiguration mergedConfig) {
this.contextCustomizer = contextCustomizer;
this.mergedConfig = mergedConfig;
}
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
this.contextCustomizer.customizeContext(applicationContext, this.mergedConfig);
}
}
/**
* {@link ApplicationContextInitializer} used to set the parent context.
*/
@Order(Ordered.HIGHEST_PRECEDENCE)
private static
|
ContextCustomizerAdapter
|
java
|
elastic__elasticsearch
|
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/predicate/operator/arithmetic/BinaryComparisonInversible.java
|
{
"start": 467,
"end": 737
}
|
interface ____ arithmetic operations that have an inverse in reference to a binary comparison.
* For instance the division is multiplication's inverse, substitution addition's, log exponentiation's a.s.o.
* Not all operations - like modulo - are invertible.
*/
public
|
for
|
java
|
FasterXML__jackson-databind
|
src/main/java/tools/jackson/databind/ser/jdk/JDKKeySerializers.java
|
{
"start": 7944,
"end": 10313
}
|
class ____ extends StdSerializer<Object>
{
// Important: MUST be transient, to allow serialization of key serializer itself
protected transient PropertySerializerMap _dynamicSerializers;
public Dynamic() {
super(String.class);
_dynamicSerializers = PropertySerializerMap.emptyForProperties();
}
Object readResolve() {
// Since it's transient, and since JDK serialization by-passes ctor, need this:
_dynamicSerializers = PropertySerializerMap.emptyForProperties();
return this;
}
@Override
public void serialize(Object value, JsonGenerator g, SerializationContext provider)
throws JacksonException
{
Class<?> cls = value.getClass();
PropertySerializerMap m = _dynamicSerializers;
ValueSerializer<Object> ser = m.serializerFor(cls);
if (ser == null) {
ser = _findAndAddDynamic(m, cls, provider);
}
ser.serialize(value, g, provider);
}
@Override
public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) {
visitStringFormat(visitor, typeHint);
}
protected ValueSerializer<Object> _findAndAddDynamic(PropertySerializerMap map,
Class<?> type, SerializationContext provider)
{
// 27-Jun-2017, tatu: [databind#1679] Need to avoid StackOverflowError...
if (type == Object.class) {
// basically just need to call `toString()`, easiest way:
ValueSerializer<Object> ser = new Default(Default.TYPE_TO_STRING, type);
_dynamicSerializers = map.newWith(type, ser);
return ser;
}
PropertySerializerMap.SerializerAndMapResult result =
// null -> for now we won't keep ref or pass BeanProperty; could change
map.findAndAddKeySerializer(type, provider, null);
// did we get a new map of serializers? If so, start using it
if (map != result.map) {
_dynamicSerializers = result.map;
}
return result.serializer;
}
}
/**
* Simple and fast key serializer when keys are Strings.
*/
public static
|
Dynamic
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/main/java/org/springframework/boot/info/SslInfo.java
|
{
"start": 7220,
"end": 7795
}
|
class ____ {
static final CertificateValidityInfo VALID = new CertificateValidityInfo(Status.VALID, null);
private final Status status;
private final @Nullable String message;
CertificateValidityInfo(Status status, @Nullable String message, Object... messageArgs) {
this.status = status;
this.message = (message != null) ? message.formatted(messageArgs) : null;
}
public Status getStatus() {
return this.status;
}
public @Nullable String getMessage() {
return this.message;
}
/**
* Validity Status.
*/
public
|
CertificateValidityInfo
|
java
|
dropwizard__dropwizard
|
dropwizard-testing/src/test/java/io/dropwizard/testing/junit5/DropwizardExtensionsSupportTest.java
|
{
"start": 1617,
"end": 2120
}
|
class ____ implements AfterEachCallback {
@Override
public void afterEach(ExtensionContext context) throws Exception {
DelayedAssertionsTest testInstance = (DelayedAssertionsTest) context.getTestInstance()
.orElseThrow(() -> new AssertionError("Null context.testInstance"));
testInstance.getDelayedAssertions().forEach(Invokable::invoke);
}
}
// -----------------------
// The rest of the classes in this file set up various different test
|
CallbackVerifyingExtension
|
java
|
spring-projects__spring-security
|
config/src/test/java/org/springframework/security/config/annotation/web/configurers/HttpBasicConfigurerTests.java
|
{
"start": 11504,
"end": 11977
}
|
class ____ {
@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeHttpRequests((authorize) -> authorize
.anyRequest().authenticated()
)
.httpBasic(withDefaults());
// @formatter:on
return http.build();
}
@Bean
UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager();
}
}
@Configuration
@EnableWebSecurity
static
|
DefaultsLambdaEntryPointConfig
|
java
|
apache__camel
|
components/camel-telegram/src/main/java/org/apache/camel/component/telegram/model/InlineQueryResultCachedVideo.java
|
{
"start": 1853,
"end": 5087
}
|
class ____ {
private String id;
private InlineKeyboardMarkup replyMarkup;
private String videoFileId;
private String title;
private String caption;
private String description;
private String parseMode;
private InputMessageContent inputMessageContext;
private Builder() {
}
public Builder id(String id) {
this.id = id;
return this;
}
public Builder replyMarkup(InlineKeyboardMarkup replyMarkup) {
this.replyMarkup = replyMarkup;
return this;
}
public Builder videoFileId(String videoFileId) {
this.videoFileId = videoFileId;
return this;
}
public Builder title(String title) {
this.title = title;
return this;
}
public Builder caption(String caption) {
this.caption = caption;
return this;
}
public Builder description(String description) {
this.description = description;
return this;
}
public Builder parseMode(String parseMode) {
this.parseMode = parseMode;
return this;
}
public Builder inputMessageContext(InputMessageContent inputMessageContext) {
this.inputMessageContext = inputMessageContext;
return this;
}
public InlineQueryResultCachedVideo build() {
InlineQueryResultCachedVideo inlineQueryResultVideo = new InlineQueryResultCachedVideo();
inlineQueryResultVideo.setType(TYPE);
inlineQueryResultVideo.setId(id);
inlineQueryResultVideo.setReplyMarkup(replyMarkup);
inlineQueryResultVideo.videoFileId = this.videoFileId;
inlineQueryResultVideo.caption = this.caption;
inlineQueryResultVideo.inputMessageContext = this.inputMessageContext;
inlineQueryResultVideo.description = this.description;
inlineQueryResultVideo.parseMode = this.parseMode;
inlineQueryResultVideo.title = this.title;
return inlineQueryResultVideo;
}
}
public String getVideoFileId() {
return videoFileId;
}
public String getTitle() {
return title;
}
public String getCaption() {
return caption;
}
public String getDescription() {
return description;
}
public String getParseMode() {
return parseMode;
}
public InputMessageContent getInputMessageContext() {
return inputMessageContext;
}
public void setVideoFileId(String videoFileId) {
this.videoFileId = videoFileId;
}
public void setTitle(String title) {
this.title = title;
}
public void setCaption(String caption) {
this.caption = caption;
}
public void setDescription(String description) {
this.description = description;
}
public void setParseMode(String parseMode) {
this.parseMode = parseMode;
}
public void setInputMessageContext(InputMessageContent inputMessageContext) {
this.inputMessageContext = inputMessageContext;
}
}
|
Builder
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/test/java/org/apache/hadoop/yarn/server/federation/failover/TestFederationRMFailoverProxyProvider.java
|
{
"start": 1380,
"end": 2302
}
|
class ____ {
@Test
public void testRMFailoverProxyProvider() throws YarnException {
YarnConfiguration configuration = new YarnConfiguration();
RMFailoverProxyProvider<ApplicationClientProtocol> clientRMFailoverProxyProvider =
ClientRMProxy.getClientRMFailoverProxyProvider(configuration, ApplicationClientProtocol.class);
assertTrue(clientRMFailoverProxyProvider instanceof DefaultNoHARMFailoverProxyProvider);
FederationProxyProviderUtil.updateConfForFederation(configuration, "SC-1");
configuration.setBoolean(YarnConfiguration.FEDERATION_NON_HA_ENABLED,true);
RMFailoverProxyProvider<ApplicationClientProtocol> clientRMFailoverProxyProvider2 =
ClientRMProxy.getClientRMFailoverProxyProvider(configuration, ApplicationClientProtocol.class);
assertTrue(clientRMFailoverProxyProvider2 instanceof FederationRMFailoverProxyProvider);
}
}
|
TestFederationRMFailoverProxyProvider
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/client/protocol/convertor/TypeConvertor.java
|
{
"start": 740,
"end": 1574
}
|
class ____ implements Convertor<RType> {
@Override
public RType convert(Object obj) {
String val = obj.toString();
if ("string".equals(val)) {
return RType.OBJECT;
}
if ("list".equals(val)) {
return RType.LIST;
}
if ("set".equals(val)) {
return RType.SET;
}
if ("zset".equals(val)) {
return RType.ZSET;
}
if ("hash".equals(val)) {
return RType.MAP;
}
if ("stream".equals(val)) {
return RType.STREAM;
}
if ("ReJSON-RL".equals(val)) {
return RType.JSON;
}
if ("none".equals(val)) {
return null;
}
throw new IllegalStateException("Can't recognize redis type: " + obj);
}
}
|
TypeConvertor
|
java
|
apache__hadoop
|
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSNamesystem.java
|
{
"start": 2420,
"end": 12872
}
|
class ____ {
@AfterEach
public void cleanUp() {
FileUtil.fullyDeleteContents(new File(MiniDFSCluster.getBaseDirectory()));
}
/**
* Tests that the namenode edits dirs are gotten with duplicates removed
*/
@Test
public void testUniqueEditDirs() throws IOException {
Configuration config = new Configuration();
config.set(DFS_NAMENODE_EDITS_DIR_KEY, "file://edits/dir, "
+ "file://edits/dir1,file://edits/dir1"); // overlapping internally
// getNamespaceEditsDirs removes duplicates
Collection<URI> editsDirs = FSNamesystem.getNamespaceEditsDirs(config);
assertEquals(2, editsDirs.size());
}
/**
* Test that FSNamesystem#clear clears all leases.
*/
@Test
public void testFSNamespaceClearLeases() throws Exception {
Configuration conf = new HdfsConfiguration();
File nameDir = new File(MiniDFSCluster.getBaseDirectory(), "name");
conf.set(DFS_NAMENODE_NAME_DIR_KEY, nameDir.getAbsolutePath());
NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
DFSTestUtil.formatNameNode(conf);
FSNamesystem fsn = FSNamesystem.loadFromDisk(conf);
LeaseManager leaseMan = fsn.getLeaseManager();
leaseMan.addLease("client1", fsn.getFSDirectory().allocateNewInodeId());
assertEquals(1, leaseMan.countLease());
clearNamesystem(fsn);
leaseMan = fsn.getLeaseManager();
assertEquals(0, leaseMan.countLease());
}
@Test
/**
* Test that isInStartupSafemode returns true only during startup safemode
* and not also during low-resource safemode
*/
public void testStartupSafemode() throws IOException {
Configuration conf = new Configuration();
FSImage fsImage = Mockito.mock(FSImage.class);
FSEditLog fsEditLog = Mockito.mock(FSEditLog.class);
Mockito.when(fsImage.getEditLog()).thenReturn(fsEditLog);
FSNamesystem fsn = new FSNamesystem(conf, fsImage);
fsn.leaveSafeMode(false);
assertTrue(!fsn.isInStartupSafeMode(),
"After leaving safemode FSNamesystem.isInStartupSafeMode still " + "returned true");
assertTrue(!fsn.isInSafeMode(),
"After leaving safemode FSNamesystem.isInSafeMode still returned" + " true");
fsn.enterSafeMode(true);
assertTrue(!fsn.isInStartupSafeMode(),
"After entering safemode due to low resources FSNamesystem."
+ "isInStartupSafeMode still returned true");
assertTrue(fsn.isInSafeMode(), "After entering safemode due to low resources FSNamesystem."
+ "isInSafeMode still returned false");
}
@Test
public void testReplQueuesActiveAfterStartupSafemode() throws IOException, InterruptedException{
Configuration conf = new Configuration();
FSEditLog fsEditLog = Mockito.mock(FSEditLog.class);
FSImage fsImage = Mockito.mock(FSImage.class);
Mockito.when(fsImage.getEditLog()).thenReturn(fsEditLog);
FSNamesystem fsNamesystem = new FSNamesystem(conf, fsImage);
FSNamesystem fsn = Mockito.spy(fsNamesystem);
BlockManager bm = fsn.getBlockManager();
Whitebox.setInternalState(bm, "namesystem", fsn);
//Make shouldPopulaeReplQueues return true
HAContext haContext = Mockito.mock(HAContext.class);
HAState haState = Mockito.mock(HAState.class);
Mockito.when(haContext.getState()).thenReturn(haState);
Mockito.when(haState.shouldPopulateReplQueues()).thenReturn(true);
Mockito.when(fsn.getHAContext()).thenReturn(haContext);
//Make NameNode.getNameNodeMetrics() not return null
NameNode.initMetrics(conf, NamenodeRole.NAMENODE);
fsn.enterSafeMode(false);
assertTrue(fsn.isInSafeMode(), "FSNamesystem didn't enter safemode");
assertTrue(!bm.isPopulatingReplQueues(),
"Replication queues were being populated during very first " + "safemode");
fsn.leaveSafeMode(false);
assertTrue(!fsn.isInSafeMode(), "FSNamesystem didn't leave safemode");
assertTrue(bm.isPopulatingReplQueues(),
"Replication queues weren't being populated even after leaving " + "safemode");
fsn.enterSafeMode(false);
assertTrue(fsn.isInSafeMode(), "FSNamesystem didn't enter safemode");
assertTrue(bm.isPopulatingReplQueues(),
"Replication queues weren't being populated after entering " + "safemode 2nd time");
}
@Test
public void testHAStateInNamespaceInfo() throws IOException {
Configuration conf = new Configuration();
FSEditLog fsEditLog = Mockito.mock(FSEditLog.class);
FSImage fsImage = Mockito.mock(FSImage.class);
Mockito.when(fsImage.getEditLog()).thenReturn(fsEditLog);
NNStorage nnStorage = Mockito.mock(NNStorage.class);
Mockito.when(fsImage.getStorage()).thenReturn(nnStorage);
FSNamesystem fsNamesystem = new FSNamesystem(conf, fsImage);
FSNamesystem fsn = Mockito.spy(fsNamesystem);
Mockito.when(fsn.getState()).thenReturn(
HAServiceProtocol.HAServiceState.ACTIVE);
NamespaceInfo nsInfo = fsn.unprotectedGetNamespaceInfo();
assertNotNull(nsInfo.getState());
}
@Test
public void testReset() throws Exception {
Configuration conf = new Configuration();
FSEditLog fsEditLog = Mockito.mock(FSEditLog.class);
FSImage fsImage = Mockito.mock(FSImage.class);
Mockito.when(fsImage.getEditLog()).thenReturn(fsEditLog);
FSNamesystem fsn = new FSNamesystem(conf, fsImage);
fsn.imageLoadComplete();
assertTrue(fsn.isImageLoaded());
clearNamesystem(fsn);
final INodeDirectory root = (INodeDirectory) fsn.getFSDirectory()
.getINode("/");
assertTrue(root.getChildrenList(Snapshot.CURRENT_STATE_ID).isEmpty());
fsn.imageLoadComplete();
assertTrue(fsn.isImageLoaded());
}
private void clearNamesystem(FSNamesystem fsn) {
fsn.writeLock(RwLockMode.GLOBAL);
try {
fsn.clear();
assertFalse(fsn.isImageLoaded());
} finally {
fsn.writeUnlock(RwLockMode.GLOBAL, "clearNamesystem");
}
}
@Test
public void testGetEffectiveLayoutVersion() {
assertEquals(-63, FSNamesystem.getEffectiveLayoutVersion(true, -60, -61, -63));
assertEquals(-61, FSNamesystem.getEffectiveLayoutVersion(true, -61, -61, -63));
assertEquals(-62, FSNamesystem.getEffectiveLayoutVersion(true, -62, -61, -63));
assertEquals(-63, FSNamesystem.getEffectiveLayoutVersion(true, -63, -61, -63));
assertEquals(-63, FSNamesystem.getEffectiveLayoutVersion(false, -60, -61, -63));
assertEquals(-63, FSNamesystem.getEffectiveLayoutVersion(false, -61, -61, -63));
assertEquals(-63, FSNamesystem.getEffectiveLayoutVersion(false, -62, -61, -63));
assertEquals(-63, FSNamesystem.getEffectiveLayoutVersion(false, -63, -61, -63));
}
@Test
public void testSafemodeReplicationConf() throws IOException {
Configuration conf = new Configuration();
FSImage fsImage = Mockito.mock(FSImage.class);
FSEditLog fsEditLog = Mockito.mock(FSEditLog.class);
Mockito.when(fsImage.getEditLog()).thenReturn(fsEditLog);
conf.setInt(DFSConfigKeys.DFS_NAMENODE_REPLICATION_MIN_KEY, 2);
FSNamesystem fsn = new FSNamesystem(conf, fsImage);
Object bmSafeMode = Whitebox.getInternalState(fsn.getBlockManager(),
"bmSafeMode");
int safeReplication = (int)Whitebox.getInternalState(bmSafeMode,
"safeReplication");
assertEquals(2, safeReplication);
}
@Test
@Timeout(value = 30)
public void testInitAuditLoggers() throws IOException {
Configuration conf = new Configuration();
FSImage fsImage = Mockito.mock(FSImage.class);
FSEditLog fsEditLog = Mockito.mock(FSEditLog.class);
Mockito.when(fsImage.getEditLog()).thenReturn(fsEditLog);
FSNamesystem fsn;
List<AuditLogger> auditLoggers;
// Not to specify any audit loggers in config
conf.set(DFSConfigKeys.DFS_NAMENODE_AUDIT_LOGGERS_KEY, "");
// Disable top logger
conf.setBoolean(DFSConfigKeys.NNTOP_ENABLED_KEY, false);
conf.setBoolean(HADOOP_CALLER_CONTEXT_ENABLED_KEY, true);
fsn = new FSNamesystem(conf, fsImage);
auditLoggers = fsn.getAuditLoggers();
assertTrue(auditLoggers.size() == 1);
assertTrue(
auditLoggers.get(0) instanceof FSNamesystem.FSNamesystemAuditLogger);
FSNamesystem.FSNamesystemAuditLogger defaultAuditLogger =
(FSNamesystem.FSNamesystemAuditLogger) auditLoggers.get(0);
assertTrue(defaultAuditLogger.getCallerContextEnabled());
// Not to specify any audit loggers in config
conf.set(DFSConfigKeys.DFS_NAMENODE_AUDIT_LOGGERS_KEY, "");
// Enable top logger
conf.setBoolean(DFSConfigKeys.NNTOP_ENABLED_KEY, true);
fsn = new FSNamesystem(conf, fsImage);
auditLoggers = fsn.getAuditLoggers();
assertTrue(auditLoggers.size() == 2);
// the audit loggers order is not defined
for (AuditLogger auditLogger : auditLoggers) {
assertThat(auditLogger)
.isInstanceOfAny(FSNamesystem.FSNamesystemAuditLogger.class,
TopAuditLogger.class);
}
// Configure default audit loggers in config
conf.set(DFSConfigKeys.DFS_NAMENODE_AUDIT_LOGGERS_KEY, "default");
// Enable top logger
conf.setBoolean(DFSConfigKeys.NNTOP_ENABLED_KEY, true);
fsn = new FSNamesystem(conf, fsImage);
auditLoggers = fsn.getAuditLoggers();
assertTrue(auditLoggers.size() == 2);
for (AuditLogger auditLogger : auditLoggers) {
assertThat(auditLogger)
.isInstanceOfAny(FSNamesystem.FSNamesystemAuditLogger.class,
TopAuditLogger.class);
}
// Configure default and customized audit loggers in config with whitespaces
conf.set(DFSConfigKeys.DFS_NAMENODE_AUDIT_LOGGERS_KEY,
" default, org.apache.hadoop.hdfs.server.namenode.TestFSNamesystem$DummyAuditLogger ");
// Enable top logger
conf.setBoolean(DFSConfigKeys.NNTOP_ENABLED_KEY, true);
fsn = new FSNamesystem(conf, fsImage);
auditLoggers = fsn.getAuditLoggers();
assertTrue(auditLoggers.size() == 3);
for (AuditLogger auditLogger : auditLoggers) {
assertThat(auditLogger)
.isInstanceOfAny(FSNamesystem.FSNamesystemAuditLogger.class,
TopAuditLogger.class, DummyAuditLogger.class);
}
// Test Configuring TopAuditLogger.
conf.set(DFSConfigKeys.DFS_NAMENODE_AUDIT_LOGGERS_KEY,
"org.apache.hadoop.hdfs.server.namenode.top.TopAuditLogger");
fsn = new FSNamesystem(conf, fsImage);
auditLoggers = fsn.getAuditLoggers();
assertEquals(1, auditLoggers.size());
assertThat(auditLoggers.get(0)).isInstanceOf(TopAuditLogger.class);
}
static
|
TestFSNamesystem
|
java
|
apache__camel
|
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv2/WeatherModel.java
|
{
"start": 1055,
"end": 1629
}
|
class ____ {
@DataField(pos = 1)
private int id;
@DataField(pos = 2)
private String date;
@DataField(pos = 3, defaultValue = "North Pole")
private String place;
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
}
|
WeatherModel
|
java
|
apache__flink
|
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/window/groupwindow/triggers/ProcessingTimeTriggers.java
|
{
"start": 8315,
"end": 10348
}
|
class ____<W extends Window> extends WindowTrigger<W> {
private static final long serialVersionUID = 2310050856564792734L;
// early trigger is always not null
private final Trigger<W> earlyTrigger;
AfterEndOfWindowNoLate(Trigger<W> earlyTrigger) {
checkNotNull(earlyTrigger);
this.earlyTrigger = earlyTrigger;
}
@Override
public void open(TriggerContext ctx) throws Exception {
this.ctx = ctx;
earlyTrigger.open(ctx);
}
@Override
public boolean onElement(Object element, long timestamp, W window) throws Exception {
ctx.registerProcessingTimeTimer(triggerTime(window));
return earlyTrigger.onElement(element, timestamp, window);
}
@Override
public boolean onProcessingTime(long time, W window) throws Exception {
return time == triggerTime(window) || earlyTrigger.onProcessingTime(time, window);
}
@Override
public boolean onEventTime(long time, W window) throws Exception {
return earlyTrigger.onEventTime(time, window);
}
@Override
public boolean canMerge() {
return earlyTrigger.canMerge();
}
@Override
public void onMerge(W window, OnMergeContext mergeContext) throws Exception {
ctx.registerProcessingTimeTimer(triggerTime(window));
earlyTrigger.onMerge(window, mergeContext);
}
@Override
public void clear(W window) throws Exception {
ctx.deleteProcessingTimeTimer(triggerTime(window));
earlyTrigger.clear(window);
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(TO_STRING);
if (earlyTrigger != null) {
builder.append(".withEarlyFirings(").append(earlyTrigger).append(")");
}
return builder.toString();
}
}
}
|
AfterEndOfWindowNoLate
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/ResourceClosedException.java
|
{
"start": 284,
"end": 567
}
|
class ____ extends HibernateException {
/**
* Constructs a ResourceClosedException using the supplied message.
*
* @param message The message explaining the exception condition
*/
public ResourceClosedException(String message) {
super( message );
}
}
|
ResourceClosedException
|
java
|
assertj__assertj-core
|
assertj-core/src/test/java/org/assertj/core/internal/longs/Longs_assertIsNegative_Test.java
|
{
"start": 1158,
"end": 2492
}
|
class ____ extends LongsBaseTest {
@Test
void should_succeed_since_actual_is_negative() {
longs.assertIsNegative(INFO, -6L);
}
@Test
void should_fail_since_actual_is_not_negative() {
// WHEN
var assertionError = expectAssertionError(() -> longs.assertIsNegative(INFO, 6L));
// THEN
then(assertionError).hasMessage(shouldBeLess(6L, 0L).create());
}
@Test
void should_fail_since_actual_is_zero() {
// WHEN
var assertionError = expectAssertionError(() -> longs.assertIsNegative(INFO, 0L));
// THEN
then(assertionError).hasMessage(shouldBeLess(0L, 0L).create());
}
@Test
void should_fail_since_actual_can_not_be_negative_according_to_custom_comparison_strategy() {
// WHEN
var assertionError = expectAssertionError(() -> longsWithAbsValueComparisonStrategy.assertIsNegative(INFO, 6L));
// THEN
then(assertionError).hasMessage(shouldBeLess(6L, 0L, absValueComparisonStrategy).create());
}
@Test
void should_fail_since_actual_is_not_negative_according_to_custom_comparison_strategy() {
// WHEN
var assertionError = expectAssertionError(() -> longsWithAbsValueComparisonStrategy.assertIsNegative(INFO, -1L));
// THEN
then(assertionError).hasMessage(shouldBeLess(-1L, 0L, absValueComparisonStrategy).create());
}
}
|
Longs_assertIsNegative_Test
|
java
|
apache__camel
|
components/camel-jetty/src/test/java/org/apache/camel/component/jetty/SpringHttpsRouteTest.java
|
{
"start": 2243,
"end": 5313
}
|
class ____ {
private static final String NULL_VALUE_MARKER = CamelTestSupport.class.getCanonicalName();
protected final String expectedBody = "<hello>world!</hello>";
protected String pwd = "changeit";
protected final Properties originalValues = new Properties();
protected final transient Logger log = LoggerFactory.getLogger(SpringHttpsRouteTest.class);
@EndpointInject("mock:a")
MockEndpoint mockEndpoint;
@Produce
private ProducerTemplate template;
private Integer port;
@BeforeEach
public void setUp() {
// ensure jsse clients can validate the self-signed dummy localhost
// cert,
// use the server keystore as the trust store for these tests
URL trustStoreUrl = Thread.currentThread().getContextClassLoader().getResource("jsse/localhost.p12");
setSystemProp("javax.net.ssl.trustStore", trustStoreUrl.getPath());
setSystemProp("javax.net.ssl.trustStorePassword", pwd);
}
@AfterEach
public void tearDown() {
restoreSystemProperties();
}
private void setSystemProp(String key, String value) {
String originalValue = System.setProperty(key, value);
originalValues.put(key, originalValue != null ? originalValue : NULL_VALUE_MARKER);
}
private void restoreSystemProperties() {
for (Map.Entry<Object, Object> entry : originalValues.entrySet()) {
Object key = entry.getKey();
Object value = entry.getValue();
if (NULL_VALUE_MARKER.equals(value)) {
System.clearProperty((String) key);
} else {
System.setProperty((String) key, (String) value);
}
}
}
@Test
public void testEndpoint() throws Exception {
mockEndpoint.reset();
mockEndpoint.expectedBodiesReceived(expectedBody);
template.sendBodyAndHeader("https://localhost:" + port + "/test", expectedBody, "Content-Type", "application/xml");
mockEndpoint.assertIsSatisfied();
List<Exchange> list = mockEndpoint.getReceivedExchanges();
Exchange exchange = list.get(0);
assertNotNull(exchange, "exchange");
Message in = exchange.getIn();
assertNotNull(in, "in");
Map<String, Object> headers = in.getHeaders();
log.info("Headers: {}", headers);
assertFalse(headers.isEmpty(), "Should be more than one header but was: " + headers);
}
@Test
public void testEndpointWithoutHttps() {
mockEndpoint.reset();
try {
template.sendBodyAndHeader("http://localhost:" + port + "/test", expectedBody, "Content-Type", "application/xml");
fail("expect exception on access to https endpoint via http");
} catch (RuntimeCamelException expected) {
}
assertTrue(mockEndpoint.getExchanges().isEmpty(), "mock endpoint was not called");
}
@Resource(name = "dynaPort")
public void setPort(AvailablePortFinder.Port port) {
this.port = port.getPort();
}
}
|
SpringHttpsRouteTest
|
java
|
elastic__elasticsearch
|
server/src/main/java/org/elasticsearch/action/admin/indices/rollover/MinSizeCondition.java
|
{
"start": 1056,
"end": 2513
}
|
class ____ extends Condition<ByteSizeValue> {
public static final String NAME = "min_size";
public MinSizeCondition(ByteSizeValue value) {
super(NAME, Type.MIN);
this.value = value;
}
public MinSizeCondition(StreamInput in) throws IOException {
super(NAME, Type.MIN);
this.value = ByteSizeValue.readFrom(in);
}
@Override
public Result evaluate(Stats stats) {
return new Result(this, stats.indexSize().getBytes() >= value.getBytes());
}
@Override
public String getWriteableName() {
return NAME;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
value.writeTo(out);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
return builder.field(NAME, value.getStringRep());
}
public static MinSizeCondition fromXContent(XContentParser parser) throws IOException {
if (parser.nextToken() == XContentParser.Token.VALUE_STRING) {
return new MinSizeCondition(ByteSizeValue.parseBytesSizeValue(parser.text(), NAME));
} else {
throw new IllegalArgumentException("invalid token when parsing " + NAME + " condition: " + parser.currentToken());
}
}
@Override
boolean includedInVersion(TransportVersion version) {
return version.onOrAfter(TransportVersions.V_8_4_0);
}
}
|
MinSizeCondition
|
java
|
apache__camel
|
components/camel-ai/camel-langchain4j-agent-api/src/main/java/org/apache/camel/component/langchain4j/agent/api/AgentConfiguration.java
|
{
"start": 6150,
"end": 7341
}
|
class ____
* @return this configuration instance for method chaining
* @see #parseGuardrailClasses(String[])
*/
public AgentConfiguration withInputGuardrailClassesArray(String[] inputGuardrailClasses) {
return withInputGuardrailClasses(parseGuardrailClasses(inputGuardrailClasses));
}
/**
* Sets input guardrail classes for security filtering of incoming messages.
*
* @param inputGuardrailClasses list of guardrail classes to apply to user inputs
* @return this configuration instance for method chaining
*/
public AgentConfiguration withInputGuardrailClasses(List<Class<?>> inputGuardrailClasses) {
this.inputGuardrailClasses = inputGuardrailClasses;
return this;
}
/**
* Gets the configured output guardrail classes for security filtering.
*
* @return the list of output guardrail classes, or {@code null} if not configured
*/
public List<Class<?>> getOutputGuardrailClasses() {
return outputGuardrailClasses;
}
/**
* Sets output guardrail classes from a comma-separated string of
|
names
|
java
|
alibaba__fastjson
|
src/test/java/com/alibaba/json/bvt/JSONObjectTest_getBigInteger.java
|
{
"start": 169,
"end": 1066
}
|
class ____ extends TestCase {
public void test_get_float() throws Exception {
JSONObject obj = new JSONObject();
obj.put("value", 123.45F);
Assert.assertTrue(123.45F == ((Float) obj.get("value")).floatValue());
Assert.assertEquals(new BigInteger("123"), obj.getBigInteger("value"));
}
public void test_get_double() throws Exception {
JSONObject obj = new JSONObject();
obj.put("value", 123.45D);
Assert.assertTrue(123.45D == ((Double) obj.get("value")).doubleValue());
Assert.assertEquals(new BigInteger("123"), obj.getBigInteger("value"));
}
public void test_get_empty() throws Exception {
JSONObject obj = new JSONObject();
obj.put("value", "");
Assert.assertEquals("", obj.get("value"));
Assert.assertNull(obj.getBigInteger("value"));
}
}
|
JSONObjectTest_getBigInteger
|
java
|
apache__flink
|
flink-formats/flink-avro/src/test/java/org/apache/flink/formats/avro/utils/AvroKryoSerializerTests.java
|
{
"start": 2155,
"end": 8516
}
|
class ____ {
public static <T> T flinkToBytesAndBack(TypeSerializer<T> serializer, T originalObject)
throws IOException {
// Serialize to byte array
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (DataOutputViewStreamWrapper outView = new DataOutputViewStreamWrapper(out)) {
serializer.serialize(originalObject, outView);
}
try (DataInputViewStreamWrapper inView =
new DataInputViewStreamWrapper(new ByteArrayInputStream(out.toByteArray()))) {
return serializer.deserialize(inView);
}
}
public static Object kryoToBytesAndBack(Kryo kryo, Object originalObject) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (Output output = new Output(byteArrayOutputStream)) {
kryo.writeClassAndObject(output, originalObject);
output.flush();
}
try (Input input =
new Input(new ByteArrayInputStream(byteArrayOutputStream.toByteArray()))) {
return kryo.readClassAndObject(input);
}
}
public <T> void testTypeSerialization(Class<T> javaClass, T originalObject) throws IOException {
ExecutionConfig ec = new ExecutionConfig();
SerializerConfig serializerConfig = ec.getSerializerConfig();
TypeInformation<T> typeInformation = TypeExtractor.createTypeInfo(javaClass);
Serializers.recursivelyRegisterType(
typeInformation.getTypeClass(), serializerConfig, new HashSet<>());
TypeSerializer<T> serializer = typeInformation.createSerializer(serializerConfig);
T deserializedObject = flinkToBytesAndBack(serializer, originalObject);
Assertions.assertEquals(originalObject, deserializedObject);
T copiedObject = serializer.copy(originalObject);
Assertions.assertEquals(originalObject, copiedObject);
if (serializer instanceof KryoSerializer) {
KryoSerializer<T> kryoSerializer = (KryoSerializer<T>) serializer;
T kryoDeserializedObject =
javaClass.cast(kryoToBytesAndBack(kryoSerializer.getKryo(), originalObject));
Assertions.assertEquals(originalObject, kryoDeserializedObject);
}
}
@Test
public void testGenericRecord() throws IOException {
final Schema timestampMilliType =
LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG));
final Schema recordSchema =
SchemaBuilder.record("demoRecord")
.namespace("demo")
.fields()
.name("timestamp")
.type(timestampMilliType)
.noDefault()
.name("arrayOfStrings")
.type()
.array()
.items()
.stringType()
.noDefault()
.endRecord();
final GenericRecord testRecordA =
new GenericRecordBuilder(recordSchema)
.set(
"timestamp",
LocalDateTime.of(2025, 2, 20, 16, 0, 0)
.toInstant(ZoneOffset.UTC)
.toEpochMilli())
.set("arrayOfStrings", Arrays.asList("aaa", "bbb", "ccc"))
.build();
testTypeSerialization(GenericRecord.class, testRecordA);
}
@Test
public void testHomogeneousRecordArray() throws IOException {
final Schema timestampMilliType =
LogicalTypes.timestampMillis().addToSchema(Schema.create(Schema.Type.LONG));
final Schema recordSchema =
SchemaBuilder.record("demoRecord")
.namespace("demo")
.fields()
.name("timestamp")
.type(timestampMilliType)
.noDefault()
.name("arrayOfStrings")
.type()
.array()
.items()
.stringType()
.noDefault()
.endRecord();
final GenericRecord testRecordA =
new GenericRecordBuilder(recordSchema)
.set(
"timestamp",
LocalDateTime.of(2025, 2, 20, 16, 0, 0)
.toInstant(ZoneOffset.UTC)
.toEpochMilli())
.set("arrayOfStrings", Arrays.asList("aaa", "bbb", "ccc"))
.build();
final GenericRecord testRecordB =
new GenericRecordBuilder(recordSchema)
.set(
"timestamp",
LocalDateTime.of(2025, 1, 20, 14, 0, 0)
.toInstant(ZoneOffset.UTC)
.toEpochMilli())
.set("arrayOfStrings", Arrays.asList("zzz", "yyy", "xxx"))
.build();
Schema arraySchema = Schema.createArray(recordSchema);
var genericRecordArray =
new GenericData.Array<>(arraySchema, List.of(testRecordA, testRecordB));
testTypeSerialization(GenericData.Array.class, genericRecordArray);
}
@Test
public void testHeterogeneousArray() throws IOException {
Schema unionSchema = SchemaBuilder.unionOf().intType().and().stringType().endUnion();
Schema arraySchema = Schema.createArray(unionSchema);
var heterogeneousArray =
new GenericData.Array<Object>(
arraySchema, List.of(new Utf8("aaa"), 123, new Utf8("zzz"), 456));
testTypeSerialization(GenericData.Array.class, heterogeneousArray);
}
@Test
public void testNullValues() throws IOException {
testTypeSerialization(Schema.class, null);
testTypeSerialization(GenericRecord.class, null);
testTypeSerialization(GenericData.Array.class, null);
}
}
|
AvroKryoSerializerTests
|
java
|
ReactiveX__RxJava
|
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableSkipLastTest.java
|
{
"start": 1255,
"end": 4482
}
|
class ____ extends RxJavaTest {
@Test
public void skipLastEmpty() {
Flowable<String> flowable = Flowable.<String> empty().skipLast(2);
Subscriber<String> subscriber = TestHelper.mockSubscriber();
flowable.subscribe(subscriber);
verify(subscriber, never()).onNext(any(String.class));
verify(subscriber, never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void skipLast1() {
Flowable<String> flowable = Flowable.fromIterable(Arrays.asList("one", "two", "three")).skipLast(2);
Subscriber<String> subscriber = TestHelper.mockSubscriber();
InOrder inOrder = inOrder(subscriber);
flowable.subscribe(subscriber);
inOrder.verify(subscriber, never()).onNext("two");
inOrder.verify(subscriber, never()).onNext("three");
verify(subscriber, times(1)).onNext("one");
verify(subscriber, never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void skipLast2() {
Flowable<String> flowable = Flowable.fromIterable(Arrays.asList("one", "two")).skipLast(2);
Subscriber<String> subscriber = TestHelper.mockSubscriber();
flowable.subscribe(subscriber);
verify(subscriber, never()).onNext(any(String.class));
verify(subscriber, never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void skipLastWithZeroCount() {
Flowable<String> w = Flowable.just("one", "two");
Flowable<String> flowable = w.skipLast(0);
Subscriber<String> subscriber = TestHelper.mockSubscriber();
flowable.subscribe(subscriber);
verify(subscriber, times(1)).onNext("one");
verify(subscriber, times(1)).onNext("two");
verify(subscriber, never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void skipLastWithBackpressure() {
Flowable<Integer> f = Flowable.range(0, Flowable.bufferSize() * 2).skipLast(Flowable.bufferSize() + 10);
TestSubscriber<Integer> ts = new TestSubscriber<>();
f.observeOn(Schedulers.computation()).subscribe(ts);
ts.awaitDone(5, TimeUnit.SECONDS);
ts.assertNoErrors();
assertEquals((Flowable.bufferSize()) - 10, ts.values().size());
}
@Test(expected = IllegalArgumentException.class)
public void skipLastWithNegativeCount() {
Flowable.just("one").skipLast(-1);
}
@Test
public void dispose() {
TestHelper.checkDisposed(Flowable.just(1).skipLast(1));
}
@Test
public void error() {
Flowable.error(new TestException())
.skipLast(1)
.test()
.assertFailure(TestException.class);
}
@Test
public void doubleOnSubscribe() {
TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Flowable<Object>>() {
@Override
public Flowable<Object> apply(Flowable<Object> f)
throws Exception {
return f.skipLast(1);
}
});
}
}
|
FlowableSkipLastTest
|
java
|
quarkusio__quarkus
|
independent-projects/bootstrap/app-model/src/main/java/io/quarkus/bootstrap/resolver/AppModelResolver.java
|
{
"start": 564,
"end": 6009
}
|
interface ____ {
/**
* (Re-)links an artifact to a path.
*
* @param artifact an artifact to (re-)link to the path
* @param localPath local path to the artifact
* @throws AppModelResolverException in case of a failure
*/
void relink(ArtifactCoords artifact, Path localPath) throws AppModelResolverException;
/**
* Resolves an artifact.
*
* @param artifact artifact to resolve
* @return resolved artifact
* @throws AppModelResolverException in case of a failure
*/
ResolvedDependency resolve(ArtifactCoords artifact) throws AppModelResolverException;
/**
* Resolve application direct and transitive dependencies configured by the user.
*
* Note that deployment dependencies are not included in the result.
*
* @param artifact application artifact
* @return the list of dependencies configured by the user
* @throws AppModelResolverException in case of a failure
*/
default Collection<ResolvedDependency> resolveUserDependencies(ArtifactCoords artifact) throws AppModelResolverException {
return resolveUserDependencies(artifact, Collections.emptyList());
}
/**
* Resolve application direct and transitive dependencies configured by the user,
* given the specific versions of the direct dependencies.
*
* Note that deployment dependencies are not included in the result.
*
* @param artifact application artifact
* @param deps some or all of the direct dependencies that should be used in place of the original ones
* @return the list of dependencies configured by the user
* @throws AppModelResolverException in case of a failure
*/
Collection<ResolvedDependency> resolveUserDependencies(ArtifactCoords artifact, Collection<Dependency> deps)
throws AppModelResolverException;
/**
* Resolve dependencies that are required at runtime, excluding test and optional dependencies.
*
* @param artifact
* @return
* @throws AppModelResolverException
*/
ApplicationModel resolveModel(ArtifactCoords artifact) throws AppModelResolverException;
/**
* Resolve artifact dependencies given the specific versions of the direct dependencies
*
* @param root root artifact
* @param deps some or all of the direct dependencies that should be used in place of the original ones
* @return collected dependencies
* @throws AppModelResolverException in case of a failure
*/
ApplicationModel resolveModel(ArtifactCoords root, Collection<Dependency> deps) throws AppModelResolverException;
ApplicationModel resolveManagedModel(ArtifactCoords appArtifact, Collection<Dependency> directDeps,
ArtifactCoords managingProject,
Set<ArtifactKey> localProjects)
throws AppModelResolverException;
/**
* Lists versions released later than the version of the artifact up to the version
* specified or all the later versions in case the up-to-version is not provided.
*
* @param artifact artifact to list the versions for
* @return the list of versions released later than the version of the artifact
* @throws AppModelResolverException in case of a failure
*/
List<String> listLaterVersions(ArtifactCoords artifact, String upToVersion, boolean inclusive)
throws AppModelResolverException;
/**
* Returns the next version of the artifact from the specified range.
* In case the next version is not available, the method returns null.
*
* @param artifact artifact
* @param fromVersion the lowest version of the range
* @param fromVersionIncluded whether the specified lowest version should be included in the range
* @param upToVersion the highest version of the range
* @param upToVersionIncluded whether the specified highest version should be included in the range
* @return the next version from the specified range or null if the next version is not available
* @throws AppModelResolverException in case of a failure
*/
String getNextVersion(ArtifactCoords artifact, String fromVersion, boolean fromVersionIncluded, String upToVersion,
boolean upToVersionIncluded) throws AppModelResolverException;
/**
* Returns the latest version for the artifact up to the version specified.
* In case there is no later version available, the artifact's version is returned.
*
* @param artifact artifact
* @param upToVersion max version boundary
* @param inclusive whether the upToVersion should be included in the range or not
* @return the latest version up to specified boundary
* @throws AppModelResolverException in case of a failure
*/
String getLatestVersion(ArtifactCoords artifact, String upToVersion, boolean inclusive) throws AppModelResolverException;
/**
* Resolves the latest version from the specified range. The version of the artifact is ignored.
*
* @param appArtifact the artifact
* @param range the version range
* @return the latest version of the artifact from the range or null, if no version was found for the specified range
* @throws AppModelResolverException in case of a failure
*/
String getLatestVersionFromRange(ArtifactCoords appArtifact, String range) throws AppModelResolverException;
}
|
AppModelResolver
|
java
|
elastic__elasticsearch
|
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/function/scalar/string/BinaryStringFunction.java
|
{
"start": 1080,
"end": 1256
}
|
class ____ binary functions that have the first parameter a string, the second parameter a number
* or a string and the result can be a string or a number.
*/
public abstract
|
for
|
java
|
hibernate__hibernate-orm
|
tooling/metamodel-generator/src/jakartaData/java/org/hibernate/processor/test/data/basic/Concrete.java
|
{
"start": 207,
"end": 258
}
|
interface ____ extends IdOperations<Thing> {
}
|
Concrete
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/readonly/Student.java
|
{
"start": 221,
"end": 936
}
|
class ____ {
private long studentNumber;
private String name;
private Course preferredCourse;
private Set enrolments = new HashSet();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(long studentNumber) {
this.studentNumber = studentNumber;
}
public Course getPreferredCourse() {
return preferredCourse;
}
public void setPreferredCourse(Course preferredCourse) {
this.preferredCourse = preferredCourse;
}
public Set getEnrolments() {
return enrolments;
}
public void setEnrolments(Set employments) {
this.enrolments = employments;
}
}
|
Student
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/transformer/InstanceTransformerTest.java
|
{
"start": 2430,
"end": 2871
}
|
class ____ {
private final String id;
public MyService() {
this("default");
}
public MyService(String id) {
this.id = id;
}
public String hello(int param1, List<String> param2) {
return id + "foobar" + param1 + param2;
}
public Set<String> doSomething(String param) {
return Set.of("quux", param, id);
}
}
}
|
MyService
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/filecontroller/LogAggregationFileControllerFactory.java
|
{
"start": 8344,
"end": 9063
}
|
class ____ {
private String value;
private boolean usingDefault = false;
private final String configKey;
DeterminedLogAggregationSuffix(Configuration conf,
String fileController) {
configKey = String.format(
YarnConfiguration.LOG_AGGREGATION_REMOTE_APP_LOG_DIR_SUFFIX_FMT,
fileController);
String suffix = conf.get(configKey);
if (suffix == null || suffix.isEmpty()) {
this.value = conf.get(YarnConfiguration.NM_REMOTE_APP_LOG_DIR_SUFFIX,
YarnConfiguration.DEFAULT_NM_REMOTE_APP_LOG_DIR_SUFFIX);
this.usingDefault = true;
} else {
this.value = suffix;
}
}
}
private static
|
DeterminedLogAggregationSuffix
|
java
|
alibaba__nacos
|
common/src/main/java/com/alibaba/nacos/common/packagescan/resource/PathMatchingResourcePatternResolver.java
|
{
"start": 38082,
"end": 40336
}
|
class ____ implements InvocationHandler {
private final String subPattern;
private final PathMatcher pathMatcher;
private final String rootPath;
private final Set<Resource> resources = new LinkedHashSet<>();
public PatternVirtualFileVisitor(String rootPath, String subPattern, PathMatcher pathMatcher) {
this.subPattern = subPattern;
this.pathMatcher = pathMatcher;
this.rootPath = (rootPath.isEmpty() || rootPath.endsWith("/") ? rootPath : rootPath + "/");
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
String methodName = method.getName();
if (Object.class == method.getDeclaringClass()) {
if ("equals".equals(methodName)) {
// Only consider equal when proxies are identical.
return (proxy == args[0]);
} else if ("hashCode".equals(methodName)) {
return System.identityHashCode(proxy);
}
} else if ("getAttributes".equals(methodName)) {
return getAttributes();
} else if ("visit".equals(methodName)) {
visit(args[0]);
return null;
} else if ("toString".equals(methodName)) {
return toString();
}
throw new IllegalStateException("Unexpected method invocation: " + method);
}
public void visit(Object vfsResource) {
if (this.pathMatcher.match(this.subPattern,
VfsPatternUtils.getPath(vfsResource).substring(this.rootPath.length()))) {
this.resources.add(new VfsResource(vfsResource));
}
}
public Object getAttributes() {
return VfsPatternUtils.getVisitorAttributes();
}
public Set<Resource> getResources() {
return this.resources;
}
public int size() {
return this.resources.size();
}
@Override
public String toString() {
return "sub-pattern: " + this.subPattern + ", resources: " + this.resources;
}
}
}
|
PatternVirtualFileVisitor
|
java
|
spring-projects__spring-framework
|
spring-websocket/src/main/java/org/springframework/web/socket/config/annotation/EnableWebSocketMessageBroker.java
|
{
"start": 1197,
"end": 1458
}
|
class ____ {
*
* }
* </pre>
*
* <p>Customize the imported configuration by implementing the
* {@link WebSocketMessageBrokerConfigurer} interface:
*
* <pre class="code">
* @Configuration
* @EnableWebSocketMessageBroker
* public
|
MyWebSocketConfig
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/test/java/org/hibernate/orm/test/schemaupdate/ColumnNamesTest.java
|
{
"start": 3566,
"end": 3794
}
|
class ____ {
@Id
private long id;
@Column(name = "`Age`")
public String age;
@Column(name = "Name")
private String name;
private String match;
private String birthday;
private String homeAddress;
}
}
|
Employee
|
java
|
spring-projects__spring-framework
|
spring-test/src/test/java/org/springframework/test/context/junit4/FailingBeforeAndAfterMethodsSpringRunnerTests.java
|
{
"start": 4921,
"end": 5153
}
|
class ____ implements TestExecutionListener {
@Override
public void afterTestMethod(TestContext testContext) {
fail("always failing afterTestMethod()");
}
}
protected static
|
AlwaysFailingAfterTestMethodTestExecutionListener
|
java
|
alibaba__fastjson
|
src/test/java/com/derbysoft/spitfire/fastjson/dto/ProviderChainDTO.java
|
{
"start": 77,
"end": 348
}
|
class ____ extends AbstractDTO{
private List<UniqueIDDTO> providers;
public List<UniqueIDDTO> getProviders() {
return providers;
}
public void setProviders(List<UniqueIDDTO> providers) {
this.providers = providers;
}
}
|
ProviderChainDTO
|
java
|
micronaut-projects__micronaut-core
|
inject-java/src/test/groovy/io/micronaut/aop/named/Config.java
|
{
"start": 742,
"end": 855
}
|
class ____ {
public Config(Inner inner) {
}
@ConfigurationProperties("inner")
public static
|
Config
|
java
|
google__auto
|
common/src/test/java/com/google/auto/common/OverridesTest.java
|
{
"start": 13153,
"end": 13231
}
|
class ____ extends XAbstractList<String> {}
private abstract static
|
XStringList
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/main/java/org/springframework/boot/logging/log4j2/SpringBootPropertySource.java
|
{
"start": 1107,
"end": 1972
}
|
class ____ implements PropertySource {
private static final String PREFIX = "log4j.";
private final Map<String, String> properties = Collections
.singletonMap(ShutdownCallbackRegistry.SHUTDOWN_HOOK_ENABLED, "false");
@Override
public void forEach(BiConsumer<String, String> action) {
this.properties.forEach(action::accept);
}
@Override
public CharSequence getNormalForm(Iterable<? extends CharSequence> tokens) {
return PREFIX + Util.joinAsCamelCase(tokens);
}
@Override
public int getPriority() {
return -200;
}
@Override
public @Nullable String getProperty(String key) {
return this.properties.get(key);
}
@Override
public boolean containsProperty(String key) {
return this.properties.containsKey(key);
}
@Override
public Collection<String> getPropertyNames() {
return this.properties.keySet();
}
}
|
SpringBootPropertySource
|
java
|
lettuce-io__lettuce-core
|
src/test/java/io/lettuce/core/cluster/PipelinedRedisFutureUnitTests.java
|
{
"start": 319,
"end": 1066
}
|
class ____ {
private PipelinedRedisFuture<String> sut;
@Test
void testComplete() {
String other = "other";
sut = new PipelinedRedisFuture<>(new HashMap<>(), o -> other);
sut.complete("");
assertThat(TestFutures.getOrTimeout(sut.toCompletableFuture())).isEqualTo(other);
assertThat(sut.getError()).isNull();
}
@Test
void testCompleteExceptionally() {
String other = "other";
sut = new PipelinedRedisFuture<>(new HashMap<>(), o -> other);
sut.completeExceptionally(new Exception());
assertThat(TestFutures.getOrTimeout(sut.toCompletableFuture())).isEqualTo(other);
assertThat(sut.getError()).isNull();
}
}
|
PipelinedRedisFutureUnitTests
|
java
|
spring-projects__spring-boot
|
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/filter/annotation/FilterAnnotationsTests.java
|
{
"start": 4294,
"end": 4348
}
|
interface ____ {
Filter[] value();
}
static
|
Filters
|
java
|
apache__hadoop
|
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-tests/src/test/java/org/apache/hadoop/yarn/server/NMTokenIdentifierNewForTest.java
|
{
"start": 1601,
"end": 4293
}
|
class ____ extends NMTokenIdentifier {
private static Logger LOG = LoggerFactory.getLogger(NMTokenIdentifierNewForTest.class);
public static final Text KIND = new Text("NMToken");
private NMTokenIdentifierNewProto proto;
private NMTokenIdentifierNewProto.Builder builder;
public NMTokenIdentifierNewForTest(){
builder = NMTokenIdentifierNewProto.newBuilder();
}
public NMTokenIdentifierNewForTest(NMTokenIdentifierNewProto proto) {
this.proto = proto;
}
public NMTokenIdentifierNewForTest(NMTokenIdentifier tokenIdentifier,
String message) {
builder = NMTokenIdentifierNewProto.newBuilder();
builder.setAppAttemptId(tokenIdentifier.getProto().getAppAttemptId());
builder.setNodeId(tokenIdentifier.getProto().getNodeId());
builder.setAppSubmitter(tokenIdentifier.getApplicationSubmitter());
builder.setKeyId(tokenIdentifier.getKeyId());
builder.setMessage(message);
proto = builder.build();
builder = null;
}
@Override
public void write(DataOutput out) throws IOException {
LOG.debug("Writing NMTokenIdentifierNewForTest to RPC layer: {}", this);
out.write(proto.toByteArray());
}
@Override
public void readFields(DataInput in) throws IOException {
DataInputStream dis = (DataInputStream)in;
byte[] buffer = IOUtils.toByteArray(dis);
proto = NMTokenIdentifierNewProto.parseFrom(buffer);
}
@Override
public Text getKind() {
return KIND;
}
@Override
public UserGroupInformation getUser() {
return null;
}
public String getMessage() {
return proto.getMessage();
}
public void setMessage(String message) {
builder.setMessage(message);
}
public NMTokenIdentifierNewProto getNewProto() {
return proto;
}
public void build() {
proto = builder.build();
builder = null;
}
public ApplicationAttemptId getApplicationAttemptId() {
return new ApplicationAttemptIdPBImpl(proto.getAppAttemptId());
}
public NodeId getNodeId() {
return new NodeIdPBImpl(proto.getNodeId());
}
public String getApplicationSubmitter() {
return proto.getAppSubmitter();
}
public int getKeyId() {
return proto.getKeyId();
}
@Override
public int hashCode() {
return this.proto.hashCode();
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other.getClass().isAssignableFrom(this.getClass())) {
return this.getNewProto().equals(this.getClass().cast(other).getNewProto());
}
return false;
}
@Override
public String toString() {
return TextFormat.shortDebugString(this.proto);
}
}
|
NMTokenIdentifierNewForTest
|
java
|
apache__hadoop
|
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/Credentials.java
|
{
"start": 2307,
"end": 2357
}
|
class ____ implements Writable {
public
|
Credentials
|
java
|
micronaut-projects__micronaut-core
|
inject-java/src/test/groovy/io/micronaut/aop/introduction/DeleteByIdCrudRepo.java
|
{
"start": 739,
"end": 824
}
|
interface ____<ID> {
void deleteById(@NonNull @NotNull ID id);
}
|
DeleteByIdCrudRepo
|
java
|
apache__maven
|
impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultModelUrlNormalizer.java
|
{
"start": 1492,
"end": 2771
}
|
class ____ implements ModelUrlNormalizer {
private final UrlNormalizer urlNormalizer;
@Inject
public DefaultModelUrlNormalizer(UrlNormalizer urlNormalizer) {
this.urlNormalizer = urlNormalizer;
}
@Override
public Model normalize(Model model, ModelBuilderRequest request) {
if (model == null) {
return null;
}
Model.Builder builder = Model.newBuilder(model);
builder.url(normalize(model.getUrl()));
Scm scm = model.getScm();
if (scm != null) {
builder.scm(Scm.newBuilder(scm)
.url(normalize(scm.getUrl()))
.connection(normalize(scm.getConnection()))
.developerConnection(normalize(scm.getDeveloperConnection()))
.build());
}
DistributionManagement dist = model.getDistributionManagement();
if (dist != null) {
Site site = dist.getSite();
if (site != null) {
builder.distributionManagement(dist.withSite(site.withUrl(normalize(site.getUrl()))));
}
}
return builder.build();
}
private String normalize(String url) {
return urlNormalizer.normalize(url);
}
}
|
DefaultModelUrlNormalizer
|
java
|
spring-projects__spring-boot
|
core/spring-boot/src/main/java/org/springframework/boot/logging/logback/GraylogExtendedLogFormatStructuredLogFormatter.java
|
{
"start": 2390,
"end": 6850
}
|
class ____ extends JsonWriterStructuredLogFormatter<ILoggingEvent> {
private static final PairExtractor<KeyValuePair> keyValuePairExtractor = PairExtractor.of((pair) -> pair.key,
(pair) -> pair.value);
private static final Log logger = LogFactory.getLog(GraylogExtendedLogFormatStructuredLogFormatter.class);
/**
* Allowed characters in field names are any word character (letter, number,
* underscore), dashes and dots.
*/
private static final Pattern FIELD_NAME_VALID_PATTERN = Pattern.compile("^[\\w.\\-]*$");
/**
* Libraries SHOULD not allow to send id as additional field ("_id"). Graylog server
* nodes omit this field automatically.
*/
private static final Set<String> ADDITIONAL_FIELD_ILLEGAL_KEYS = Set.of("id", "_id");
GraylogExtendedLogFormatStructuredLogFormatter(Environment environment,
@Nullable StackTracePrinter stackTracePrinter, ContextPairs contextPairs,
ThrowableProxyConverter throwableProxyConverter,
@Nullable StructuredLoggingJsonMembersCustomizer<?> customizer) {
super((members) -> jsonMembers(environment, stackTracePrinter, contextPairs, throwableProxyConverter, members),
customizer);
}
private static void jsonMembers(Environment environment, @Nullable StackTracePrinter stackTracePrinter,
ContextPairs contextPairs, ThrowableProxyConverter throwableProxyConverter,
JsonWriter.Members<ILoggingEvent> members) {
Extractor extractor = new Extractor(stackTracePrinter, throwableProxyConverter);
members.add("version", "1.1");
members.add("short_message", ILoggingEvent::getFormattedMessage)
.as(GraylogExtendedLogFormatStructuredLogFormatter::getMessageText);
members.add("timestamp", ILoggingEvent::getTimeStamp)
.as(GraylogExtendedLogFormatStructuredLogFormatter::formatTimeStamp);
members.add("level", LevelToSyslogSeverity::convert);
members.add("_level_name", ILoggingEvent::getLevel);
members.add("_process_pid", environment.getProperty("spring.application.pid", Long.class)).whenNotNull();
members.add("_process_thread_name", ILoggingEvent::getThreadName);
GraylogExtendedLogFormatProperties.get(environment).jsonMembers(members);
members.add("_log_logger", ILoggingEvent::getLoggerName);
members.add().usingPairs(contextPairs.flat(additionalFieldJoiner(), (pairs) -> {
pairs.addMapEntries(ILoggingEvent::getMDCPropertyMap);
pairs.add(ILoggingEvent::getKeyValuePairs, keyValuePairExtractor);
}));
Function<@Nullable ILoggingEvent, @Nullable Object> getThrowableProxy = (event) -> (event != null)
? event.getThrowableProxy() : null;
members.add()
.whenNotNull(getThrowableProxy)
.usingMembers((throwableMembers) -> throwableMembers(throwableMembers, extractor));
}
private static String getMessageText(String formattedMessage) {
// Always return text as a blank message will lead to a error as of Graylog v6
return (!StringUtils.hasText(formattedMessage)) ? "(blank)" : formattedMessage;
}
/**
* GELF requires "seconds since UNIX epoch with optional <b>decimal places for
* milliseconds</b>". To comply with this requirement, we format a POSIX timestamp
* with millisecond precision as e.g. "1725459730385" -> "1725459730.385"
* @param timeStamp the timestamp of the log message
* @return the timestamp formatted as string with millisecond precision
*/
private static WritableJson formatTimeStamp(long timeStamp) {
return (out) -> out.append(new BigDecimal(timeStamp).movePointLeft(3).toPlainString());
}
private static void throwableMembers(Members<ILoggingEvent> members, Extractor extractor) {
members.add("full_message", extractor::messageAndStackTrace);
members.add("_error_type", ILoggingEvent::getThrowableProxy).as(IThrowableProxy::getClassName);
members.add("_error_stack_trace", extractor::stackTrace);
members.add("_error_message", ILoggingEvent::getThrowableProxy).as(IThrowableProxy::getMessage);
}
private static Joiner additionalFieldJoiner() {
return (prefix, name) -> {
name = prefix + name;
if (!FIELD_NAME_VALID_PATTERN.matcher(name).matches()) {
logger.warn(LogMessage.format("'%s' is not a valid field name according to GELF standard", name));
return null;
}
if (ADDITIONAL_FIELD_ILLEGAL_KEYS.contains(name)) {
logger.warn(LogMessage.format("'%s' is an illegal field name according to GELF standard", name));
return null;
}
return (!name.startsWith("_")) ? "_" + name : name;
};
}
}
|
GraylogExtendedLogFormatStructuredLogFormatter
|
java
|
quarkusio__quarkus
|
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/validation/QualifierWithBindingAnnotationTest.java
|
{
"start": 1035,
"end": 1117
}
|
class ____ {
}
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@
|
Alpha
|
java
|
apache__camel
|
components/camel-undertow/src/main/java/org/apache/camel/component/undertow/UndertowComponent.java
|
{
"start": 2665,
"end": 19792
}
|
class ____ extends DefaultComponent
implements RestConsumerFactory, RestApiConsumerFactory, RestProducerFactory, SSLContextParametersAware {
private static final Logger LOG = LoggerFactory.getLogger(UndertowComponent.class);
private final Map<UndertowHostKey, UndertowHost> undertowRegistry = new ConcurrentHashMap<>();
private final Set<HttpHandlerRegistrationInfo> handlers = new LinkedHashSet<>();
@Metadata(label = "advanced")
private UndertowHttpBinding undertowHttpBinding;
@Metadata(label = "security")
private SSLContextParameters sslContextParameters;
@Metadata(label = "security")
private boolean useGlobalSslContextParameters;
@Metadata(label = "advanced")
private UndertowHostOptions hostOptions;
@Metadata(label = "consumer")
private boolean muteException;
@Metadata(label = "security")
private Object securityConfiguration;
@Metadata(label = "security")
private String allowedRoles;
@Metadata(label = "security")
private UndertowSecurityProvider securityProvider;
public UndertowComponent() {
this(null);
}
public UndertowComponent(CamelContext context) {
super(context);
}
@Override
protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
URI uriHttpUriAddress = new URI(UnsafeUriCharactersEncoder.encodeHttpURI(remaining));
URI endpointUri = URISupport.createRemainingURI(uriHttpUriAddress, parameters);
// any additional channel options
Map<String, Object> options = PropertiesHelper.extractProperties(parameters, "option.");
// determine sslContextParameters
SSLContextParameters sslParams = this.sslContextParameters;
if (sslParams == null) {
sslParams = retrieveGlobalSslContextParameters();
}
// create the endpoint first
UndertowEndpoint endpoint = createEndpointInstance(endpointUri, this);
// set options from component
endpoint.setSslContextParameters(sslParams);
endpoint.setMuteException(muteException);
// Prefer endpoint configured over component configured
if (undertowHttpBinding == null) {
// fallback to component configured
undertowHttpBinding = getUndertowHttpBinding();
}
if (undertowHttpBinding != null) {
endpoint.setUndertowHttpBinding(undertowHttpBinding);
}
// set options from parameters
setProperties(endpoint, parameters);
if (options != null) {
endpoint.setOptions(options);
}
// then re-create the http uri with the remaining parameters which the endpoint did not use
URI httpUri = URISupport.createRemainingURI(
new URI(
uriHttpUriAddress.getScheme(),
uriHttpUriAddress.getUserInfo(),
uriHttpUriAddress.getHost(),
uriHttpUriAddress.getPort(),
uriHttpUriAddress.getPath(),
uriHttpUriAddress.getQuery(),
uriHttpUriAddress.getFragment()),
parameters);
endpoint.setHttpURI(httpUri);
return endpoint;
}
protected UndertowEndpoint createEndpointInstance(URI endpointUri, UndertowComponent component) {
return new UndertowEndpoint(endpointUri.toString(), component);
}
@Override
public Consumer createConsumer(
CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters)
throws Exception {
return doCreateConsumer(camelContext, processor, verb, basePath, uriTemplate, consumes, produces, configuration,
parameters, false);
}
@Override
public Consumer createApiConsumer(
CamelContext camelContext, Processor processor, String contextPath,
RestConfiguration configuration, Map<String, Object> parameters)
throws Exception {
// reuse the createConsumer method we already have. The api need to use GET and match on uri prefix
return doCreateConsumer(camelContext, processor, "GET", contextPath, null, null, null, configuration, parameters, true);
}
private void initSecurityProvider() throws Exception {
Object securityConfiguration = getSecurityConfiguration();
if (securityConfiguration != null) {
ServiceLoader<UndertowSecurityProvider> securityProvider = ServiceLoader.load(UndertowSecurityProvider.class);
Iterator<UndertowSecurityProvider> iter = securityProvider.iterator();
List<String> providers = new LinkedList();
while (iter.hasNext()) {
UndertowSecurityProvider security = iter.next();
//only securityProvider, who accepts security configuration, could be used
if (security.acceptConfiguration(securityConfiguration, null)) {
this.securityProvider = security;
LOG.info("Security provider found {}", securityProvider.getClass().getName());
break;
}
providers.add(security.getClass().getName());
}
if (this.securityProvider == null) {
LOG.info("Security provider for configuration {} not found {}", securityConfiguration, providers);
}
}
}
Consumer doCreateConsumer(
CamelContext camelContext, Processor processor, String verb, String basePath, String uriTemplate,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters, boolean api)
throws Exception {
String path = basePath;
if (uriTemplate != null) {
// make sure to avoid double slashes
if (uriTemplate.startsWith("/")) {
path = path + uriTemplate;
} else {
path = path + "/" + uriTemplate;
}
}
path = FileUtil.stripLeadingSeparator(path);
String scheme = "http";
String host = "";
int port = 0;
RestConfiguration config = configuration;
if (config == null) {
config = CamelContextHelper.getRestConfiguration(camelContext, getComponentName());
}
if (config.getScheme() != null) {
scheme = config.getScheme();
}
if (config.getHost() != null) {
host = config.getHost();
}
int num = config.getPort();
if (num > 0) {
port = num;
}
// prefix path with context-path if configured in rest-dsl configuration
String contextPath = config.getContextPath();
if (ObjectHelper.isNotEmpty(contextPath)) {
contextPath = FileUtil.stripTrailingSeparator(contextPath);
contextPath = FileUtil.stripLeadingSeparator(contextPath);
if (ObjectHelper.isNotEmpty(contextPath)) {
path = contextPath + "/" + path;
}
}
// if no explicit hostname set then resolve the hostname
if (ObjectHelper.isEmpty(host)) {
host = RestComponentHelper.resolveRestHostName(host, config);
}
Map<String, Object> map = RestComponentHelper.initRestEndpointProperties(getComponentName(), config);
// build query string, and append any endpoint configuration properties
// must use upper case for restrict
String restrict = verb.toUpperCase(Locale.US);
boolean explicitOptions = restrict.contains("OPTIONS");
boolean cors = config.isEnableCORS();
if (cors) {
// allow HTTP Options as we want to handle CORS in rest-dsl
map.put("optionsEnabled", "true");
} else if (explicitOptions) {
// the rest-dsl is using OPTIONS
map.put("optionsEnabled", "true");
}
if (api) {
map.put("matchOnUriPrefix", "true");
}
RestComponentHelper.addHttpRestrictParam(map, verb, !explicitOptions);
String url = RestComponentHelper.createRestConsumerUrl(getComponentName(), scheme, host, port, path, map);
UndertowEndpoint endpoint = (UndertowEndpoint) camelContext.getEndpoint(url, parameters);
if (!map.containsKey("undertowHttpBinding")) {
// use the rest binding, if not using a custom http binding
endpoint.setUndertowHttpBinding(new RestUndertowHttpBinding(endpoint.isUseStreaming()));
}
// configure consumer properties
Consumer consumer = endpoint.createConsumer(processor);
if (config.getConsumerProperties() != null && !config.getConsumerProperties().isEmpty()) {
setProperties(camelContext, consumer, config.getConsumerProperties());
}
if (consumer instanceof UndertowConsumer) {
// mark the consumer as a rest consumer
((UndertowConsumer) consumer).setRest(true);
}
return consumer;
}
@Override
public Producer createProducer(
CamelContext camelContext, String host,
String verb, String basePath, String uriTemplate, String queryParameters,
String consumes, String produces, RestConfiguration configuration, Map<String, Object> parameters)
throws Exception {
// avoid leading slash
basePath = FileUtil.stripLeadingSeparator(basePath);
uriTemplate = FileUtil.stripLeadingSeparator(uriTemplate);
// get the endpoint
String url = getComponentName() + ":" + host;
if (!ObjectHelper.isEmpty(basePath)) {
url += "/" + basePath;
}
if (!ObjectHelper.isEmpty(uriTemplate)) {
url += "/" + uriTemplate;
}
RestConfiguration config = CamelContextHelper.getRestConfiguration(camelContext, null, getComponentName());
Map<String, Object> map = new HashMap<>();
// build query string, and append any endpoint configuration properties
if (config.getProducerComponent() == null || config.getProducerComponent().equals(getComponentName())) {
// setup endpoint options
if (config.getEndpointProperties() != null && !config.getEndpointProperties().isEmpty()) {
map.putAll(config.getEndpointProperties());
}
}
url = recreateUrl(map, url);
parameters = parameters != null ? new HashMap<>(parameters) : new HashMap<>();
// there are cases where we might end up here without component being created beforehand
// we need to abide by the component properties specified in the parameters when creating
// the component
RestProducerFactoryHelper.setupComponentFor(url, camelContext, (Map<String, Object>) parameters.remove("component"));
UndertowEndpoint endpoint = (UndertowEndpoint) camelContext.getEndpoint(url, parameters);
String path = uriTemplate != null ? uriTemplate : basePath;
endpoint.setHeaderFilterStrategy(new UndertowRestHeaderFilterStrategy(path, queryParameters));
// the endpoint must be started before creating the producer
ServiceHelper.startService(endpoint);
return endpoint.createProducer();
}
@Override
protected void doInit() throws Exception {
super.doInit();
if (this.securityProvider == null) {
initSecurityProvider();
}
try {
RestConfiguration config = CamelContextHelper.getRestConfiguration(getCamelContext(), getComponentName());
// configure additional options on undertow configuration
if (config.getComponentProperties() != null && !config.getComponentProperties().isEmpty()) {
setProperties(this, config.getComponentProperties());
}
} catch (IllegalArgumentException e) {
// if there's a mismatch between the component and the rest-configuration,
// then getRestConfiguration throws IllegalArgumentException which can be
// safely ignored as it means there's no special conf for this component.
}
}
public HttpHandler registerEndpoint(
UndertowConsumer consumer, HttpHandlerRegistrationInfo registrationInfo, SSLContext sslContext, HttpHandler handler)
throws Exception {
final URI uri = registrationInfo.getUri();
final UndertowHostKey key = new UndertowHostKey(uri.getHost(), uri.getPort(), sslContext);
final UndertowHost host = undertowRegistry.computeIfAbsent(key, this::createUndertowHost);
host.validateEndpointURI(uri);
handlers.add(registrationInfo);
HttpHandler handlerWrapped = handler;
if (this.securityProvider != null) {
handlerWrapped = this.securityProvider.wrapHttpHandler(handler);
}
return host.registerHandler(consumer, registrationInfo, handlerWrapped);
}
public void unregisterEndpoint(
UndertowConsumer consumer, HttpHandlerRegistrationInfo registrationInfo, SSLContext sslContext) {
final URI uri = registrationInfo.getUri();
final UndertowHostKey key = new UndertowHostKey(uri.getHost(), uri.getPort(), sslContext);
final UndertowHost host = undertowRegistry.get(key);
handlers.remove(registrationInfo);
// if the route is not automatically started, then the undertow registry
// may not have any instance of UndertowHost associated to the given
// registrationInfo
if (host != null) {
host.unregisterHandler(consumer, registrationInfo);
}
}
protected UndertowHost createUndertowHost(UndertowHostKey key) {
return new DefaultUndertowHost(key, hostOptions);
}
public UndertowHttpBinding getUndertowHttpBinding() {
return undertowHttpBinding;
}
/**
* To use a custom HttpBinding to control the mapping between Camel message and HttpClient.
*/
public void setUndertowHttpBinding(UndertowHttpBinding undertowHttpBinding) {
this.undertowHttpBinding = undertowHttpBinding;
}
public SSLContextParameters getSslContextParameters() {
return sslContextParameters;
}
/**
* To configure security using SSLContextParameters
*/
public void setSslContextParameters(SSLContextParameters sslContextParameters) {
this.sslContextParameters = sslContextParameters;
}
@Override
public boolean isUseGlobalSslContextParameters() {
return this.useGlobalSslContextParameters;
}
/**
* Enable usage of global SSL context parameters.
*/
@Override
public void setUseGlobalSslContextParameters(boolean useGlobalSslContextParameters) {
this.useGlobalSslContextParameters = useGlobalSslContextParameters;
}
public UndertowHostOptions getHostOptions() {
return hostOptions;
}
/**
* To configure common options, such as thread pools
*/
public void setHostOptions(UndertowHostOptions hostOptions) {
this.hostOptions = hostOptions;
}
public boolean isMuteException() {
return muteException;
}
/**
* If enabled and an Exchange failed processing on the consumer side the response's body won't contain the
* exception's stack trace.
*/
public void setMuteException(boolean muteException) {
this.muteException = muteException;
}
protected String getComponentName() {
return "undertow";
}
public Set<HttpHandlerRegistrationInfo> getHandlers() {
return handlers;
}
public Object getSecurityConfiguration() {
return securityConfiguration;
}
/**
* Configuration used by UndertowSecurityProvider. Security configuration object for use from
* UndertowSecurityProvider. Configuration is UndertowSecurityProvider specific. Each provider decides, whether it
* accepts configuration.
*/
public void setSecurityConfiguration(Object securityConfiguration) {
this.securityConfiguration = securityConfiguration;
}
public String getAllowedRoles() {
return allowedRoles;
}
/**
* Configuration used by UndertowSecurityProvider. Comma separated list of allowed roles.
*/
public void setAllowedRoles(String allowedRoles) {
this.allowedRoles = allowedRoles;
}
/**
* Security provider allows plug in the provider, which will be used to secure requests. SPI approach could be used
* too (component then finds security provider using SPI).
*/
public void setSecurityProvider(UndertowSecurityProvider securityProvider) {
this.securityProvider = securityProvider;
}
public UndertowSecurityProvider getSecurityProvider() {
return securityProvider;
}
}
|
UndertowComponent
|
java
|
spring-projects__spring-boot
|
module/spring-boot-jdbc/src/main/java/org/springframework/boot/jdbc/autoconfigure/PropertiesJdbcConnectionDetails.java
|
{
"start": 839,
"end": 1718
}
|
class ____ implements JdbcConnectionDetails {
private final DataSourceProperties properties;
PropertiesJdbcConnectionDetails(DataSourceProperties properties) {
this.properties = properties;
}
@Override
public @Nullable String getUsername() {
return this.properties.determineUsername();
}
@Override
public @Nullable String getPassword() {
return this.properties.determinePassword();
}
@Override
public String getJdbcUrl() {
return this.properties.determineUrl();
}
@Override
public String getDriverClassName() {
return this.properties.determineDriverClassName();
}
@Override
public @Nullable String getXaDataSourceClassName() {
return (this.properties.getXa().getDataSourceClassName() != null)
? this.properties.getXa().getDataSourceClassName()
: JdbcConnectionDetails.super.getXaDataSourceClassName();
}
}
|
PropertiesJdbcConnectionDetails
|
java
|
spring-projects__spring-boot
|
module/spring-boot-amqp/src/test/java/org/springframework/boot/amqp/autoconfigure/RabbitAutoConfigurationTests.java
|
{
"start": 61111,
"end": 61704
}
|
class ____ {
@Bean
RabbitConnectionDetails rabbitConnectionDetails() {
return new RabbitConnectionDetails() {
@Override
public String getUsername() {
return "user-1";
}
@Override
public String getPassword() {
return "password-1";
}
@Override
public String getVirtualHost() {
return "/vhost-1";
}
@Override
public List<Address> getAddresses() {
return List.of(new Address("rabbit.example.com", 12345), new Address("rabbit2.example.com", 23456));
}
};
}
}
@Configuration
static
|
ConnectionDetailsConfiguration
|
java
|
apache__kafka
|
streams/src/test/java/org/apache/kafka/streams/processor/internals/GlobalProcessorContextImplTest.java
|
{
"start": 2220,
"end": 9763
}
|
class ____ {
private static final String GLOBAL_STORE_NAME = "global-store";
private static final String GLOBAL_KEY_VALUE_STORE_NAME = "global-key-value-store";
private static final String GLOBAL_TIMESTAMPED_KEY_VALUE_STORE_NAME = "global-timestamped-key-value-store";
private static final String GLOBAL_WINDOW_STORE_NAME = "global-window-store";
private static final String GLOBAL_TIMESTAMPED_WINDOW_STORE_NAME = "global-timestamped-window-store";
private static final String GLOBAL_SESSION_STORE_NAME = "global-session-store";
private static final String UNKNOWN_STORE = "unknown-store";
private GlobalProcessorContextImpl globalContext;
@Mock
private ProcessorNode<Object, Object, Object, Object> child;
private ProcessorRecordContext recordContext;
@Mock
private GlobalStateManager stateManager;
@BeforeEach
public void setup() {
final StreamsConfig streamsConfig = mock(StreamsConfig.class);
when(streamsConfig.getString(StreamsConfig.APPLICATION_ID_CONFIG)).thenReturn("dummy-id");
globalContext = new GlobalProcessorContextImpl(
streamsConfig,
stateManager,
null,
null,
Time.SYSTEM);
final ProcessorNode<Object, Object, Object, Object> processorNode = new ProcessorNode<>("testNode");
processorNode.addChild(child);
globalContext.setCurrentNode(processorNode);
recordContext = mock(ProcessorRecordContext.class);
globalContext.setRecordContext(recordContext);
}
@Test
public void shouldReturnGlobalOrNullStore() {
when(stateManager.globalStore(GLOBAL_STORE_NAME)).thenReturn(mock(StateStore.class));
assertThat(globalContext.getStateStore(GLOBAL_STORE_NAME), new IsInstanceOf(StateStore.class));
assertNull(globalContext.getStateStore(UNKNOWN_STORE));
}
@Test
public void shouldForwardToSingleChild() {
doNothing().when(child).process(any());
when(recordContext.timestamp()).thenReturn(0L);
when(recordContext.headers()).thenReturn(new RecordHeaders());
globalContext.forward((Object /*forcing a call to the K/V forward*/) null, null);
}
@Test
public void shouldFailToForwardUsingToParameter() {
assertThrows(IllegalStateException.class, () -> globalContext.forward(null, null, To.all()));
}
@Test
public void shouldNotFailOnNoOpCommit() {
globalContext.commit();
}
@Test
public void shouldNotAllowToSchedulePunctuations() {
assertThrows(UnsupportedOperationException.class, () -> globalContext.schedule(null, null, null));
}
@Test
public void shouldNotAllowInitForKeyValueStore() {
when(stateManager.globalStore(GLOBAL_KEY_VALUE_STORE_NAME)).thenReturn(mock(KeyValueStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_KEY_VALUE_STORE_NAME);
try {
store.init(null, null);
fail("Should have thrown UnsupportedOperationException.");
} catch (final UnsupportedOperationException expected) { }
}
@Test
public void shouldNotAllowInitForTimestampedKeyValueStore() {
when(stateManager.globalStore(GLOBAL_TIMESTAMPED_KEY_VALUE_STORE_NAME)).thenReturn(mock(TimestampedKeyValueStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_TIMESTAMPED_KEY_VALUE_STORE_NAME);
try {
store.init(null, null);
fail("Should have thrown UnsupportedOperationException.");
} catch (final UnsupportedOperationException expected) { }
}
@Test
public void shouldNotAllowInitForWindowStore() {
when(stateManager.globalStore(GLOBAL_WINDOW_STORE_NAME)).thenReturn(mock(WindowStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_WINDOW_STORE_NAME);
try {
store.init(null, null);
fail("Should have thrown UnsupportedOperationException.");
} catch (final UnsupportedOperationException expected) { }
}
@Test
public void shouldNotAllowInitForTimestampedWindowStore() {
when(stateManager.globalStore(GLOBAL_TIMESTAMPED_WINDOW_STORE_NAME)).thenReturn(mock(TimestampedWindowStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_TIMESTAMPED_WINDOW_STORE_NAME);
try {
store.init(null, null);
fail("Should have thrown UnsupportedOperationException.");
} catch (final UnsupportedOperationException expected) { }
}
@Test
public void shouldNotAllowInitForSessionStore() {
when(stateManager.globalStore(GLOBAL_SESSION_STORE_NAME)).thenReturn(mock(SessionStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_SESSION_STORE_NAME);
try {
store.init(null, null);
fail("Should have thrown UnsupportedOperationException.");
} catch (final UnsupportedOperationException expected) { }
}
@Test
public void shouldNotAllowCloseForKeyValueStore() {
when(stateManager.globalStore(GLOBAL_KEY_VALUE_STORE_NAME)).thenReturn(mock(KeyValueStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_KEY_VALUE_STORE_NAME);
try {
store.close();
fail("Should have thrown UnsupportedOperationException.");
} catch (final UnsupportedOperationException expected) { }
}
@Test
public void shouldNotAllowCloseForTimestampedKeyValueStore() {
when(stateManager.globalStore(GLOBAL_TIMESTAMPED_KEY_VALUE_STORE_NAME)).thenReturn(mock(TimestampedKeyValueStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_TIMESTAMPED_KEY_VALUE_STORE_NAME);
try {
store.close();
fail("Should have thrown UnsupportedOperationException.");
} catch (final UnsupportedOperationException expected) { }
}
@Test
public void shouldNotAllowCloseForWindowStore() {
when(stateManager.globalStore(GLOBAL_WINDOW_STORE_NAME)).thenReturn(mock(WindowStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_WINDOW_STORE_NAME);
try {
store.close();
fail("Should have thrown UnsupportedOperationException.");
} catch (final UnsupportedOperationException expected) { }
}
@Test
public void shouldNotAllowCloseForTimestampedWindowStore() {
when(stateManager.globalStore(GLOBAL_TIMESTAMPED_WINDOW_STORE_NAME)).thenReturn(mock(TimestampedWindowStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_TIMESTAMPED_WINDOW_STORE_NAME);
try {
store.close();
fail("Should have thrown UnsupportedOperationException.");
} catch (final UnsupportedOperationException expected) { }
}
@Test
public void shouldNotAllowCloseForSessionStore() {
when(stateManager.globalStore(GLOBAL_SESSION_STORE_NAME)).thenReturn(mock(SessionStore.class));
final StateStore store = globalContext.getStateStore(GLOBAL_SESSION_STORE_NAME);
try {
store.close();
fail("Should have thrown UnsupportedOperationException.");
} catch (final UnsupportedOperationException expected) { }
}
@Test
public void shouldThrowOnCurrentStreamTime() {
assertThrows(UnsupportedOperationException.class, () -> globalContext.currentStreamTimeMs());
}
}
|
GlobalProcessorContextImplTest
|
java
|
square__retrofit
|
retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java
|
{
"start": 99367,
"end": 99945
}
|
class ____ {
@FormUrlEncoded
@POST("/query")
Call<ResponseBody> queryPath(@Field("a") Object a) {
return null;
}
}
Retrofit.Builder retrofitBuilder =
new Retrofit.Builder()
.baseUrl("http://example.com")
.addConverterFactory(new NullObjectConverterFactory());
Request request = buildRequest(Example.class, retrofitBuilder, "Ignored");
assertThat(request.url().toString()).doesNotContain("Ignored");
}
@Test
public void fieldParamMapsConvertedToNullShouldError() throws Exception {
|
Example
|
java
|
spring-projects__spring-data-jpa
|
spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/config/JpaRepositoriesRegistrarIntegrationTests.java
|
{
"start": 2263,
"end": 2514
}
|
class ____ {
@Autowired UserRepository repository;
@Autowired SampleRepository sampleRepository;
@Configuration
@EnableJpaRepositories(basePackages = "org.springframework.data.jpa.repository.sample")
static
|
JpaRepositoriesRegistrarIntegrationTests
|
java
|
apache__camel
|
components/camel-netty/src/test/java/org/apache/camel/component/netty/NettyOptionTest.java
|
{
"start": 969,
"end": 1673
}
|
class ____ extends NettyTCPSyncTest {
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("netty:tcp://localhost:{{port}}?sync=true&option.child.keepAlive=false")
.process(new Processor() {
public void process(Exchange exchange) {
exchange.getMessage().setBody(
"When You Go Home, Tell Them Of Us And Say, For Your Tomorrow, We Gave Our Today.");
}
});
}
};
}
}
|
NettyOptionTest
|
java
|
google__dagger
|
javatests/dagger/internal/codegen/MultibindingTest.java
|
{
"start": 18330,
"end": 18522
}
|
interface ____<out T>");
Source myInterface =
CompilerTests.kotlinSource(
"test.MyInterface.kt",
"package test",
"",
"
|
MyGenericInterface
|
java
|
spring-projects__spring-framework
|
spring-webflux/src/main/java/org/springframework/web/reactive/function/client/WebClient.java
|
{
"start": 3271,
"end": 5326
}
|
interface ____ {
/**
* Start building an HTTP GET request.
* @return a spec for specifying the target URL
*/
RequestHeadersUriSpec<?> get();
/**
* Start building an HTTP HEAD request.
* @return a spec for specifying the target URL
*/
RequestHeadersUriSpec<?> head();
/**
* Start building an HTTP POST request.
* @return a spec for specifying the target URL
*/
RequestBodyUriSpec post();
/**
* Start building an HTTP PUT request.
* @return a spec for specifying the target URL
*/
RequestBodyUriSpec put();
/**
* Start building an HTTP PATCH request.
* @return a spec for specifying the target URL
*/
RequestBodyUriSpec patch();
/**
* Start building an HTTP DELETE request.
* @return a spec for specifying the target URL
*/
RequestHeadersUriSpec<?> delete();
/**
* Start building an HTTP OPTIONS request.
* @return a spec for specifying the target URL
*/
RequestHeadersUriSpec<?> options();
/**
* Start building a request for the given {@code HttpMethod}.
* @return a spec for specifying the target URL
*/
RequestBodyUriSpec method(HttpMethod method);
/**
* Return a builder to create a new {@code WebClient} whose settings are
* replicated from the current {@code WebClient}.
*/
Builder mutate();
// Static, factory methods
/**
* Create a new {@code WebClient} with Reactor Netty by default.
* @see #create(String)
* @see #builder()
*/
static WebClient create() {
return new DefaultWebClientBuilder().build();
}
/**
* Variant of {@link #create()} that accepts a default base URL. For more
* details see {@link Builder#baseUrl(String) Builder.baseUrl(String)}.
* @param baseUrl the base URI for all requests
* @see #builder()
*/
static WebClient create(String baseUrl) {
return new DefaultWebClientBuilder().baseUrl(baseUrl).build();
}
/**
* Obtain a {@code WebClient} builder.
*/
static WebClient.Builder builder() {
return new DefaultWebClientBuilder();
}
/**
* A mutable builder for creating a {@link WebClient}.
*/
|
WebClient
|
java
|
apache__rocketmq
|
common/src/main/java/org/apache/rocketmq/common/help/FAQUrl.java
|
{
"start": 851,
"end": 3141
}
|
class ____ {
public static final String DEFAULT_FAQ_URL = "https://rocketmq.apache.org/docs/bestPractice/06FAQ";
public static final String APPLY_TOPIC_URL = DEFAULT_FAQ_URL;
public static final String NAME_SERVER_ADDR_NOT_EXIST_URL = DEFAULT_FAQ_URL;
public static final String GROUP_NAME_DUPLICATE_URL = DEFAULT_FAQ_URL;
public static final String CLIENT_PARAMETER_CHECK_URL = DEFAULT_FAQ_URL;
public static final String SUBSCRIPTION_GROUP_NOT_EXIST = DEFAULT_FAQ_URL;
public static final String CLIENT_SERVICE_NOT_OK = DEFAULT_FAQ_URL;
// FAQ: No route info of this topic, TopicABC
public static final String NO_TOPIC_ROUTE_INFO = DEFAULT_FAQ_URL;
public static final String LOAD_JSON_EXCEPTION = DEFAULT_FAQ_URL;
public static final String SAME_GROUP_DIFFERENT_TOPIC = DEFAULT_FAQ_URL;
public static final String MQLIST_NOT_EXIST = DEFAULT_FAQ_URL;
public static final String UNEXPECTED_EXCEPTION_URL = DEFAULT_FAQ_URL;
public static final String SEND_MSG_FAILED = DEFAULT_FAQ_URL;
public static final String UNKNOWN_HOST_EXCEPTION = DEFAULT_FAQ_URL;
private static final String TIP_STRING_BEGIN = "\nSee ";
private static final String TIP_STRING_END = " for further details.";
private static final String MORE_INFORMATION = "For more information, please visit the url, ";
public static String suggestTodo(final String url) {
StringBuilder sb = new StringBuilder(TIP_STRING_BEGIN.length() + url.length() + TIP_STRING_END.length());
sb.append(TIP_STRING_BEGIN);
sb.append(url);
sb.append(TIP_STRING_END);
return sb.toString();
}
public static String attachDefaultURL(final String errorMessage) {
if (errorMessage != null) {
int index = errorMessage.indexOf(TIP_STRING_BEGIN);
if (-1 == index) {
StringBuilder sb = new StringBuilder(errorMessage.length() + UNEXPECTED_EXCEPTION_URL.length() + MORE_INFORMATION.length() + 1);
sb.append(errorMessage);
sb.append("\n");
sb.append(MORE_INFORMATION);
sb.append(UNEXPECTED_EXCEPTION_URL);
return sb.toString();
}
}
return errorMessage;
}
}
|
FAQUrl
|
java
|
apache__camel
|
core/camel-util/src/main/java21/org/apache/camel/util/concurrent/ThreadType.java
|
{
"start": 1189,
"end": 1727
}
|
enum ____ {
PLATFORM,
VIRTUAL;
private static final Logger LOG = LoggerFactory.getLogger(ThreadType.class);
private static final ThreadType CURRENT = Boolean.getBoolean("camel.threads.virtual.enabled") ? VIRTUAL : PLATFORM;
static {
if (CURRENT == VIRTUAL) {
LOG.info("The type of thread detected is: {}", CURRENT);
} else {
LOG.debug("The type of thread detected is: {}", CURRENT);
}
}
public static ThreadType current() {
return CURRENT;
}
}
|
ThreadType
|
java
|
alibaba__nacos
|
config/src/test/java/com/alibaba/nacos/config/server/service/repository/embedded/EmbeddedConfigInfoTagPersistServiceImplTest.java
|
{
"start": 2511,
"end": 14841
}
|
class ____ {
MockedStatic<EnvUtil> envUtilMockedStatic;
MockedStatic<EmbeddedStorageContextHolder> embeddedStorageContextHolderMockedStatic;
MockedStatic<DynamicDataSource> dynamicDataSourceMockedStatic;
@Mock
DynamicDataSource dynamicDataSource;
@Mock
DatabaseOperate databaseOperate;
private EmbeddedConfigInfoTagPersistServiceImpl embeddedConfigInfoTagPersistService;
@Mock
private DataSourceService dataSourceService;
@BeforeEach
void before() {
embeddedStorageContextHolderMockedStatic = Mockito.mockStatic(EmbeddedStorageContextHolder.class);
dynamicDataSourceMockedStatic = Mockito.mockStatic(DynamicDataSource.class);
envUtilMockedStatic = Mockito.mockStatic(EnvUtil.class);
when(DynamicDataSource.getInstance()).thenReturn(dynamicDataSource);
when(dynamicDataSource.getDataSource()).thenReturn(dataSourceService);
when(dataSourceService.getDataSourceType()).thenReturn("derby");
envUtilMockedStatic.when(() -> EnvUtil.getProperty(anyString(), eq(Boolean.class), eq(false))).thenReturn(false);
embeddedConfigInfoTagPersistService = new EmbeddedConfigInfoTagPersistServiceImpl(databaseOperate);
}
@AfterEach
void after() {
dynamicDataSourceMockedStatic.close();
envUtilMockedStatic.close();
embeddedStorageContextHolderMockedStatic.close();
}
@Test
void testInsertOrUpdateTagOfAdd() {
String dataId = "dataId111222";
String group = "group";
String tenant = "tenant";
String appName = "appname1234";
String content = "c12345";
ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content);
configInfo.setEncryptedDataKey("key23456");
//mock query config state empty and return obj after insert
ConfigInfoStateWrapper configInfoStateWrapper = new ConfigInfoStateWrapper();
configInfoStateWrapper.setLastModified(System.currentTimeMillis());
configInfoStateWrapper.setId(234567890L);
String tag = "tag123";
Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, tag}),
eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null).thenReturn(configInfoStateWrapper);
String srcIp = "ip345678";
String srcUser = "user1234567";
ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTag(configInfo, tag, srcIp, srcUser);
//mock insert invoked.
embeddedStorageContextHolderMockedStatic.verify(
() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag), eq(appName),
eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class),
any(Timestamp.class)), times(1));
assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId());
assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified());
}
@Test
void testInsertOrUpdateTagOfUpdate() {
String dataId = "dataId111222";
String group = "group";
String tenant = "tenant";
String appName = "appname1234";
String content = "c12345";
ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content);
configInfo.setEncryptedDataKey("key23456");
//mock query config state and return obj after update
ConfigInfoStateWrapper configInfoStateWrapper = new ConfigInfoStateWrapper();
configInfoStateWrapper.setLastModified(System.currentTimeMillis());
configInfoStateWrapper.setId(234567890L);
String tag = "tag123";
Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, tag}),
eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()).thenReturn(configInfoStateWrapper);
String srcIp = "ip345678";
String srcUser = "user1234567";
ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTag(configInfo, tag, srcIp, srcUser);
//verify update to be invoked
embeddedStorageContextHolderMockedStatic.verify(() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(content),
eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), eq(appName),
eq(dataId), eq(group), eq(tenant), eq(tag)), times(1));
assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId());
assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified());
}
@Test
void testInsertOrUpdateTagCasOfAdd() {
String dataId = "dataId111222";
String group = "group";
String tenant = "tenant";
String appName = "appname1234";
String content = "c12345";
ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content);
configInfo.setEncryptedDataKey("key23456");
configInfo.setMd5("casMd5");
//mock query config state empty and return obj after insert
ConfigInfoStateWrapper configInfoStateWrapper = new ConfigInfoStateWrapper();
configInfoStateWrapper.setLastModified(System.currentTimeMillis());
configInfoStateWrapper.setId(234567890L);
String tag = "tag123";
Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, tag}),
eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(null).thenReturn(configInfoStateWrapper);
String srcIp = "ip345678";
String srcUser = "user1234567";
ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, tag, srcIp, srcUser);
//verify insert to be invoked
//mock insert invoked.
embeddedStorageContextHolderMockedStatic.verify(
() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag), eq(appName),
eq(content), eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class),
any(Timestamp.class)), times(1));
assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId());
assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified());
}
@Test
void testInsertOrUpdateTagCasOfUpdate() {
String dataId = "dataId111222";
String group = "group";
String tenant = "tenant";
String appName = "appname1234";
String content = "c12345";
ConfigInfo configInfo = new ConfigInfo(dataId, group, tenant, appName, content);
configInfo.setEncryptedDataKey("key23456");
configInfo.setMd5("casMd5");
//mock query config state and return obj after update
ConfigInfoStateWrapper configInfoStateWrapper = new ConfigInfoStateWrapper();
configInfoStateWrapper.setLastModified(System.currentTimeMillis());
configInfoStateWrapper.setId(234567890L);
String tag = "tag123";
Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, tag}),
eq(CONFIG_INFO_STATE_WRAPPER_ROW_MAPPER))).thenReturn(new ConfigInfoStateWrapper()).thenReturn(configInfoStateWrapper);
String srcIp = "ip345678";
String srcUser = "user1234567";
//mock cas update return 1
Mockito.when(databaseOperate.blockUpdate()).thenReturn(true);
ConfigOperateResult configOperateResult = embeddedConfigInfoTagPersistService.insertOrUpdateTagCas(configInfo, tag, srcIp, srcUser);
//verify update to be invoked
embeddedStorageContextHolderMockedStatic.verify(() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(content),
eq(MD5Utils.md5Hex(content, Constants.PERSIST_ENCODE)), eq(srcIp), eq(srcUser), any(Timestamp.class), eq(appName),
eq(dataId), eq(group), eq(tenant), eq(tag), eq(configInfo.getMd5())), times(1));
assertEquals(configInfoStateWrapper.getId(), configOperateResult.getId());
assertEquals(configInfoStateWrapper.getLastModified(), configOperateResult.getLastModified());
}
@Test
void testRemoveConfigInfoTag() {
String dataId = "dataId1112222";
String group = "group22";
String tenant = "tenant2";
String tag = "tag123345";
String srcIp = "ip345678";
String srcUser = "user1234567";
embeddedConfigInfoTagPersistService.removeConfigInfoTag(dataId, group, tenant, tag, srcIp, srcUser);
//verify delete sql invoked.
embeddedStorageContextHolderMockedStatic.verify(
() -> EmbeddedStorageContextHolder.addSqlContext(anyString(), eq(dataId), eq(group), eq(tenant), eq(tag)), times(1));
}
@Test
void testFindConfigInfo4Tag() {
String dataId = "dataId1112222";
String group = "group22";
String tenant = "tenant2";
String tag = "tag123345";
//mock query tag return obj
ConfigInfoTagWrapper configInfoTagWrapperMocked = new ConfigInfoTagWrapper();
configInfoTagWrapperMocked.setLastModified(System.currentTimeMillis());
Mockito.when(databaseOperate.queryOne(anyString(), eq(new Object[] {dataId, group, tenant, tag}),
eq(CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER))).thenReturn(configInfoTagWrapperMocked);
ConfigInfoTagWrapper configInfo4TagReturn = embeddedConfigInfoTagPersistService.findConfigInfo4Tag(dataId, group, tenant, tag);
assertEquals(configInfoTagWrapperMocked, configInfo4TagReturn);
}
@Test
void testConfigInfoTagCount() {
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//mock count
Mockito.when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(308);
//execute & verify
int count = embeddedConfigInfoTagPersistService.configInfoTagCount();
assertEquals(308, count);
}
@Test
void testFindAllConfigInfoTagForDumpAll() {
//mock count
Mockito.when(databaseOperate.queryOne(anyString(), eq(Integer.class))).thenReturn(308);
List<ConfigInfoTagWrapper> mockTagList = new ArrayList<>();
mockTagList.add(new ConfigInfoTagWrapper());
mockTagList.add(new ConfigInfoTagWrapper());
mockTagList.add(new ConfigInfoTagWrapper());
mockTagList.get(0).setLastModified(System.currentTimeMillis());
mockTagList.get(1).setLastModified(System.currentTimeMillis());
mockTagList.get(2).setLastModified(System.currentTimeMillis());
//mock query list
Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {}), eq(CONFIG_INFO_TAG_WRAPPER_ROW_MAPPER)))
.thenReturn(mockTagList);
int pageNo = 3;
int pageSize = 100;
//execute & verify
Page<ConfigInfoTagWrapper> returnTagPage = embeddedConfigInfoTagPersistService.findAllConfigInfoTagForDumpAll(pageNo, pageSize);
assertEquals(308, returnTagPage.getTotalCount());
assertEquals(mockTagList, returnTagPage.getPageItems());
}
@Test
void testFindConfigInfoTags() {
String dataId = "dataId1112222";
String group = "group22";
String tenant = "tenant2";
List<String> mockedTags = Arrays.asList("tags1", "tags11", "tags111");
Mockito.when(databaseOperate.queryMany(anyString(), eq(new Object[] {dataId, group, tenant}), eq(String.class)))
.thenReturn(mockedTags);
List<String> configInfoTags = embeddedConfigInfoTagPersistService.findConfigInfoTags(dataId, group, tenant);
assertEquals(mockedTags, configInfoTags);
}
}
|
EmbeddedConfigInfoTagPersistServiceImplTest
|
java
|
google__dagger
|
javatests/dagger/functional/assisted/AssistedFactoryWithAssistedInjectParamTest.java
|
{
"start": 1408,
"end": 1482
}
|
interface ____ {
Foo create(Bar bar);
}
@AssistedFactory
|
FooFactory
|
java
|
quarkusio__quarkus
|
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/multipart/TooLargeFormAttributeMultipartFormInputTest.java
|
{
"start": 1050,
"end": 3643
}
|
class ____ extends AbstractMultipartTest {
private static final java.nio.file.Path uploadDir = Paths.get("file-uploads");
@RegisterExtension
static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest()
.setUploadPath(uploadDir)
.setDeleteUploadedFilesOnEnd(false)
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(Resource.class, Status.class, FormDataBase.class, OtherPackageFormDataBase.class,
FormData.class);
}
});
private final File FORM_ATTR_SOURCE_FILE = new File("./src/test/resources/larger-than-default-form-attribute.txt");
private final File HTML_FILE = new File("./src/test/resources/test.html");
private final File XML_FILE = new File("./src/test/resources/test.html");
private final File TXT_FILE = new File("./src/test/resources/lorem.txt");
@BeforeEach
public void assertEmptyUploads() {
Assertions.assertTrue(isDirectoryEmpty(uploadDir));
}
@AfterEach
public void clearDirectory() {
clearDirectory(uploadDir);
}
@Test
public void test() throws IOException {
String fileContents = new String(Files.readAllBytes(FORM_ATTR_SOURCE_FILE.toPath()), StandardCharsets.UTF_8);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; ++i) {
sb.append(fileContents);
}
fileContents = sb.toString();
Assertions.assertTrue(fileContents.length() > HttpServerOptions.DEFAULT_MAX_FORM_ATTRIBUTE_SIZE);
given()
.multiPart("active", "true")
.multiPart("num", "25")
.multiPart("status", "WORKING")
.multiPart("htmlFile", HTML_FILE, "text/html")
.multiPart("xmlFile", XML_FILE, "text/xml")
.multiPart("txtFile", TXT_FILE, "text/plain")
.multiPart("name", fileContents)
.accept("text/plain")
.when()
.post("/test")
.then()
.statusCode(413);
// ensure that no files where created on disk
// as RESTEasy Reactive doesn't wait for the files to be deleted before returning the HTTP response,
// we need to wait in the test
awaitUploadDirectoryToEmpty(uploadDir);
}
@Path("/test")
public static
|
TooLargeFormAttributeMultipartFormInputTest
|
java
|
apache__hadoop
|
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/NotificationTestCase.java
|
{
"start": 1723,
"end": 2246
}
|
class ____ test Job end notification in local and cluster mode.
*
* Starts up hadoop on Local or Cluster mode (by extending of the
* HadoopTestCase class) and it starts a servlet engine that hosts
* a servlet that will receive the notification of job finalization.
*
* The notification servlet returns a HTTP 400 the first time is called
* and a HTTP 200 the second time, thus testing retry.
*
* In both cases local file system is used (this is irrelevant for
* the tested functionality)
*
*
*/
public abstract
|
to
|
java
|
spring-projects__spring-framework
|
spring-context/src/main/java/org/springframework/validation/DefaultBindingErrorProcessor.java
|
{
"start": 1783,
"end": 4426
}
|
class ____ implements BindingErrorProcessor {
/**
* Error code that a missing field error (i.e. a required field not
* found in the list of property values) will be registered with:
* "required".
*/
public static final String MISSING_FIELD_ERROR_CODE = "required";
@Override
public void processMissingFieldError(String missingField, BindingResult bindingResult) {
// Create field error with code "required".
String fixedField = bindingResult.getNestedPath() + missingField;
String[] codes = bindingResult.resolveMessageCodes(MISSING_FIELD_ERROR_CODE, missingField);
Object[] arguments = getArgumentsForBindError(bindingResult.getObjectName(), fixedField);
FieldError error = new FieldError(bindingResult.getObjectName(), fixedField, "", true,
codes, arguments, "Field '" + fixedField + "' is required");
bindingResult.addError(error);
}
@Override
public void processPropertyAccessException(PropertyAccessException ex, BindingResult bindingResult) {
// Create field error with the code of the exception, for example, "typeMismatch".
String field = ex.getPropertyName();
Assert.state(field != null, "No field in exception");
String[] codes = bindingResult.resolveMessageCodes(ex.getErrorCode(), field);
Object[] arguments = getArgumentsForBindError(bindingResult.getObjectName(), field);
Object rejectedValue = ex.getValue();
if (ObjectUtils.isArray(rejectedValue)) {
rejectedValue = StringUtils.arrayToCommaDelimitedString(ObjectUtils.toObjectArray(rejectedValue));
}
FieldError error = new FieldError(bindingResult.getObjectName(), field, rejectedValue, true,
codes, arguments, ex.getLocalizedMessage());
error.wrap(ex);
bindingResult.addError(error);
}
/**
* Return FieldError arguments for a binding error on the given field.
* Invoked for each missing required field and each type mismatch.
* <p>The default implementation returns a single argument indicating the field name
* (of type DefaultMessageSourceResolvable, with "objectName.field" and "field" as codes).
* @param objectName the name of the target object
* @param field the field that caused the binding error
* @return the Object array that represents the FieldError arguments
* @see org.springframework.validation.FieldError#getArguments
* @see org.springframework.context.support.DefaultMessageSourceResolvable
*/
protected Object[] getArgumentsForBindError(String objectName, String field) {
String[] codes = new String[] {objectName + Errors.NESTED_PATH_SEPARATOR + field, field};
return new Object[] {new DefaultMessageSourceResolvable(codes, field)};
}
}
|
DefaultBindingErrorProcessor
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/submitted/dml_return_types/User.java
|
{
"start": 712,
"end": 1085
}
|
class ____ {
private int id;
private String name;
public User() {
}
public User(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|
User
|
java
|
apache__hadoop
|
hadoop-tools/hadoop-rumen/src/main/java/org/apache/hadoop/tools/rumen/DeepInequalityException.java
|
{
"start": 876,
"end": 962
}
|
class ____ the unit test, and we do a deep comparison
* when we run the
*
*/
public
|
in
|
java
|
spring-projects__spring-security
|
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/OAuth2RefreshTokenAuthenticationToken.java
|
{
"start": 1269,
"end": 2564
}
|
class ____ extends OAuth2AuthorizationGrantAuthenticationToken {
private final String refreshToken;
private final Set<String> scopes;
/**
* Constructs an {@code OAuth2RefreshTokenAuthenticationToken} using the provided
* parameters.
* @param refreshToken the refresh token
* @param clientPrincipal the authenticated client principal
* @param scopes the requested scope(s)
* @param additionalParameters the additional parameters
*/
public OAuth2RefreshTokenAuthenticationToken(String refreshToken, Authentication clientPrincipal,
@Nullable Set<String> scopes, @Nullable Map<String, Object> additionalParameters) {
super(AuthorizationGrantType.REFRESH_TOKEN, clientPrincipal, additionalParameters);
Assert.hasText(refreshToken, "refreshToken cannot be empty");
this.refreshToken = refreshToken;
this.scopes = Collections.unmodifiableSet((scopes != null) ? new HashSet<>(scopes) : Collections.emptySet());
}
/**
* Returns the refresh token.
* @return the refresh token
*/
public String getRefreshToken() {
return this.refreshToken;
}
/**
* Returns the requested scope(s).
* @return the requested scope(s), or an empty {@code Set} if not available
*/
public Set<String> getScopes() {
return this.scopes;
}
}
|
OAuth2RefreshTokenAuthenticationToken
|
java
|
apache__kafka
|
streams/test-utils/src/main/java/org/apache/kafka/streams/processor/MockProcessorContext.java
|
{
"start": 21728,
"end": 22260
}
|
interface ____ assumed by state stores that add change-logging.
// Rather than risk a mysterious ClassCastException during unit tests, throw an explanatory exception.
throw new UnsupportedOperationException(
"MockProcessorContext does not provide record collection. " +
"For processor unit tests, use an in-memory state store with change-logging disabled. " +
"Alternatively, use the TopologyTestDriver for testing processor/store/topology integration."
);
}
}
|
is
|
java
|
apache__camel
|
core/camel-api/src/main/java/org/apache/camel/spi/BrowsableVariableRepository.java
|
{
"start": 967,
"end": 1423
}
|
interface ____ extends VariableRepository {
/**
* Are there any variables in the repository.
*/
boolean hasVariables();
/**
* Number of variables
*/
int size();
/**
* The variable names
*/
Stream<String> names();
/**
* Gets all the variables in a Map
*/
Map<String, Object> getVariables();
/**
* Removes all variables
*/
void clear();
}
|
BrowsableVariableRepository
|
java
|
resilience4j__resilience4j
|
resilience4j-consumer/src/test/java/io/github/resilience4j/consumer/EventConsumerRegistryTest.java
|
{
"start": 874,
"end": 2876
}
|
class ____ {
@Test
public void shouldCreateAnEventConsumer() {
EventConsumerRegistry<CircuitBreakerEvent> registry = new DefaultEventConsumerRegistry<>();
EventConsumer<CircuitBreakerEvent> eventEventConsumer = registry
.createEventConsumer("testName", 5);
assertThat(eventEventConsumer).isNotNull();
}
@Test
public void shouldRemoveAnEventConsumer() {
EventConsumerRegistry<CircuitBreakerEvent> registry = new DefaultEventConsumerRegistry<>();
String eventConsumerId = "testName";
EventConsumer<CircuitBreakerEvent> eventEventConsumerAdded = registry.createEventConsumer(eventConsumerId, 5);
assertThat(eventEventConsumerAdded).isNotNull();
EventConsumer<CircuitBreakerEvent> eventEventConsumerRemoved = registry.removeEventConsumer(eventConsumerId);
assertThat(eventEventConsumerRemoved).isNotNull();
assertThat(eventEventConsumerAdded).isEqualTo(eventEventConsumerRemoved);
EventConsumer<CircuitBreakerEvent> eventEventConsumer = registry.getEventConsumer(eventConsumerId);
assertThat(eventEventConsumer).isNull();
}
@Test
public void shouldReturnTheSameEventConsumer() {
EventConsumerRegistry<CircuitBreakerEvent> registry = new DefaultEventConsumerRegistry<>();
EventConsumer<CircuitBreakerEvent> eventEventConsumer1 = registry
.createEventConsumer("testName", 5);
EventConsumer<CircuitBreakerEvent> eventEventConsumer2 = registry
.getEventConsumer("testName");
assertThat(eventEventConsumer1).isEqualTo(eventEventConsumer2);
}
@Test
public void shouldReturnAllEventConsumer() {
EventConsumerRegistry<CircuitBreakerEvent> registry = new DefaultEventConsumerRegistry<>();
registry.createEventConsumer("testName1", 5);
registry.createEventConsumer("testName2", 2);
assertThat(registry.getAllEventConsumer()).hasSize(2);
}
}
|
EventConsumerRegistryTest
|
java
|
apache__flink
|
flink-runtime/src/test/java/org/apache/flink/runtime/resourcemanager/StandaloneResourceManagerTest.java
|
{
"start": 5626,
"end": 6973
}
|
class ____ extends StandaloneResourceManager {
private TestingStandaloneResourceManager(
RpcService rpcService,
UUID leaderSessionId,
ResourceID resourceId,
HeartbeatServices heartbeatServices,
DelegationTokenManager delegationTokenManager,
SlotManager slotManager,
JobLeaderIdService jobLeaderIdService,
ClusterInformation clusterInformation,
FatalErrorHandler fatalErrorHandler,
ResourceManagerMetricGroup resourceManagerMetricGroup,
Duration startupPeriodTime) {
super(
rpcService,
leaderSessionId,
resourceId,
heartbeatServices,
delegationTokenManager,
slotManager,
NoOpResourceManagerPartitionTracker::get,
new NoOpBlocklistHandler.Factory(),
jobLeaderIdService,
clusterInformation,
fatalErrorHandler,
resourceManagerMetricGroup,
startupPeriodTime,
RpcUtils.INF_TIMEOUT,
ForkJoinPool.commonPool());
}
}
}
|
TestingStandaloneResourceManager
|
java
|
elastic__elasticsearch
|
plugins/mapper-size/src/main/java/org/elasticsearch/index/mapper/size/SizeFieldMapper.java
|
{
"start": 1402,
"end": 1951
}
|
class ____ extends MetadataFieldMapper.Builder {
private final Parameter<Explicit<Boolean>> enabled = updateableBoolParam("enabled", m -> toType(m).enabled, false);
private Builder() {
super(NAME);
}
@Override
protected Parameter<?>[] getParameters() {
return new Parameter<?>[] { enabled };
}
@Override
public SizeFieldMapper build() {
return new SizeFieldMapper(enabled.getValue(), new SizeFieldType());
}
}
private static
|
Builder
|
java
|
quarkusio__quarkus
|
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/providers/ParamConverterTest.java
|
{
"start": 1694,
"end": 2366
}
|
class ____ {
@Path("single")
@GET
public String single(@QueryParam("id") UUID uuid) {
return uuid.toString();
}
@Path("set")
@GET
public String set(@QueryParam("id") Set<UUID> uuids) {
return join(uuids.stream());
}
@Path("list")
@GET
public String list(@QueryParam("id") List<? extends UUID> uuids) {
return join(uuids.stream());
}
private static String join(Stream<? extends UUID> uuids) {
return uuids.map(UUID::toString).collect(Collectors.joining(","));
}
}
@Provider
public static
|
UUIDResource
|
java
|
elastic__elasticsearch
|
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/attachment/EmailAttachmentParser.java
|
{
"start": 896,
"end": 2491
}
|
interface ____ extends ToXContentFragment {
/**
* @return A type to identify the email attachment, same as the parser identifier
*/
String type();
/**
* @return The id of this attachment
*/
String id();
/**
* Allows the attachment to decide of it should be of disposition type attachment or inline, which is important
* for being able to display inside of desktop email clients
*
* @return a boolean flagging this attachment as being inline
*/
boolean inline();
}
/**
* @return An identifier of this parser
*/
String type();
/**
* A parser to create an EmailAttachment, that is serializable and does not execute anything
*
* @param id The id of this attachment, parsed from the outer content
* @param parser The XContentParser used for parsing
* @return A concrete EmailAttachment
* @throws IOException in case parsing fails
*/
T parse(String id, XContentParser parser) throws IOException;
/**
* Converts an email attachment to an attachment, potentially executing code like an HTTP request
* @param context The WatchExecutionContext supplied with the whole watch execution
* @param payload The Payload supplied with the action
* @param attachment The typed attachment
* @return An attachment that is ready to be used in a MimeMessage
*/
Attachment toAttachment(WatchExecutionContext context, Payload payload, T attachment) throws IOException;
}
|
EmailAttachment
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/spi/DotIdentifierSequence.java
|
{
"start": 326,
"end": 425
}
|
interface ____ a standard way of interacting with them.
*
* @author Steve Ebersole
*/
public
|
defines
|
java
|
hibernate__hibernate-orm
|
hibernate-core/src/main/java/org/hibernate/query/sqm/mutation/spi/SqmMultiTableMutationStrategyProvider.java
|
{
"start": 589,
"end": 1118
}
|
interface ____ extends Service {
/**
* Determine the SqmMultiTableMutationStrategy to use for the given entity
*/
SqmMultiTableMutationStrategy createMutationStrategy(
EntityMappingType rootEntityDescriptor,
MappingModelCreationProcess creationProcess);
/**
* Determine the SqmMultiTableInsertStrategy to use for the given entity
*/
SqmMultiTableInsertStrategy createInsertStrategy(
EntityMappingType rootEntityDescriptor,
MappingModelCreationProcess creationProcess);
}
|
SqmMultiTableMutationStrategyProvider
|
java
|
mybatis__mybatis-3
|
src/test/java/org/apache/ibatis/submitted/xml_external_ref/MultipleCrossIncludePersonMapper.java
|
{
"start": 712,
"end": 818
}
|
interface ____ {
Person select(Integer id);
Pet selectPet(Integer id);
}
|
MultipleCrossIncludePersonMapper
|
java
|
apache__camel
|
components/camel-mustache/src/test/java/org/apache/camel/component/mustache/MustacheComponentTest.java
|
{
"start": 1346,
"end": 5791
}
|
class ____ extends CamelTestSupport {
@EndpointInject("mock:endSimple")
protected MockEndpoint endSimpleMock;
@Produce("direct:startSimple")
protected ProducerTemplate startSimpleProducerTemplate;
/**
* Main test
*/
@Test
public void testMustache() throws Exception {
// Prepare
endSimpleMock.expectedMessageCount(1);
endSimpleMock.expectedBodiesReceived("\nMessage with body 'The Body' and some header 'Some Header'");
// Act
startSimpleProducerTemplate.sendBodyAndHeader("The Body", "someHeader", "Some Header");
// Verify
MockEndpoint.assertIsSatisfied(context);
}
/**
* Test using code Template header
*/
@Test
public void testMustacheWithTemplateHeader() throws Exception {
// Prepare
Exchange exchange = createExchangeWithBody("The Body");
exchange.getIn().setHeader("someHeader", "Some Header");
exchange.getIn().setHeader(MustacheConstants.MUSTACHE_TEMPLATE, "Body='{{body}}'|SomeHeader='{{headers.someHeader}}'");
endSimpleMock.expectedMessageCount(1);
endSimpleMock.expectedBodiesReceived("Body='The Body'|SomeHeader='Some Header'");
// Act
startSimpleProducerTemplate.send(exchange);
// Verify
MockEndpoint.assertIsSatisfied(context);
}
/**
* Test using Resource URI header
*/
@Test
public void testMustacheWithResourceUriHeader() throws Exception {
// Prepare
Exchange exchange = createExchangeWithBody("The Body");
exchange.getIn().setHeader("someHeader", "Some Header");
exchange.getIn().setHeader(MustacheConstants.MUSTACHE_RESOURCE_URI, "/another.mustache");
endSimpleMock.expectedMessageCount(1);
endSimpleMock.message(0).body().contains("The Body");
endSimpleMock.message(0).body().contains("Some Header");
// Act
startSimpleProducerTemplate.send(exchange);
// Verify
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testMustacheWithInheritance() throws Exception {
// Prepare
Exchange exchange = createExchangeWithBody("The Body");
exchange.getIn().setHeader(MustacheConstants.MUSTACHE_RESOURCE_URI, "/child.mustache");
endSimpleMock.expectedMessageCount(1);
endSimpleMock.message(0).body().contains("Content 1: Child 1");
endSimpleMock.message(0).body().contains("Middle");
endSimpleMock.message(0).body().contains("Content 2: Child 2");
// Act
startSimpleProducerTemplate.send(exchange);
// Verify
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testMustacheWithPartials() throws Exception {
// Prepare
Exchange exchange = createExchangeWithBody("The Body");
exchange.getIn().setHeader(MustacheConstants.MUSTACHE_RESOURCE_URI, "/includer.mustache");
endSimpleMock.expectedMessageCount(1);
endSimpleMock.message(0).body().contains("Start");
endSimpleMock.message(0).body().contains("Included");
endSimpleMock.message(0).body().contains("End");
// Act
startSimpleProducerTemplate.send(exchange);
// Verify
MockEndpoint.assertIsSatisfied(context);
}
/**
* Main test
*/
@Test
public void testMustachePerformance() throws Exception {
int messageCount = 10000;
endSimpleMock.expectedMessageCount(messageCount);
StopWatch stopwatch = new StopWatch(true);
for (int i = 0; i < messageCount; i++) {
startSimpleProducerTemplate.sendBodyAndHeader("The Body", "someHeader", "Some Header");
}
MockEndpoint.assertIsSatisfied(context);
LoggerFactory.getLogger(getClass())
.info("Mustache performance: " + stopwatch.taken() + "ms for " + messageCount + " messages");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
MustacheComponent mc = context.getComponent("mustache", MustacheComponent.class);
mc.setAllowTemplateFromHeader(true);
from("direct:startSimple")
.to("mustache://simple.mustache")
.to("mock:endSimple");
}
};
}
}
|
MustacheComponentTest
|
java
|
hibernate__hibernate-orm
|
tooling/metamodel-generator/src/main/java/org/hibernate/processor/util/TypeUtils.java
|
{
"start": 9537,
"end": 10132
}
|
class ____ the {@code Element} or {@code null} in case
* the {@code TypeElement} does not host the specified annotation.
*/
public static @Nullable AnnotationMirror getAnnotationMirror(Element element, String qualifiedName) {
assert element != null;
assert qualifiedName != null;
for ( AnnotationMirror mirror : element.getAnnotationMirrors() ) {
if ( isAnnotationMirrorOfType( mirror, qualifiedName ) ) {
return mirror;
}
}
return null;
}
/**
* Checks whether the {@code Element} hosts the annotation (directly or inherited) with the given fully qualified
|
from
|
java
|
redisson__redisson
|
redisson/src/main/java/org/redisson/mapreduce/MapperTask.java
|
{
"start": 1079,
"end": 2553
}
|
class ____<KIn, VIn, KOut, VOut> extends BaseMapperTask<KOut, VOut> {
private static final long serialVersionUID = 2441161019495880394L;
protected RMapper<KIn, VIn, KOut, VOut> mapper;
public MapperTask() {
}
public MapperTask(RMapper<KIn, VIn, KOut, VOut> mapper, Class<?> objectClass, Class<?> objectCodecClass) {
super(objectClass, objectCodecClass);
this.mapper = mapper;
}
@Override
public void run() {
Codec codec;
try {
codec = (Codec) objectCodecClass.getConstructor().newInstance();
} catch (Exception e) {
throw new IllegalStateException(e);
}
Injector.inject(mapper, redisson);
RCollector<KOut, VOut> collector = new Collector<KOut, VOut>(codec, redisson, collectorMapName, workersAmount, timeout);
for (String objectName : objectNames) {
RMap<KIn, VIn> map = null;
if (RMapCache.class.isAssignableFrom(objectClass)) {
map = redisson.getMapCache(objectName, codec);
} else {
map = redisson.getMap(objectName, codec);
}
for (Entry<KIn, VIn> entry : map.entrySet()) {
if (Thread.currentThread().isInterrupted()) {
return;
}
mapper.map(entry.getKey(), entry.getValue(), collector);
}
}
}
}
|
MapperTask
|
java
|
spring-projects__spring-framework
|
spring-core/src/test/java/org/springframework/core/annotation/AnnotationTypeMappingsTests.java
|
{
"start": 25219,
"end": 25415
}
|
interface ____ {
@AliasFor(annotation = AliasForWithIncompatibleReturnTypesTarget.class)
String[] test() default {};
}
@Retention(RetentionPolicy.RUNTIME)
@
|
AliasForWithIncompatibleReturnTypes
|
java
|
micronaut-projects__micronaut-core
|
inject-java/src/test/groovy/io/micronaut/visitors/MySimpleClass.java
|
{
"start": 39,
"end": 431
}
|
class ____ {
private String name;
private int age;
public MySimpleClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
MySimpleClass
|
java
|
spring-projects__spring-framework
|
spring-jdbc/src/main/java/org/springframework/jdbc/core/namedparam/EmptySqlParameterSource.java
|
{
"start": 859,
"end": 1580
}
|
class ____ implements SqlParameterSource {
/**
* A shared instance of {@link EmptySqlParameterSource}.
*/
public static final EmptySqlParameterSource INSTANCE = new EmptySqlParameterSource();
@Override
public boolean hasValue(String paramName) {
return false;
}
@Override
public @Nullable Object getValue(String paramName) throws IllegalArgumentException {
throw new IllegalArgumentException("This SqlParameterSource is empty");
}
@Override
public int getSqlType(String paramName) {
return TYPE_UNKNOWN;
}
@Override
public @Nullable String getTypeName(String paramName) {
return null;
}
@Override
public String @Nullable [] getParameterNames() {
return null;
}
}
|
EmptySqlParameterSource
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.