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 | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/RedisPublisher.java | {
"start": 31087,
"end": 32840
} | class ____ implements Runnable {
private static final Recycler<OnComplete> RECYCLER = new Recycler<OnComplete>() {
@Override
protected OnComplete newObject(Handle<OnComplete> handle) {
return new OnComplete(handle);
}
};
private final Recycler.Handle<OnComplete> handle;
private Throwable signal;
private Subscriber<?> subscriber;
OnComplete(Recycler.Handle<OnComplete> handle) {
this.handle = handle;
}
/**
* Allocate a new instance.
*
* @return
* @see Subscriber#onError(Throwable)
*/
static OnComplete newInstance(Throwable signal, Subscriber<?> subscriber) {
OnComplete entry = RECYCLER.get();
entry.signal = signal;
entry.subscriber = subscriber;
return entry;
}
/**
* Allocate a new instance.
*
* @return
* @see Subscriber#onComplete()
*/
static OnComplete newInstance(Subscriber<?> subscriber) {
OnComplete entry = RECYCLER.get();
entry.signal = null;
entry.subscriber = subscriber;
return entry;
}
@Override
public void run() {
try {
if (signal != null) {
subscriber.onError(signal);
} else {
subscriber.onComplete();
}
} finally {
recycle();
}
}
private void recycle() {
this.signal = null;
this.subscriber = null;
handle.recycle(this);
}
}
}
| OnComplete |
java | apache__camel | components/camel-web3j/src/main/java/org/apache/camel/component/web3j/Web3jConstants.java | {
"start": 892,
"end": 11891
} | interface ____ {
String WEB3_CLIENT_VERSION = "WEB3_CLIENT_VERSION";
String WEB3_SHA3 = "WEB3_SHA3";
String NET_VERSION = "NET_VERSION";
String NET_LISTENING = "NET_LISTENING";
String NET_PEER_COUNT = "NET_PEER_COUNT";
String ETH_PROTOCOL_VERSION = "ethProtocolVersion";
String ETH_COINBASE = "ETH_COINBASE";
String ETH_SYNCING = "ETH_SYNCING";
String ETH_MINING = "ETH_MINING";
@Metadata(label = "producer", description = "A hexadecimal string representation (32 bytes) of the hash rate.",
javaType = "String")
String ETH_HASHRATE = "ETH_HASHRATE";
String ETH_GAS_PRICE = "ETH_GAS_PRICE";
String ETH_ACCOUNTS = "ETH_ACCOUNTS";
String ETH_BLOCK_NUMBER = "ETH_BLOCK_NUMBER";
String ETH_GET_BALANCE = "ETH_GET_BALANCE";
String ETH_GET_STORAGE_AT = "ETH_GET_STORAGE_AT";
String ETH_GET_TRANSACTION_COUNT = "ETH_GET_TRANSACTION_COUNT";
String ETH_GET_BLOCK_TRANSACTION_COUNT_BY_HASH = "ETH_GET_BLOCK_TRANSACTION_COUNT_BY_HASH";
String ETH_GET_BLOCK_TRANSACTION_COUNT_BY_NUMBER = "ETH_GET_BLOCK_TRANSACTION_COUNT_BY_NUMBER";
String ETH_GET_UNCLE_COUNT_BY_BLOCK_HASH = "ETH_GET_UNCLE_COUNT_BY_BLOCK_HASH";
String ETH_GET_UNCLE_COUNT_BY_BLOCK_NUMBER = "ETH_GET_UNCLE_COUNT_BY_BLOCK_NUMBER";
String ETH_GET_CODE = "ETH_GET_CODE";
String ETH_SIGN = "ETH_SIGN";
String ETH_SEND_TRANSACTION = "ETH_SEND_TRANSACTION";
String ETH_SEND_RAW_TRANSACTION = "ETH_SEND_RAW_TRANSACTION";
String ETH_CALL = "ETH_CALL";
String ETH_ESTIMATE_GAS = "ETH_ESTIMATE_GAS";
String ETH_GET_BLOCK_BY_HASH = "ETH_GET_BLOCK_BY_HASH";
String ETH_GET_BLOCK_BY_NUMBER = "ETH_GET_BLOCK_BY_NUMBER";
String ETH_GET_TRANSACTION_BY_HASH = "ETH_GET_TRANSACTION_BY_HASH";
String ETH_GET_TRANSACTION_BY_BLOCK_HASH_AND_INDEX = "ETH_GET_TRANSACTION_BY_BLOCK_HASH_AND_INDEX";
String ETH_GET_TRANSACTION_BY_BLOCK_NUMBER_AND_INDEX = "ETH_GET_TRANSACTION_BY_BLOCK_NUMBER_AND_INDEX";
String ETH_GET_TRANSACTION_RECEIPT = "ETH_GET_TRANSACTION_RECEIPT";
String ETH_GET_UNCLE_BY_BLOCK_HASH_AND_INDEX = "ETH_GET_UNCLE_BY_BLOCK_HASH_AND_INDEX";
String ETH_GET_UNCLE_BY_BLOCK_NUMBER_AND_INDEX = "ETH_GET_UNCLE_BY_BLOCK_NUMBER_AND_INDEX";
String ETH_GET_COMPILERS = "ETH_GET_COMPILERS";
String ETH_COMPILE_LLL = "ETH_COMPILE_LLL";
String ETH_COMPILE_SOLIDITY = "ETH_COMPILE_SOLIDITY";
String ETH_COMPILE_SERPENT = "ETH_COMPILE_SERPENT";
String ETH_NEW_FILTER = "ETH_NEW_FILTER";
String ETH_NEW_BLOCK_FILTER = "ETH_NEW_BLOCK_FILTER";
String ETH_NEW_PENDING_TRANSACTION_FILTER = "ETH_NEW_PENDING_TRANSACTION_FILTER";
String ETH_UNINSTALL_FILTER = "ETH_UNINSTALL_FILTER";
String ETH_GET_FILTER_CHANGES = "ETH_GET_FILTER_CHANGES";
String ETH_GET_FILTER_LOGS = "ETH_GET_FILTER_LOGS";
String ETH_GET_LOGS = "ETH_GET_LOGS";
String ETH_GET_WORK = "ETH_GET_WORK";
String ETH_SUBMIT_WORK = "ETH_SUBMIT_WORK";
String ETH_SUBMIT_HASHRATE = "ETH_SUBMIT_HASHRATE";
String DB_PUT_STRING = "DB_PUT_STRING";
String DB_GET_STRING = "DB_GET_STRING";
String DB_PUT_HEX = "DB_PUT_HEX";
String DB_GET_HEX = "DB_GET_HEX";
String SHH_VERSION = "SHH_VERSION";
String SHH_POST = "SHH_POST";
String SHH_NEW_IDENTITY = "SHH_NEW_IDENTITY";
String SHH_HAS_IDENTITY = "SHH_HAS_IDENTITY";
String SHH_NEW_GROUP = "SHH_NEW_GROUP";
String SHH_ADD_TO_GROUP = "SHH_ADD_TO_GROUP";
String SHH_NEW_FILTER = "SHH_NEW_FILTER";
String SHH_UNINSTALL_FILTER = "SHH_UNINSTALL_FILTER";
String SHH_GET_FILTER_CHANGES = "SHH_GET_FILTER_CHANGES";
String SHH_GET_MESSAGES = "SHH_GET_MESSAGES";
String QUORUM_ETH_SEND_TRANSACTION = "QUORUM_ETH_SEND_TRANSACTION";
String QUORUM_NODE_INFO = "QUORUM_NODE_INFO";
String QUORUM_GET_PRIVATE_PAYLOAD = "QUORUM_GET_PRIVATE_PAYLOAD";
String ETH_LOG_OBSERVABLE = "ETH_LOG_OBSERVABLE";
String ETH_BLOCK_HASH_OBSERVABLE = "ETH_BLOCK_HASH_OBSERVABLE";
String ETH_PENDING_TRANSACTION_HASH_OBSERVABLE = "ETH_PENDING_TRANSACTION_HASH_OBSERVABLE";
String TRANSACTION_OBSERVABLE = "TRANSACTION_OBSERVABLE";
String PENDING_TRANSACTION_OBSERVABLE = "PENDING_TRANSACTION_OBSERVABLE";
String BLOCK_OBSERVABLE = "BLOCK_OBSERVABLE";
String REPLAY_BLOCKS_OBSERVABLE = "REPLAY_BLOCKS_OBSERVABLE";
String REPLAY_TRANSACTIONS_OBSERVABLE = "REPLAY_TRANSACTIONS_OBSERVABLE";
@Metadata(label = "producer", description = "The id", javaType = "Long")
String ID = "ID";
String OPERATION = "OPERATION";
String TRANSACTION = "TRANSACTION";
/**
* The block number, or the string "latest" for the last mined block or "pending", "earliest" for not yet mined
* transactions.
*/
@Metadata(label = "producer", javaType = "String")
String AT_BLOCK = "AT_BLOCK";
@Metadata(label = "producer", description = "Contract address.", javaType = "String")
String ADDRESS = "ADDRESS";
@Metadata(label = "producer", description = "Contract address or a list of addresses.", javaType = "List<String>")
String ADDRESSES = "ADDRESSES";
@Metadata(label = "producer", description = "The address the transaction is send from", javaType = "String")
String FROM_ADDRESS = "FROM_ADDRESS";
@Metadata(label = "producer", description = "The address the transaction is directed to", javaType = "String")
String TO_ADDRESS = "TO_ADDRESS";
@Metadata(label = "producer", description = "The transaction index position withing a block.", javaType = "String")
String POSITION = "POSITION";
@Metadata(label = "producer", description = "Hash of the block where this transaction was in.", javaType = "String")
String BLOCK_HASH = "BLOCK_HASH";
@Metadata(label = "producer", description = "The information about a transaction requested by transaction hash.",
javaType = "String")
String TRANSACTION_HASH = "TRANSACTION_HASH";
@Metadata(label = "producer", description = "Message to sign by calculating an Ethereum specific signature.",
javaType = "String")
String SHA3_HASH_OF_DATA_TO_SIGN = "SHA3_HASH_OF_DATA_TO_SIGN";
@Metadata(label = "producer",
description = "The signed transaction data for a new message call transaction or a contract creation for signed transactions.",
javaType = "String")
String SIGNED_TRANSACTION_DATA = "SIGNED_TRANSACTION_DATA";
@Metadata(label = "producer",
description = "If true it returns the full transaction objects, if false only the hashes of the transactions.",
javaType = "Boolean")
String FULL_TRANSACTION_OBJECTS = "FULL_TRANSACTION_OBJECTS";
@Metadata(label = "producer", description = "The transactions/uncle index position in the block.", javaType = "String")
String INDEX = "INDEX";
@Metadata(label = "producer", description = "The source code to compile.", javaType = "String")
String SOURCE_CODE = "SOURCE_CODE";
@Metadata(label = "producer", description = "The filter id to use.", javaType = "java.math.BigInteger")
String FILTER_ID = "FILTER_ID";
@Metadata(label = "producer", description = "The local database name.", javaType = "String")
String DATABASE_NAME = "DATABASE_NAME";
@Metadata(label = "producer", description = "The key name in the database.", javaType = "String")
String KEY_NAME = "KEY_NAME";
@Metadata(label = "producer", description = "The nonce found (64 bits) used for submitting a proof-of-work solution.",
javaType = "java.math.BigInteger")
String NONCE = "NONCE";
@Metadata(label = "producer",
description = "The header's pow-hash (256 bits) used for submitting a proof-of-work solution.",
javaType = "String")
String HEADER_POW_HASH = "HEADER_POW_HASH";
@Metadata(label = "producer", description = "The mix digest (256 bits) used for submitting a proof-of-work solution.",
javaType = "String")
String MIX_DIGEST = "MIX_DIGEST";
@Metadata(label = "producer", description = "A random hexadecimal(32 bytes) ID identifying the client.",
javaType = "String")
String CLIENT_ID = "CLIENT_ID";
@Metadata(label = "producer", description = "Gas price used for each paid gas.", javaType = "java.math.BigInteger")
String GAS_PRICE = "GAS_PRICE";
@Metadata(label = "producer", description = "The maximum gas allowed in this block.", javaType = "java.math.BigInteger")
String GAS_LIMIT = "GAS_LIMIT";
@Metadata(label = "producer", description = "The value sent within a transaction.", javaType = "java.math.BigInteger")
String VALUE = "VALUE";
@Metadata(label = "producer",
description = "The compiled code of a contract OR the hash of the invoked method signature and encoded parameters.",
javaType = "String")
String DATA = "DATA";
/**
* The block number, or the string "latest" for the last mined block or "pending", "earliest" for not yet mined
* transactions.
*/
@Metadata(label = "producer", javaType = "String")
String FROM_BLOCK = "FROM_BLOCK";
/**
* The block number, or the string "latest" for the last mined block or "pending", "earliest" for not yet mined
* transactions.
*/
@Metadata(label = "producer", javaType = "String")
String TO_BLOCK = "TO_BLOCK";
@Metadata(label = "producer", description = "Topics are order-dependent. Each topic can also be a list of topics. " +
"Specify multiple topics separated by comma.",
javaType = "List<String>")
String TOPICS = "TOPICS";
@Metadata(label = "producer", description = "The priority of a whisper message.", javaType = "java.math.BigInteger")
String PRIORITY = "PRIORITY";
@Metadata(label = "producer", description = "The time to live in seconds of a whisper message.",
javaType = "java.math.BigInteger")
String TTL = "TTL";
@Metadata(label = "producer", description = "A transaction privateFor nodes with public keys in a Quorum network",
javaType = "List<String>")
String PRIVATE_FOR = "PRIVATE_FOR";
@Metadata(label = "producer", description = "A transaction privateFrom",
javaType = "String")
String PRIVATE_FROM = "PRIVATE_FROM";
@Metadata(label = "producer", description = "The error code", javaType = "int")
String ERROR_CODE = "ERROR_CODE";
@Metadata(label = "producer", description = "The error data", javaType = "String")
String ERROR_DATA = "ERROR_DATA";
@Metadata(label = "producer", description = "The error message", javaType = "String")
String ERROR_MESSAGE = "ERROR_MESSAGE";
@Metadata(label = "consumer", description = "The status of the operation", javaType = "String")
String HEADER_STATUS = "status";
@Metadata(label = "consumer", description = "The operation", javaType = "String")
String HEADER_OPERATION = "operation";
}
| Web3jConstants |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/blockmanagement/TestDatanodeDescriptor.java | {
"start": 1424,
"end": 1482
} | class ____ that methods in DatanodeDescriptor
*/
public | tests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/nullness/EqualsMissingNullableTest.java | {
"start": 5365,
"end": 5489
} | class ____ {
public abstract boolean equals(Object o);
}
""")
.doTest();
}
}
| Foo |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/util/Base64Util.java | {
"start": 1102,
"end": 1588
} | class ____ {
private static final Base64.Encoder ENCODER = Base64.getEncoder();
private Base64Util() {}
/**
* This method does not specify an encoding for the {@code str} parameter and should not be used.
* @deprecated since 2.22.0, use {@link java.util.Base64} instead.
*/
@Deprecated
public static String encode(final String str) {
return str != null ? ENCODER.encodeToString(str.getBytes(Charset.defaultCharset())) : null;
}
}
| Base64Util |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/client/HttpServerErrorException.java | {
"start": 4774,
"end": 5412
} | class ____ extends HttpServerErrorException {
private InternalServerError(String statusText, HttpHeaders headers, byte[] body, @Nullable Charset charset) {
super(HttpStatus.INTERNAL_SERVER_ERROR, statusText, headers, body, charset);
}
private InternalServerError(String message, String statusText,
HttpHeaders headers, byte[] body, @Nullable Charset charset) {
super(message, HttpStatus.INTERNAL_SERVER_ERROR, statusText, headers, body, charset);
}
}
/**
* {@link HttpServerErrorException} for status HTTP 501 Not Implemented.
* @since 5.1
*/
@SuppressWarnings("serial")
public static final | InternalServerError |
java | square__retrofit | retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java | {
"start": 2800,
"end": 3336
} | class ____ {
@HTTP(method = "CUSTOM2", path = "/foo", hasBody = true)
Call<ResponseBody> method(@Body RequestBody body) {
return null;
}
}
RequestBody body = RequestBody.create(TEXT_PLAIN, "hi");
Request request = buildRequest(Example.class, body);
assertThat(request.method()).isEqualTo("CUSTOM2");
assertThat(request.url().toString()).isEqualTo("http://example.com/foo");
assertBody(request.body(), "hi");
}
@Test
public void onlyOneEncodingIsAllowedMultipartFirst() {
| Example |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/builditem/HotDeploymentWatchedFileBuildItem.java | {
"start": 2937,
"end": 3982
} | class ____ {
private String location;
private Predicate<String> locationPredicate;
private boolean restartNeeded = true;
public Builder setLocation(String location) {
if (locationPredicate != null) {
throw new IllegalArgumentException("Predicate already set");
}
this.location = location;
return this;
}
public Builder setLocationPredicate(Predicate<String> locationPredicate) {
if (location != null) {
throw new IllegalArgumentException("Location already set");
}
this.locationPredicate = locationPredicate;
return this;
}
public Builder setRestartNeeded(boolean restartNeeded) {
this.restartNeeded = restartNeeded;
return this;
}
public HotDeploymentWatchedFileBuildItem build() {
return new HotDeploymentWatchedFileBuildItem(location, locationPredicate, restartNeeded);
}
}
}
| Builder |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng8299CustomLifecycleTest.java | {
"start": 1001,
"end": 1809
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Verify that invoking the third phase will invoke the first two
*/
@Test
void testPhaseOrdering() throws Exception {
File testDir = extractResources("/mng-8299-custom-lifecycle");
Verifier verifier = newVerifier(new File(testDir, "CustomLifecyclePlugin").getAbsolutePath());
verifier.addCliArgument("install");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier = newVerifier(new File(testDir, "CustomLifecycleProject").getAbsolutePath());
verifier.addCliArgument("phase3");
verifier.execute();
verifier.verifyErrorFreeLog();
verifier.verifyTextInLog("[INFO] Doing Phase 1 stuff. Oh yeah baby.");
}
}
| MavenITmng8299CustomLifecycleTest |
java | apache__maven | impl/maven-impl/src/main/java/org/apache/maven/impl/cache/CacheSelector.java | {
"start": 5070,
"end": 5472
} | class ____ (without package) of a class.
*/
private String getShortClassName(Class<?> clazz) {
String name = clazz.getSimpleName();
return name.isEmpty() ? clazz.getName() : name;
}
@Override
public String toString() {
if (parentRequestType == null) {
return requestType;
}
return parentRequestType + " " + requestType;
}
}
| name |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/parser/promql/PromqlExpressionBuilder.java | {
"start": 2373,
"end": 13446
} | class ____ extends PromqlIdentifierBuilder {
/**
* Prometheus duration limits based on Go time.Duration (int64 nanoseconds).
* Maximum: ~292.27 years (2^63 - 1 nanoseconds = 9,223,372,036 seconds)
* Minimum: ~-292.27 years (-(2^63) nanoseconds = -9,223,372,037 seconds)
*/
private static final long MAX_DURATION_SECONDS = 9223372036L;
private static final long MIN_DURATION_SECONDS = -9223372037L;
private final Literal start, end;
PromqlExpressionBuilder(Literal start, Literal end, int startLine, int startColumn) {
super(startLine, startColumn);
this.start = start;
this.end = end;
}
protected Expression expression(ParseTree ctx) {
return typedParsing(this, ctx, Expression.class);
}
protected List<Expression> expressions(List<? extends ParserRuleContext> contexts) {
return visitList(this, contexts, Expression.class);
}
/**
* Validates that a duration is within Prometheus's acceptable range (~292 years).
* Prometheus uses Go's time.Duration internally, which is an int64 of nanoseconds.
*
* @param source the source location for error reporting
* @param duration the duration to validate
* @throws ParsingException if the duration is out of range
*/
private static void validateDurationRange(Source source, Duration duration) {
long seconds = duration.getSeconds();
if (seconds > MAX_DURATION_SECONDS || seconds < MIN_DURATION_SECONDS) {
throw new ParsingException(source, "Duration out of range");
}
}
@Override
public List<String> visitLabelList(LabelListContext ctx) {
return ctx != null ? visitList(this, ctx.labelName(), String.class) : emptyList();
}
@Override
public String visitLabelName(LabelNameContext ctx) {
if (ctx.identifier() != null) {
return visitIdentifier(ctx.identifier());
}
if (ctx.STRING() != null) {
return string(ctx.STRING());
}
if (ctx.number() != null) {
Literal l = typedParsing(this, ctx.number(), Literal.class);
return String.valueOf(l.value());
}
throw new ParsingException(source(ctx), "Expected label name, got [{}]", source(ctx).text());
}
@Override
public Evaluation visitEvaluation(EvaluationContext ctx) {
if (ctx == null) {
return Evaluation.NONE;
}
Literal offset = Literal.NULL;
boolean negativeOffset = false;
Literal at = Literal.NULL;
AtContext atCtx = ctx.at();
if (atCtx != null) {
Source source = source(atCtx);
if (atCtx.AT_START() != null) {
if (start == null) {
throw new ParsingException(source, "@ start() can only be used if parameter [start] or [time] is provided");
}
at = start;
} else if (atCtx.AT_END() != null) {
if (end == null) {
throw new ParsingException(source, "@ end() can only be used if parameter [end] or [time] is provided");
}
at = end;
} else {
Duration timeValue = visitTimeValue(atCtx.timeValue());
// the value can have a floating point
long seconds = timeValue.getSeconds();
int nanos = timeValue.getNano();
if (atCtx.MINUS() != null) {
if (seconds == Long.MIN_VALUE) {
throw new ParsingException(source, "Value [{}] cannot be negated due to underflow", seconds);
}
seconds = -seconds;
nanos = -nanos;
}
at = Literal.dateTime(source, Instant.ofEpochSecond(seconds, nanos));
}
}
OffsetContext offsetContext = ctx.offset();
if (offsetContext != null) {
offset = visitDuration(offsetContext.duration());
negativeOffset = offsetContext.MINUS() != null;
}
return new Evaluation(offset, negativeOffset, at);
}
@Override
public Literal visitDuration(DurationContext ctx) {
if (ctx == null) {
return Literal.NULL;
}
Object o = visit(ctx.expression());
// unwrap expressions to get the underlying value
o = switch (o) {
case LogicalPlan plan -> {
// Scalar arithmetic has been folded and wrapped in LiteralSelector
if (plan instanceof LiteralSelector literalSelector) {
yield literalSelector.literal().value();
}
throw new ParsingException(source(ctx), "Expected duration or numeric value, got [{}]", plan.getClass().getSimpleName());
}
case Literal l -> l.value();
case Expression e -> {
// Fallback for Expression (shouldn't happen with new logic)
if (e.foldable()) {
yield e.fold(FoldContext.small());
}
// otherwise bail out
throw new ParsingException(source(ctx), "Expected a duration, got [{}]", source(ctx).text());
}
default -> o;
};
Duration d = switch (o) {
case Duration duration -> duration;
// Handle numeric scalars interpreted as seconds
case Number num -> {
long seconds = num.longValue();
if (seconds <= 0) {
throw new ParsingException(source(ctx), "Duration must be positive, got [{}]s", seconds);
}
Duration duration = Duration.ofSeconds(seconds);
// Validate the resulting duration is within acceptable range
validateDurationRange(source(ctx), duration);
yield duration;
}
default -> throw new ParsingException(source(ctx), "Expected a duration, got [{}]", source(ctx).text());
};
return Literal.timeDuration(source(ctx), d);
}
@Override
public Duration visitTimeValue(TimeValueContext ctx) {
if (ctx.number() != null) {
var literal = typedParsing(this, ctx.number(), Literal.class);
Number number = (Number) literal.value();
if (number instanceof Double d) {
double v = d.doubleValue();
Source source = literal.source();
if (Double.isFinite(v) == false) {
throw new ParsingException(source, "Invalid timestamp [{}]", v);
}
// Check if the value exceeds duration range before conversion
if (v > MAX_DURATION_SECONDS || v < MIN_DURATION_SECONDS) {
throw new ParsingException(source, "Duration out of range");
}
// Convert to milliseconds (matching Prometheus behavior)
double millisDouble = v * 1000.0;
if (millisDouble >= Long.MAX_VALUE || millisDouble <= Long.MIN_VALUE) {
throw new ParsingException(source, "Timestamp out of bounds [{}]", v);
}
// Round to nearest millisecond, supporting sub-millisecond input
long millis = Math.round(millisDouble);
return Duration.ofMillis(millis);
}
// Handle integer/long values
long longValue = number.longValue();
if (longValue > MAX_DURATION_SECONDS || longValue < MIN_DURATION_SECONDS) {
throw new ParsingException(literal.source(), "Duration out of range");
}
return Duration.ofSeconds(longValue);
}
String timeString = null;
Source source;
var timeCtx = ctx.TIME_VALUE_WITH_COLON();
if (timeCtx != null) {
// drop leading :
timeString = timeCtx.getText().substring(1).trim();
} else {
timeCtx = ctx.TIME_VALUE();
timeString = timeCtx.getText();
}
source = source(timeCtx);
return parseTimeValue(source, timeString);
}
@Override
public Literal visitDecimalLiteral(DecimalLiteralContext ctx) {
Source source = source(ctx);
String text = ctx.getText();
try {
double value;
String s = text.toLowerCase(Locale.ROOT);
if ("inf".equals(s)) {
value = Double.POSITIVE_INFINITY;
} else if ("nan".equals(s)) {
value = Double.NaN;
} else {
value = Double.parseDouble(text);
}
return Literal.fromDouble(source, value);
} catch (NumberFormatException ne) {
throw new ParsingException(source, "Cannot parse number [{}]", text);
}
}
@Override
public Literal visitIntegerLiteral(IntegerLiteralContext ctx) {
Source source = source(ctx);
String text = ctx.getText();
Number value;
try {
value = StringUtils.parseIntegral(text);
} catch (InvalidArgumentException siae) {
// if it's too large, then quietly try to parse as a float instead
try {
// use DataTypes.DOUBLE for precise type
return Literal.fromDouble(source, StringUtils.parseDouble(text));
} catch (QlIllegalArgumentException ignored) {}
throw new ParsingException(source, siae.getMessage());
}
// use type instead for precise type
return new Literal(source, value, value instanceof Integer ? DataType.INTEGER : DataType.LONG);
}
@Override
public Literal visitHexLiteral(HexLiteralContext ctx) {
Source source = source(ctx);
String text = ctx.getText();
DataType type = DataType.LONG;
Object val;
// remove leading 0x
long value;
try {
value = Long.parseLong(text.substring(2), 16);
} catch (NumberFormatException e) {
throw new ParsingException(source, "Cannot parse hexadecimal expression [{}]", text);
}
// try to downsize to int
if ((int) value == value) {
type = DataType.INTEGER;
val = (int) value;
} else {
val = value;
}
return new Literal(source, val, type);
}
@Override
public Literal visitString(StringContext ctx) {
Source source = source(ctx);
return Literal.keyword(source, string(ctx.STRING()));
}
private static Duration parseTimeValue(Source source, String text) {
Duration duration = PromqlParserUtils.parseDuration(source, text);
if (duration.isZero()) {
throw new ParsingException(source, "Invalid time duration [{}], zero value specified", text);
}
validateDurationRange(source, duration);
return duration;
}
}
| PromqlExpressionBuilder |
java | grpc__grpc-java | interop-testing/src/generated/main/grpc/io/grpc/testing/integration/TestServiceGrpc.java | {
"start": 41340,
"end": 47467
} | class ____<Req, Resp> implements
io.grpc.stub.ServerCalls.UnaryMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ServerStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.ClientStreamingMethod<Req, Resp>,
io.grpc.stub.ServerCalls.BidiStreamingMethod<Req, Resp> {
private final AsyncService serviceImpl;
private final int methodId;
MethodHandlers(AsyncService serviceImpl, int methodId) {
this.serviceImpl = serviceImpl;
this.methodId = methodId;
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public void invoke(Req request, io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_EMPTY_CALL:
serviceImpl.emptyCall((io.grpc.testing.integration.EmptyProtos.Empty) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty>) responseObserver);
break;
case METHODID_UNARY_CALL:
serviceImpl.unaryCall((io.grpc.testing.integration.Messages.SimpleRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.SimpleResponse>) responseObserver);
break;
case METHODID_CACHEABLE_UNARY_CALL:
serviceImpl.cacheableUnaryCall((io.grpc.testing.integration.Messages.SimpleRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.SimpleResponse>) responseObserver);
break;
case METHODID_STREAMING_OUTPUT_CALL:
serviceImpl.streamingOutputCall((io.grpc.testing.integration.Messages.StreamingOutputCallRequest) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse>) responseObserver);
break;
case METHODID_UNIMPLEMENTED_CALL:
serviceImpl.unimplementedCall((io.grpc.testing.integration.EmptyProtos.Empty) request,
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.EmptyProtos.Empty>) responseObserver);
break;
default:
throw new AssertionError();
}
}
@java.lang.Override
@java.lang.SuppressWarnings("unchecked")
public io.grpc.stub.StreamObserver<Req> invoke(
io.grpc.stub.StreamObserver<Resp> responseObserver) {
switch (methodId) {
case METHODID_STREAMING_INPUT_CALL:
return (io.grpc.stub.StreamObserver<Req>) serviceImpl.streamingInputCall(
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingInputCallResponse>) responseObserver);
case METHODID_FULL_DUPLEX_CALL:
return (io.grpc.stub.StreamObserver<Req>) serviceImpl.fullDuplexCall(
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse>) responseObserver);
case METHODID_HALF_DUPLEX_CALL:
return (io.grpc.stub.StreamObserver<Req>) serviceImpl.halfDuplexCall(
(io.grpc.stub.StreamObserver<io.grpc.testing.integration.Messages.StreamingOutputCallResponse>) responseObserver);
default:
throw new AssertionError();
}
}
}
public static final io.grpc.ServerServiceDefinition bindService(AsyncService service) {
return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor())
.addMethod(
getEmptyCallMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty>(
service, METHODID_EMPTY_CALL)))
.addMethod(
getUnaryCallMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.SimpleRequest,
io.grpc.testing.integration.Messages.SimpleResponse>(
service, METHODID_UNARY_CALL)))
.addMethod(
getCacheableUnaryCallMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.SimpleRequest,
io.grpc.testing.integration.Messages.SimpleResponse>(
service, METHODID_CACHEABLE_UNARY_CALL)))
.addMethod(
getStreamingOutputCallMethod(),
io.grpc.stub.ServerCalls.asyncServerStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingOutputCallRequest,
io.grpc.testing.integration.Messages.StreamingOutputCallResponse>(
service, METHODID_STREAMING_OUTPUT_CALL)))
.addMethod(
getStreamingInputCallMethod(),
io.grpc.stub.ServerCalls.asyncClientStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingInputCallRequest,
io.grpc.testing.integration.Messages.StreamingInputCallResponse>(
service, METHODID_STREAMING_INPUT_CALL)))
.addMethod(
getFullDuplexCallMethod(),
io.grpc.stub.ServerCalls.asyncBidiStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingOutputCallRequest,
io.grpc.testing.integration.Messages.StreamingOutputCallResponse>(
service, METHODID_FULL_DUPLEX_CALL)))
.addMethod(
getHalfDuplexCallMethod(),
io.grpc.stub.ServerCalls.asyncBidiStreamingCall(
new MethodHandlers<
io.grpc.testing.integration.Messages.StreamingOutputCallRequest,
io.grpc.testing.integration.Messages.StreamingOutputCallResponse>(
service, METHODID_HALF_DUPLEX_CALL)))
.addMethod(
getUnimplementedCallMethod(),
io.grpc.stub.ServerCalls.asyncUnaryCall(
new MethodHandlers<
io.grpc.testing.integration.EmptyProtos.Empty,
io.grpc.testing.integration.EmptyProtos.Empty>(
service, METHODID_UNIMPLEMENTED_CALL)))
.build();
}
private static abstract | MethodHandlers |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/CancelableCompletionStageTest.java | {
"start": 2366,
"end": 3013
} | class ____ {
public static final AtomicInteger COUNT = new AtomicInteger(0);
@GET
@Produces(MediaType.TEXT_PLAIN)
public CompletionStage<String> hello() {
COUNT.incrementAndGet();
return CompletableFuture.supplyAsync(
new Supplier<>() {
@Override
public String get() {
COUNT.incrementAndGet();
return "Hello, world";
}
},
CompletableFuture.delayedExecutor(5, TimeUnit.SECONDS));
}
}
}
| Resource |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/mapper/ShortOffsetDocValuesLoaderTests.java | {
"start": 517,
"end": 771
} | class ____ extends OffsetDocValuesLoaderTestCase {
@Override
protected String getFieldTypeName() {
return "short";
}
@Override
protected Object randomValue() {
return randomShort();
}
}
| ShortOffsetDocValuesLoaderTests |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/testng/transaction/ejb/RollbackForRequiresNewEjbTxDaoTestNGTests.java | {
"start": 1723,
"end": 1859
} | class ____ extends CommitForRequiresNewEjbTxDaoTestNGTests {
/* test methods in superclass */
}
| RollbackForRequiresNewEjbTxDaoTestNGTests |
java | apache__logging-log4j2 | log4j-api-test/src/main/java/org/apache/logging/log4j/test/junit/TypeBasedParameterResolver.java | {
"start": 1138,
"end": 1886
} | class ____<T> implements ParameterResolver {
private final Type supportedParameterType;
public TypeBasedParameterResolver(final Type supportedParameterType) {
this.supportedParameterType = supportedParameterType;
}
@Override
public boolean supportsParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext)
throws ParameterResolutionException {
return this.supportedParameterType.equals(
parameterContext.getParameter().getParameterizedType());
}
@Override
public abstract T resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext)
throws ParameterResolutionException;
}
| TypeBasedParameterResolver |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ImmutableSetForContainsTest.java | {
"start": 11265,
"end": 12081
} | class ____ {
private static final ImmutableList<String> MY_LIST_1 = ImmutableList.of("hello");
private static final ImmutableList<String> MY_LIST_2 = ImmutableList.of("hello");
private void myFunc() {
ImmutableMap<String, List<String>> myMap =
ImmutableMap.<String, List<String>>builder().put("a", MY_LIST_1).build();
boolean myBool = ImmutableList.of().equals(MY_LIST_2);
}
}
""")
.expectUnchanged()
.doTest();
}
@Test
public void immutableList_uniqueElements_inLoopExprAndStatement_doesNothing() {
refactoringHelper
.addInputLines(
"Test.java",
"""
import com.google.common.collect.ImmutableList;
| Test |
java | spring-projects__spring-security | access/src/main/java/org/springframework/security/access/vote/RoleVoter.java | {
"start": 2615,
"end": 4289
} | class ____ implements AccessDecisionVoter<Object> {
private String rolePrefix = "ROLE_";
public String getRolePrefix() {
return this.rolePrefix;
}
/**
* Allows the default role prefix of <code>ROLE_</code> to be overridden. May be set
* to an empty value, although this is usually not desirable.
* @param rolePrefix the new prefix
*/
public void setRolePrefix(String rolePrefix) {
this.rolePrefix = rolePrefix;
}
@Override
public boolean supports(ConfigAttribute attribute) {
return (attribute.getAttribute() != null) && attribute.getAttribute().startsWith(getRolePrefix());
}
/**
* This implementation supports any type of class, because it does not query the
* presented secure object.
* @param clazz the secure object
* @return always <code>true</code>
*/
@Override
public boolean supports(Class<?> clazz) {
return true;
}
@Override
public int vote(Authentication authentication, Object object, Collection<ConfigAttribute> attributes) {
if (authentication == null) {
return ACCESS_DENIED;
}
int result = ACCESS_ABSTAIN;
Collection<? extends GrantedAuthority> authorities = extractAuthorities(authentication);
for (ConfigAttribute attribute : attributes) {
if (this.supports(attribute)) {
result = ACCESS_DENIED;
// Attempt to find a matching granted authority
for (GrantedAuthority authority : authorities) {
if (attribute.getAttribute().equals(authority.getAuthority())) {
return ACCESS_GRANTED;
}
}
}
}
return result;
}
Collection<? extends GrantedAuthority> extractAuthorities(Authentication authentication) {
return authentication.getAuthorities();
}
}
| RoleVoter |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/argumentselectiondefects/ArgumentSelectionDefectCheckerTest.java | {
"start": 11262,
"end": 12144
} | class ____ extends BugChecker
implements MethodInvocationTreeMatcher {
@Override
public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) {
return buildDescription(tree)
.setMessage(
String.valueOf(
ASTHelpers.getSymbol(tree).getParameters().stream()
.noneMatch(p -> p.getSimpleName().toString().matches("arg[0-9]"))))
.build();
}
}
@Test
public void parameterNamesAvailable_returnsTree_onMethodNotInCompilationUnit() {
CompilationTestHelper.newInstance(ParameterNamesAvailableChecker.class, getClass())
.addSourceLines(
"Test.java",
String.format("import %s;", CompilationTestHelper.class.getName()),
String.format("import %s;", BugChecker.class.getName()),
" | ParameterNamesAvailableChecker |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ObjectEqualsForPrimitivesTest.java | {
"start": 4626,
"end": 5229
} | class ____ {
private static boolean testBooleans(boolean a, boolean b) {
return !(a == b);
}
private static boolean testInts(int a, int b) {
return !(a == b);
}
private static boolean testLongs(long a, long b) {
return !(a == b);
}
}
""")
.doTest();
}
@Test
public void intAndLong() {
refactoringHelper
.addInputLines(
"Test.java",
"""
import java.util.Objects;
public | Test |
java | apache__kafka | streams/integration-tests/src/test/java/org/apache/kafka/streams/integration/SmokeTestDriverIntegrationTest.java | {
"start": 2351,
"end": 3237
} | class ____ {
private static EmbeddedKafkaCluster cluster = null;
public TestInfo testInfo;
private ArrayList<SmokeTestClient> clients = new ArrayList<>();
@BeforeAll
public static void startCluster() throws IOException {
cluster = new EmbeddedKafkaCluster(3);
cluster.start();
}
@AfterAll
public static void closeCluster() {
cluster.stop();
cluster = null;
}
@BeforeEach
public void setUp(final TestInfo testInfo) {
this.testInfo = testInfo;
}
@AfterEach
public void shutDown(final TestInfo testInfo) {
// Clean up clients in case the test failed or timed out
for (final SmokeTestClient client : clients) {
if (!client.closed() && !client.error()) {
client.close();
}
}
}
private static | SmokeTestDriverIntegrationTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/logging/LogConfigurator.java | {
"start": 6663,
"end": 18435
} | class
____ logger = LogManager.getLogger("StatusLogger");
var listener = new StatusConsoleListener(Level.WARN) {
@Override
public void log(StatusData data) {
logger.log(data.getLevel(), data.getMessage(), data.getThrowable());
super.log(data);
}
};
StatusLogger.getLogger().registerListener(listener);
}
public static void configureESLogging() {
LoggerFactory.setInstance(new LoggerFactoryImpl());
}
/**
* Load logging plugins so we can have {@code node_name} in the pattern.
*/
public static void loadLog4jPlugins() {
PluginManager.addPackage(LogConfigurator.class.getPackage().getName());
}
/**
* Sets the node name. This is called before logging is configured if the
* node name is set in elasticsearch.yml. Otherwise it is called as soon
* as the node id is available.
*/
public static void setNodeName(String nodeName) {
NodeNamePatternConverter.setNodeName(nodeName);
}
// Some classes within log4j have static initializers that require security manager permissions.
// Here we aggressively initialize those classes during logging configuration so that
// actual logging calls at runtime do not trigger that initialization.
private static void initializeStatics() {
try {
MethodHandles.publicLookup().ensureInitialized(Unbox.class);
} catch (IllegalAccessException impossible) {
throw new AssertionError(impossible);
}
}
private static void checkErrorListener() {
assert errorListenerIsRegistered() : "expected error listener to be registered";
if (error.get()) {
throw new IllegalStateException("status logger logged an error before logging was configured");
}
}
private static boolean errorListenerIsRegistered() {
return StreamSupport.stream(StatusLogger.getLogger().getListeners().spliterator(), false).anyMatch(l -> l == ERROR_LISTENER);
}
private static void configure(final Settings settings, final Path configsPath, final Path logsPath, boolean useConsole)
throws IOException {
Objects.requireNonNull(settings);
Objects.requireNonNull(configsPath);
Objects.requireNonNull(logsPath);
loadLog4jPlugins();
setLogConfigurationSystemProperty(logsPath, settings);
// we initialize the status logger immediately otherwise Log4j will complain when we try to get the context
configureStatusLogger();
final LoggerContext context = (LoggerContext) LogManager.getContext(false);
final Set<String> locationsWithDeprecatedPatterns = Collections.synchronizedSet(new HashSet<>());
final List<AbstractConfiguration> configurations = new ArrayList<>();
/*
* Subclass the properties configurator to hack the new pattern in
* place so users don't have to change log4j2.properties in
* a minor release. In 7.0 we'll remove this and force users to
* change log4j2.properties. If they don't customize log4j2.properties
* then they won't have to do anything anyway.
*
* Everything in this subclass that isn't marked as a hack is copied
* from log4j2's source.
*/
final PropertiesConfigurationFactory factory = new PropertiesConfigurationFactory() {
@Override
public PropertiesConfiguration getConfiguration(final LoggerContext loggerContext, final ConfigurationSource source) {
final Properties properties = new Properties();
try (InputStream configStream = source.getInputStream()) {
properties.load(configStream);
} catch (final IOException ioe) {
throw new ConfigurationException("Unable to load " + source.toString(), ioe);
}
// Hack the new pattern into place
for (String name : properties.stringPropertyNames()) {
if (false == name.endsWith(".pattern")) continue;
// Null is weird here but we can't do anything with it so ignore it
String value = properties.getProperty(name);
if (value == null) continue;
// Tests don't need to be changed
if (value.contains("%test_thread_info")) continue;
/*
* Patterns without a marker are sufficiently customized
* that we don't have an opinion about them.
*/
if (false == value.contains("%marker")) continue;
if (false == value.contains("%node_name")) {
locationsWithDeprecatedPatterns.add(source.getLocation());
properties.setProperty(name, value.replace("%marker", "[%node_name]%marker "));
}
}
// end hack
return new PropertiesConfigurationBuilder().setConfigurationSource(source)
.setRootProperties(properties)
.setLoggerContext(loggerContext)
.build();
}
};
final Set<FileVisitOption> options = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
Files.walkFileTree(configsPath, options, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
if (file.getFileName().toString().equals("log4j2.properties")) {
configurations.add((PropertiesConfiguration) factory.getConfiguration(context, file.toString(), file.toUri()));
}
return FileVisitResult.CONTINUE;
}
});
assert configurations.isEmpty() == false;
configurations.add(createStaticConfiguration(context));
context.start(new CompositeConfiguration(configurations));
configureLoggerLevels(settings);
final String deprecatedLocationsString = String.join("\n ", locationsWithDeprecatedPatterns);
if (deprecatedLocationsString.length() > 0) {
LogManager.getLogger(LogConfigurator.class)
.warn(
"Some logging configurations have %marker but don't have %node_name. "
+ "We will automatically add %node_name to the pattern to ease the migration for users who customize "
+ "log4j2.properties but will stop this behavior in 7.0. You should manually replace `%node_name` with "
+ "`[%node_name]%marker ` in these locations:\n {}",
deprecatedLocationsString
);
}
JULBridge.install();
// Redirect stdout/stderr to log4j. While we ensure Elasticsearch code does not write to those streams,
// third party libraries may do that. Note that we do NOT close the streams because other code may have
// grabbed a handle to the streams and intend to write to it, eg log4j for writing to the console
System.setOut(new PrintStream(new LoggingOutputStream(LogManager.getLogger("stdout"), Level.INFO), false, StandardCharsets.UTF_8));
System.setErr(new PrintStream(new LoggingOutputStream(LogManager.getLogger("stderr"), Level.WARN), false, StandardCharsets.UTF_8));
final Logger rootLogger = LogManager.getRootLogger();
Appender appender = Loggers.findAppender(rootLogger, ConsoleAppender.class);
if (appender != null) {
if (useConsole) {
consoleAppender = appender;
} else {
Loggers.removeAppender(rootLogger, appender);
}
}
}
/**
* Creates a log4j configuration that is not changeable by users.
*/
private static AbstractConfiguration createStaticConfiguration(LoggerContext context) {
var builder = new DefaultConfigurationBuilder<>();
builder.setConfigurationSource(ConfigurationSource.NULL_SOURCE);
builder.setLoggerContext(context);
// adding filters for confusing Lucene messages
addRegexFilter(builder, "org.apache.lucene.store.MemorySegmentIndexInputProvider", "Using MemorySegmentIndexInput.*");
addRegexFilter(builder, "org.apache.lucene.util.VectorUtilProvider", ".* incubator module is not readable.*");
return builder.build();
}
private static void addRegexFilter(DefaultConfigurationBuilder<BuiltConfiguration> builder, String loggerName, String pattern) {
var filterBuilder = builder.newFilter("RegexFilter", Filter.Result.DENY, Filter.Result.NEUTRAL);
filterBuilder.addAttribute("regex", pattern);
var loggerBuilder = builder.newLogger(loggerName);
loggerBuilder.add(filterBuilder);
builder.add(loggerBuilder);
}
/**
* Removes the appender for the console, if one exists.
*/
public static Appender removeConsoleAppender() {
Appender appender = consoleAppender;
if (appender != null) {
Loggers.removeAppender(LogManager.getRootLogger(), appender);
consoleAppender = null;
}
return appender;
}
private static void configureStatusLogger() {
final ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel(Level.ERROR);
Configurator.initialize(builder.build());
}
/**
* Configures the logging levels for loggers configured in the specified settings.
*
* @param settings the settings from which logger levels will be extracted
*/
private static void configureLoggerLevels(final Settings settings) {
if (Loggers.LOG_DEFAULT_LEVEL_SETTING.exists(settings)) {
final Level level = Loggers.LOG_DEFAULT_LEVEL_SETTING.get(settings);
Loggers.setLevel(LogManager.getRootLogger(), level);
}
Loggers.LOG_LEVEL_SETTING.getAllConcreteSettings(settings)
// do not set a log level for a logger named level (from the default log setting)
.filter(s -> s.getKey().equals(Loggers.LOG_DEFAULT_LEVEL_SETTING.getKey()) == false)
.forEach(s -> {
final Level level = s.get(settings);
Loggers.setLevel(LogManager.getLogger(s.getKey().substring("logger.".length())), level);
});
}
/**
* Set system properties that can be used in configuration files to specify paths and file patterns for log files. We expose three
* properties here:
* <ul>
* <li>
* {@code es.logs.base_path} the base path containing the log files
* </li>
* <li>
* {@code es.logs.cluster_name} the cluster name, used as the prefix of log filenames in the default configuration
* </li>
* <li>
* {@code es.logs.node_name} the node name, can be used as part of log filenames
* </li>
* </ul>
*
* @param logsPath the path to the log files
* @param settings the settings to extract the cluster and node names
*/
@SuppressForbidden(reason = "sets system property for logging configuration")
private static void setLogConfigurationSystemProperty(final Path logsPath, final Settings settings) {
System.setProperty("es.logs.base_path", logsPath.toString());
System.setProperty("es.logs.cluster_name", ClusterName.CLUSTER_NAME_SETTING.get(settings).value());
System.setProperty("es.logs.node_name", Node.NODE_NAME_SETTING.get(settings));
}
}
| var |
java | quarkusio__quarkus | core/deployment/src/test/java/io/quarkus/deployment/runnerjar/DependencyInProfileActiveByDefaultEffectiveModelBuilderTest.java | {
"start": 489,
"end": 5420
} | class ____ extends BootstrapFromOriginalJarTestBase {
@Override
protected boolean createWorkspace() {
return true;
}
@Override
protected void setSystemProperties() {
setSystemProperty("quarkus.bootstrap.effective-model-builder", "true");
}
@Override
protected TsArtifact composeApplication() {
final TsQuarkusExt extA_100 = new TsQuarkusExt("ext-a", "1.0.0");
addToExpectedLib(extA_100.getRuntime());
final TsQuarkusExt extB_100 = new TsQuarkusExt("ext-b", "1.0.0");
install(extB_100);
final TsArtifact extB_100_rt = extB_100.getRuntime();
addToExpectedLib(extB_100_rt);
final TsArtifact commonLibraryJar = TsArtifact.jar("common-library");
addToExpectedLib(commonLibraryJar);
addWorkspaceModule(commonLibraryJar);
final TsArtifact module1Jar = TsArtifact.jar("module-one");
module1Jar.addDependency(commonLibraryJar);
addToExpectedLib(module1Jar);
final TsArtifact module2Jar = TsArtifact.jar("module-two");
module2Jar.addDependency(commonLibraryJar);
addToExpectedLib(module2Jar);
install(module2Jar);
addWorkspaceModuleToProfile(module2Jar, "extra");
final TsArtifact appJar = TsArtifact.jar("app")
.addManagedDependency(platformDescriptor())
.addManagedDependency(platformProperties())
.addDependency(extA_100)
.addDependency(module1Jar);
final Profile profile = new Profile();
profile.setId("extra");
Activation activation = new Activation();
activation.setActiveByDefault(true);
profile.setActivation(activation);
Dependency dep = new Dependency();
dep.setGroupId(extB_100_rt.getGroupId());
dep.setArtifactId(extB_100_rt.getArtifactId());
dep.setVersion(extB_100_rt.getVersion());
profile.addDependency(dep);
dep = new Dependency();
dep.setGroupId(module2Jar.getGroupId());
dep.setArtifactId(module2Jar.getArtifactId());
dep.setVersion(module2Jar.getVersion());
profile.addDependency(dep);
appJar.addProfile(profile);
createWorkspace();
return appJar;
}
@Override
protected void assertAppModel(ApplicationModel model) {
final Map<String, ResolvedDependency> deps = new HashMap<>();
model.getDependencies().forEach(d -> deps.put(d.getArtifactId(), d));
assertThat(deps).hasSize(7);
ResolvedDependency d = deps.get("module-one");
assertThat(d).isNotNull();
assertThat(d.isRuntimeCp()).isTrue();
assertThat(d.isDeploymentCp()).isTrue();
assertThat(d.isWorkspaceModule()).isTrue();
assertThat(d.isReloadable()).isTrue();
assertThat(d.isRuntimeExtensionArtifact()).isFalse();
d = deps.get("module-two");
assertThat(d).isNotNull();
assertThat(d.isRuntimeCp()).isTrue();
assertThat(d.isDeploymentCp()).isTrue();
assertThat(d.isWorkspaceModule()).isTrue();
assertThat(d.isReloadable()).isTrue();
assertThat(d.isRuntimeExtensionArtifact()).isFalse();
d = deps.get("common-library");
assertThat(d).isNotNull();
assertThat(d.isRuntimeCp()).isTrue();
assertThat(d.isDeploymentCp()).isTrue();
assertThat(d.isWorkspaceModule()).isTrue();
assertThat(d.isReloadable()).isTrue();
assertThat(d.isRuntimeExtensionArtifact()).isFalse();
d = deps.get("ext-a");
assertThat(d).isNotNull();
assertThat(d.isRuntimeExtensionArtifact()).isTrue();
assertThat(d.isRuntimeCp()).isTrue();
assertThat(d.isDeploymentCp()).isTrue();
assertThat(d.isWorkspaceModule()).isTrue();
assertThat(d.isReloadable()).isFalse();
d = deps.get("ext-b");
assertThat(d).isNotNull();
assertThat(d.isRuntimeExtensionArtifact()).isTrue();
assertThat(d.isRuntimeCp()).isTrue();
assertThat(d.isDeploymentCp()).isTrue();
assertThat(d.isWorkspaceModule()).isFalse();
assertThat(d.isReloadable()).isFalse();
d = deps.get("ext-a-deployment");
assertThat(d).isNotNull();
assertThat(d.isRuntimeExtensionArtifact()).isFalse();
assertThat(d.isRuntimeCp()).isFalse();
assertThat(d.isDeploymentCp()).isTrue();
assertThat(d.isWorkspaceModule()).isFalse();
assertThat(d.isReloadable()).isFalse();
d = deps.get("ext-b-deployment");
assertThat(d).isNotNull();
assertThat(d.isRuntimeExtensionArtifact()).isFalse();
assertThat(d.isRuntimeCp()).isFalse();
assertThat(d.isDeploymentCp()).isTrue();
assertThat(d.isWorkspaceModule()).isFalse();
assertThat(d.isReloadable()).isFalse();
}
}
| DependencyInProfileActiveByDefaultEffectiveModelBuilderTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/filter/wall/mysql/MySqlWallTest17.java | {
"start": 837,
"end": 1074
} | class ____ extends TestCase {
public void test_true() throws Exception {
assertTrue(WallUtils.isValidateMySql(//
"DELETE FROM as_home_notification WHERE uid>? AND new=? AND dateline<?-?"));
}
}
| MySqlWallTest17 |
java | apache__kafka | connect/runtime/src/test/java/org/apache/kafka/connect/runtime/rest/resources/ConnectorPluginsResourceTest.java | {
"start": 24536,
"end": 26226
} | class ____ extends SourceConnector {
private static final String TEST_STRING_CONFIG = "test.string.config";
private static final String TEST_INT_CONFIG = "test.int.config";
private static final String TEST_STRING_CONFIG_DEFAULT = "test.string.config.default";
private static final String TEST_LIST_CONFIG = "test.list.config";
private static final String GROUP = "Test";
private static final ConfigDef CONFIG_DEF = new ConfigDef()
.define(TEST_STRING_CONFIG, Type.STRING, Importance.HIGH, "Test configuration for string type.")
.define(TEST_INT_CONFIG, Type.INT, Importance.MEDIUM, "Test configuration for integer type.", GROUP, 1, Width.MEDIUM, TEST_INT_CONFIG, new IntegerRecommender())
.define(TEST_STRING_CONFIG_DEFAULT, Type.STRING, "", Importance.LOW, "Test configuration with default value.")
.define(TEST_LIST_CONFIG, Type.LIST, Importance.HIGH, "Test configuration for list type.", GROUP, 2, Width.LONG, TEST_LIST_CONFIG, new ListRecommender());
@Override
public String version() {
return AppInfoParser.getVersion();
}
@Override
public void start(Map<String, String> props) {
}
@Override
public Class<? extends Task> taskClass() {
return null;
}
@Override
public List<Map<String, String>> taskConfigs(int maxTasks) {
return null;
}
@Override
public void stop() {
}
@Override
public ConfigDef config() {
return CONFIG_DEF;
}
}
private static | ConnectorPluginsResourceTestConnector |
java | grpc__grpc-java | netty/src/main/java/io/grpc/netty/NettyServerProvider.java | {
"start": 832,
"end": 1568
} | class ____ extends ServerProvider {
@Override
protected boolean isAvailable() {
return true;
}
@Override
protected int priority() {
return 5;
}
@Override
protected NettyServerBuilder builderForPort(int port) {
return NettyServerBuilder.forPort(port);
}
@Override
protected NewServerBuilderResult newServerBuilderForPort(int port, ServerCredentials creds) {
ProtocolNegotiators.FromServerCredentialsResult result = ProtocolNegotiators.from(creds);
if (result.error != null) {
return NewServerBuilderResult.error(result.error);
}
return NewServerBuilderResult.serverBuilder(
new NettyServerBuilder(new InetSocketAddress(port), result.negotiator));
}
}
| NettyServerProvider |
java | quarkusio__quarkus | extensions/grpc/deployment/src/test/java/io/quarkus/grpc/client/tls/TlsWithJKSTrustStoreWithHttpServerTest.java | {
"start": 866,
"end": 2445
} | class ____ {
private static final String configuration = """
quarkus.grpc.clients.hello.plain-text=false
quarkus.grpc.clients.hello.tls.trust-certificate-jks.path=target/certs/grpc-client-truststore.jks
quarkus.grpc.clients.hello.tls.trust-certificate-jks.password=password
quarkus.grpc.clients.hello.tls.enabled=true
quarkus.grpc.clients.hello.use-quarkus-grpc-client=true
quarkus.grpc.server.use-separate-server=false
quarkus.grpc.server.plain-text=false # Force the client to use TLS for the tests
quarkus.http.ssl.certificate.key-store-file=target/certs/grpc-keystore.jks
quarkus.http.ssl.certificate.key-store-password=password
quarkus.http.insecure-requests=disabled
""";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addPackage(HelloWorldTlsEndpoint.class.getPackage())
.addPackage(io.grpc.examples.helloworld.GreeterGrpc.class.getPackage())
.add(new StringAsset(configuration), "application.properties"));
@GrpcClient("hello")
GreeterGrpc.GreeterBlockingStub blockingHelloService;
@Test
void testClientTlsConfiguration() {
HelloReply reply = blockingHelloService.sayHello(HelloRequest.newBuilder().setName("neo").build());
assertThat(reply.getMessage()).isEqualTo("Hello neo");
}
}
| TlsWithJKSTrustStoreWithHttpServerTest |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_3561/Issue3561Mapper.java | {
"start": 394,
"end": 796
} | interface ____ {
Issue3561Mapper INSTANCE = Mappers.getMapper( Issue3561Mapper.class );
@Mapping(target = "value", conditionQualifiedByName = "shouldMapValue")
Target map(Source source, @Context boolean shouldMapValue);
@Condition
@Named("shouldMapValue")
default boolean shouldMapValue(@Context boolean shouldMapValue) {
return shouldMapValue;
}
| Issue3561Mapper |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/scheduling/annotation/EnableScheduling.java | {
"start": 1447,
"end": 1752
} | class ____ {
*
* // various @Bean definitions
* }</pre>
*
* <p>This enables detection of {@link Scheduled @Scheduled} annotations on any
* Spring-managed bean in the container. For example, given a class {@code MyTask}:
*
* <pre class="code">
* package com.myco.tasks;
*
* public | AppConfig |
java | apache__logging-log4j2 | log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/ReflectionBenchmark.java | {
"start": 1499,
"end": 1750
} | class ____ {
private final Random r = new Random();
int random;
@Setup(Level.Iteration)
public void setup() {
random = r.nextInt();
}
}
@State(Scope.Benchmark)
public static | RandomInteger |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/references/FooMapper.java | {
"start": 273,
"end": 327
} | interface ____ {
Bar fooToBar(Foo source);
}
| FooMapper |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/OAuth2AuthorizationConsent.java | {
"start": 5691,
"end": 8038
} | class ____ {
private final String registeredClientId;
private final String principalName;
private final Set<GrantedAuthority> authorities = new HashSet<>();
private Builder(String registeredClientId, String principalName) {
this(registeredClientId, principalName, Collections.emptySet());
}
private Builder(String registeredClientId, String principalName, Set<GrantedAuthority> authorities) {
this.registeredClientId = registeredClientId;
this.principalName = principalName;
if (!CollectionUtils.isEmpty(authorities)) {
this.authorities.addAll(authorities);
}
}
/**
* Adds a scope to the collection of {@code authorities} in the resulting
* {@link OAuth2AuthorizationConsent}, wrapping it in a
* {@link SimpleGrantedAuthority}, prefixed by {@code SCOPE_}. For example, a
* {@code message.write} scope would be stored as {@code SCOPE_message.write}.
* @param scope the scope
* @return the {@code Builder} for further configuration
*/
public Builder scope(String scope) {
authority(new SimpleGrantedAuthority(AUTHORITIES_SCOPE_PREFIX + scope));
return this;
}
/**
* Adds a {@link GrantedAuthority} to the collection of {@code authorities} in the
* resulting {@link OAuth2AuthorizationConsent}.
* @param authority the {@link GrantedAuthority}
* @return the {@code Builder} for further configuration
*/
public Builder authority(GrantedAuthority authority) {
this.authorities.add(authority);
return this;
}
/**
* A {@code Consumer} of the {@code authorities}, allowing the ability to add,
* replace or remove.
* @param authoritiesConsumer a {@code Consumer} of the {@code authorities}
* @return the {@code Builder} for further configuration
*/
public Builder authorities(Consumer<Set<GrantedAuthority>> authoritiesConsumer) {
authoritiesConsumer.accept(this.authorities);
return this;
}
/**
* Validate the authorities and build the {@link OAuth2AuthorizationConsent}.
* There must be at least one {@link GrantedAuthority}.
* @return the {@link OAuth2AuthorizationConsent}
*/
public OAuth2AuthorizationConsent build() {
Assert.notEmpty(this.authorities, "authorities cannot be empty");
return new OAuth2AuthorizationConsent(this.registeredClientId, this.principalName, this.authorities);
}
}
}
| Builder |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/datanode/SimulatedFSDataset.java | {
"start": 39629,
"end": 39749
} | class ____ an output stream that merely throws its data away, but records its
* length.
*/
static private | implements |
java | netty__netty | handler/src/test/java/io/netty/handler/ssl/util/CachedSelfSignedCertificate.java | {
"start": 1410,
"end": 1727
} | class ____ {
public static final Object INSTANCE = createInstance();
private static Object createInstance() {
try {
return new SelfSignedCertificate();
} catch (CertificateException e) {
return e;
}
}
}
}
| LazyDefaultInstance |
java | quarkusio__quarkus | independent-projects/bootstrap/core/src/main/java/io/quarkus/bootstrap/classloading/ClassPathElement.java | {
"start": 2339,
"end": 4625
} | class ____ element contains resources that can be reloaded in dev mode.
*/
boolean containsReloadableResources();
/**
*
* @return The protection domain that should be used to define classes from this element
*/
ProtectionDomain getProtectionDomain();
ManifestAttributes getManifestAttributes();
/**
* Checks whether this is a runtime classpath element
*
* @return true in case this is a runtime classpath element, otherwise - false
*/
boolean isRuntime();
/**
* Creates an element from a file system path
*/
static ClassPathElement fromPath(Path path, boolean runtime) {
return new PathTreeClassPathElement(PathTree.ofDirectoryOrArchive(path),
runtime);
}
static ClassPathElement fromDependency(ResolvedDependency dep) {
return fromDependency(dep.getContentTree(), dep);
}
static ClassPathElement fromDependency(PathTree contentTree, ResolvedDependency dep) {
return new PathTreeClassPathElement(contentTree, dep.isRuntimeCp(), dep);
}
ClassPathElement EMPTY = new ClassPathElement() {
@Override
public Path getRoot() {
return null;
}
@Override
public boolean isRuntime() {
return false;
}
@Override
public <T> T apply(Function<OpenPathTree, T> func) {
return func.apply(EmptyPathTree.getInstance());
}
@Override
public ClassPathResource getResource(String name) {
return null;
}
@Override
public Set<String> getProvidedResources() {
return Set.of();
}
@Override
public boolean containsReloadableResources() {
return false;
}
@Override
public ProtectionDomain getProtectionDomain() {
return null;
}
@Override
public ManifestAttributes getManifestAttributes() {
return null;
}
@Override
public void close() {
}
};
default List<ClassPathResource> getResources(String name) {
ClassPathResource resource = getResource(name);
return resource == null ? List.of() : List.of(resource);
}
}
| path |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/join/deltajoin/StreamingDeltaJoinOperatorTest.java | {
"start": 77591,
"end": 80860
} | class ____ extends AbstractTestSpec {
private static final LogLogTableJoinTestSpec WITHOUT_FILTER_ON_TABLE =
new LogLogTableJoinTestSpec(false);
private static final LogLogTableJoinTestSpec WITH_FILTER_ON_TABLE =
new LogLogTableJoinTestSpec(true);
private final boolean filterOnTable;
public LogLogTableJoinTestSpec(boolean filterOnTable) {
this.filterOnTable = filterOnTable;
}
@Override
RowType getLeftInputRowType() {
return RowType.of(
new LogicalType[] {new IntType(), new BooleanType(), VarCharType.STRING_TYPE},
new String[] {"left_value", "left_jk1", "left_jk2_index"});
}
@Override
RowType getRightInputRowType() {
return RowType.of(
new LogicalType[] {VarCharType.STRING_TYPE, new IntType(), new BooleanType()},
new String[] {"right_jk2", "right_value", "right_jk1_index"});
}
@Override
Optional<int[]> getLeftUpsertKey() {
return Optional.empty();
}
@Override
Optional<int[]> getRightUpsertKey() {
return Optional.empty();
}
@Override
int[] getLeftJoinKeyIndices() {
return new int[] {1, 2};
}
@Override
int[] getRightJoinKeyIndices() {
return new int[] {2, 0};
}
@Override
Optional<Function<RowData, Boolean>> getFilterOnLeftTable() {
if (filterOnTable) {
return Optional.of((rowData -> rowData.getBoolean(1)));
}
return Optional.empty();
}
@Override
Optional<Function<RowData, Boolean>> getFilterOnRightTable() {
if (filterOnTable) {
return Optional.of((rowData -> "jklk1".equals(rowData.getString(0).toString())));
}
return Optional.empty();
}
}
/**
* Mock sql like the following.
*
* <pre>
* CREATE TABLE leftSrc(
* left_value INT,
* left_pk1 BOOLEAN,
* left_pk2_jk_index STRING,
* PRIMARY KEY (left_pk1, left_pk2_jk_index) NOT ENFORCED
* INDEX(left_pk2_jk_index)
* )
* </pre>
*
* <pre>
* CREATE TABLE rightSrc(
* right_pk2_jk_index STRING,
* right_value INT,
* right_pk1 BOOLEAN,
* PRIMARY KEY (right_pk2_jk_index, right_pk1) NOT ENFORCED
* INDEX(right_pk2_jk_index)
* )
* </pre>
*
* <p>If the flag {@link #filterOnTable} is false, the query is:
*
* <pre>
* select * from leftSrc join rightSrc
* on leftSrc.left_pk2_jk_index = rightSrc.right_pk2_jk_index
* </pre>
*
* <p>If the flag {@link #filterOnTable} is true, the query is:
*
* <pre>
* select * from (
* select * from leftSrc where left_pk1 = 'true'
* ) join (
* select * form rightSrc where right_pk1 = 'false'
* ) on left_pk2_jk_index = right_pk2_jk_index
* </pre>
*/
private static | LogLogTableJoinTestSpec |
java | apache__camel | components/camel-sjms2/src/main/java/org/apache/camel/component/sjms2/Sjms2Component.java | {
"start": 1113,
"end": 1387
} | class ____ extends SjmsComponent {
public Sjms2Component() {
super(SjmsEndpoint.class);
}
@Override
protected SjmsEndpoint createSjmsEndpoint(String uri, String remaining) {
return new Sjms2Endpoint(uri, this, remaining);
}
}
| Sjms2Component |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/plan/nodes/exec/batch/BatchExecLookupJoin.java | {
"start": 2955,
"end": 8661
} | class ____ extends CommonExecLookupJoin
implements BatchExecNode<RowData>, SingleTransformationTranslator<RowData> {
public BatchExecLookupJoin(
ReadableConfig tableConfig,
FlinkJoinType joinType,
@Nullable RexNode preFilterCondition,
@Nullable RexNode remainingJoinCondition,
TemporalTableSourceSpec temporalTableSourceSpec,
Map<Integer, FunctionCallUtil.FunctionParam> lookupKeys,
@Nullable List<RexNode> projectionOnTemporalTable,
@Nullable RexNode filterOnTemporalTable,
@Nullable FunctionCallUtil.AsyncOptions asyncLookupOptions,
InputProperty inputProperty,
RowType outputType,
String description,
boolean preferCustomShuffle) {
super(
ExecNodeContext.newNodeId(),
ExecNodeContext.newContext(BatchExecLookupJoin.class),
ExecNodeContext.newPersistedConfig(BatchExecLookupJoin.class, tableConfig),
joinType,
preFilterCondition,
remainingJoinCondition,
temporalTableSourceSpec,
lookupKeys,
projectionOnTemporalTable,
filterOnTemporalTable,
asyncLookupOptions,
// batch lookup join does not support retry hint currently
null,
ChangelogMode.insertOnly(),
Collections.singletonList(inputProperty),
outputType,
description,
preferCustomShuffle);
}
@JsonCreator
public BatchExecLookupJoin(
@JsonProperty(FIELD_NAME_ID) int id,
@JsonProperty(FIELD_NAME_TYPE) ExecNodeContext context,
@JsonProperty(FIELD_NAME_CONFIGURATION) ReadableConfig persistedConfig,
@JsonProperty(FIELD_NAME_JOIN_TYPE) FlinkJoinType joinType,
@JsonProperty(FIELD_NAME_PRE_FILTER_CONDITION) @Nullable RexNode preFilterCondition,
@JsonProperty(FIELD_NAME_REMAINING_JOIN_CONDITION) @Nullable
RexNode remainingJoinCondition,
@JsonProperty(FIELD_NAME_TEMPORAL_TABLE)
TemporalTableSourceSpec temporalTableSourceSpec,
@JsonProperty(FIELD_NAME_LOOKUP_KEYS)
Map<Integer, FunctionCallUtil.FunctionParam> lookupKeys,
@JsonProperty(FIELD_NAME_PROJECTION_ON_TEMPORAL_TABLE) @Nullable
List<RexNode> projectionOnTemporalTable,
@JsonProperty(FIELD_NAME_FILTER_ON_TEMPORAL_TABLE) @Nullable
RexNode filterOnTemporalTable,
@JsonProperty(FIELD_NAME_ASYNC_OPTIONS) @Nullable
FunctionCallUtil.AsyncOptions asyncLookupOptions,
@JsonProperty(FIELD_NAME_INPUT_PROPERTIES) List<InputProperty> inputProperties,
@JsonProperty(FIELD_NAME_OUTPUT_TYPE) RowType outputType,
@JsonProperty(FIELD_NAME_DESCRIPTION) String description,
@JsonProperty(FIELD_NAME_PREFER_CUSTOM_SHUFFLE) boolean preferCustomShuffle) {
super(
id,
context,
persistedConfig,
joinType,
preFilterCondition,
remainingJoinCondition,
temporalTableSourceSpec,
lookupKeys,
projectionOnTemporalTable,
filterOnTemporalTable,
asyncLookupOptions,
// batch lookup join does not support retry hint currently
null,
ChangelogMode.insertOnly(),
inputProperties,
outputType,
description,
preferCustomShuffle);
}
@Override
@SuppressWarnings("unchecked")
public Transformation<RowData> translateToPlanInternal(
PlannerBase planner, ExecNodeConfig config) {
// There's no optimization when lookupKeyContainsPrimaryKey is true for batch, so set it to
// false for now. We can add it to CommonExecLookupJoin when needed.
return createJoinTransformation(planner, config, false, false);
}
@Override
protected Transformation<RowData> createSyncLookupJoinWithState(
Transformation<RowData> inputTransformation,
RelOptTable temporalTable,
ExecNodeConfig config,
ClassLoader classLoader,
Map<Integer, FunctionCallUtil.FunctionParam> allLookupKeys,
TableFunction<?> syncLookupFunction,
RelBuilder relBuilder,
RowType inputRowType,
RowType tableSourceRowType,
RowType resultRowType,
boolean isLeftOuterJoin,
boolean isObjectReuseEnabled,
boolean lookupKeyContainsPrimaryKey) {
return inputTransformation;
}
@Override
protected Transformation<RowData> createKeyOrderedAsyncLookupJoin(
Transformation<RowData> inputTransformation,
RelOptTable temporalTable,
ExecNodeConfig config,
ClassLoader classLoader,
Map<Integer, FunctionCallUtil.FunctionParam> allLookupKeys,
AsyncTableFunction<Object> asyncLookupFunction,
RelBuilder relBuilder,
RowType inputRowType,
RowType tableSourceRowType,
RowType resultRowType,
boolean isLeftOuterJoin,
FunctionCallUtil.AsyncOptions asyncLookupOptions) {
throw new IllegalStateException(
"Batch mode should not use key-ordered async lookup joins. This is a bug. Please file an issue.");
}
}
| BatchExecLookupJoin |
java | micronaut-projects__micronaut-core | runtime-osx/src/main/java/io/micronaut/scheduling/io/watch/osx/MacOsWatchThread.java | {
"start": 1890,
"end": 2892
} | class ____ extends DefaultWatchThread {
/**
* Default constructor.
*
* @param eventPublisher The event publisher
* @param configuration the configuration
* @param watchService the watch service
*/
public MacOsWatchThread(
ApplicationEventPublisher eventPublisher,
FileWatchConfiguration configuration,
WatchService watchService) {
super(eventPublisher, configuration, watchService);
}
@Override
protected @NonNull WatchKey registerPath(@NonNull Path dir) throws IOException {
WatchablePath watchPath = new WatchablePath(dir);
return watchPath.register(
getWatchService(),
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY
);
}
@Override
protected void closeWatchService() {
// no-op - for some reason this causes a JVM crash if not overridden
}
}
| MacOsWatchThread |
java | spring-projects__spring-framework | spring-core/src/test/java/org/springframework/core/convert/support/ByteBufferConverterTests.java | {
"start": 1008,
"end": 2917
} | class ____ {
private final GenericConversionService conversionService = new DefaultConversionService();
@BeforeEach
void setup() {
conversionService.addConverter(new ByteArrayToOtherTypeConverter());
conversionService.addConverter(new OtherTypeToByteArrayConverter());
}
@Test
void byteArrayToByteBuffer() {
byte[] bytes = new byte[] { 1, 2, 3 };
ByteBuffer convert = conversionService.convert(bytes, ByteBuffer.class);
assertThat(convert.array()).isNotSameAs(bytes);
assertThat(convert.array()).isEqualTo(bytes);
}
@Test
void byteBufferToByteArray() {
byte[] bytes = new byte[] { 1, 2, 3 };
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
byte[] convert = conversionService.convert(byteBuffer, byte[].class);
assertThat(convert).isNotSameAs(bytes);
assertThat(convert).isEqualTo(bytes);
}
@Test
void byteBufferToOtherType() {
byte[] bytes = new byte[] { 1, 2, 3 };
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
OtherType convert = conversionService.convert(byteBuffer, OtherType.class);
assertThat(convert.bytes).isNotSameAs(bytes);
assertThat(convert.bytes).isEqualTo(bytes);
}
@Test
void otherTypeToByteBuffer() {
byte[] bytes = new byte[] { 1, 2, 3 };
OtherType otherType = new OtherType(bytes);
ByteBuffer convert = conversionService.convert(otherType, ByteBuffer.class);
assertThat(convert.array()).isNotSameAs(bytes);
assertThat(convert.array()).isEqualTo(bytes);
}
@Test
void byteBufferToByteBuffer() {
byte[] bytes = new byte[] { 1, 2, 3 };
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
ByteBuffer convert = conversionService.convert(byteBuffer, ByteBuffer.class);
assertThat(convert).isNotSameAs(byteBuffer.rewind());
assertThat(convert).isEqualTo(byteBuffer.rewind());
assertThat(convert).isEqualTo(ByteBuffer.wrap(bytes));
assertThat(convert.array()).isEqualTo(bytes);
}
private static | ByteBufferConverterTests |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/join/lookup/keyordered/TableAsyncExecutionControllerTest.java | {
"start": 19834,
"end": 20158
} | class ____ extends AsyncWaitOperatorTest.LazyAsyncFunction {
public TestLazyAsyncFunction() {}
@Override
public void asyncInvoke(final Integer input, final ResultFuture<Integer> resultFuture) {
resultFuture.complete(Collections.singletonList(input));
}
}
}
| TestLazyAsyncFunction |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/shortcircuit/DfsClientShmManager.java | {
"start": 2974,
"end": 16326
} | class ____ {
/**
* The datanode we're managing.
*/
private final DatanodeInfo datanode;
/**
* Shared memory segments which have no empty slots.
*
* Protected by the manager lock.
*/
private final TreeMap<ShmId, DfsClientShm> full = new TreeMap<>();
/**
* Shared memory segments which have at least one empty slot.
*
* Protected by the manager lock.
*/
private final TreeMap<ShmId, DfsClientShm> notFull = new TreeMap<>();
/**
* True if this datanode doesn't support short-circuit shared memory
* segments.
*
* Protected by the manager lock.
*/
private boolean disabled = false;
/**
* True if we're in the process of loading a shared memory segment from
* this DataNode.
*
* Protected by the manager lock.
*/
private boolean loading = false;
EndpointShmManager (DatanodeInfo datanode) {
this.datanode = datanode;
}
/**
* Pull a slot out of a preexisting shared memory segment.
*
* Must be called with the manager lock held.
*
* @param blockId The blockId to put inside the Slot object.
*
* @return null if none of our shared memory segments contain a
* free slot; the slot object otherwise.
*/
private Slot allocSlotFromExistingShm(ExtendedBlockId blockId) {
if (notFull.isEmpty()) {
return null;
}
Entry<ShmId, DfsClientShm> entry = notFull.firstEntry();
DfsClientShm shm = entry.getValue();
ShmId shmId = shm.getShmId();
Slot slot = shm.allocAndRegisterSlot(blockId);
if (shm.isFull()) {
LOG.trace("{}: pulled the last slot {} out of {}",
this, slot.getSlotIdx(), shm);
DfsClientShm removedShm = notFull.remove(shmId);
Preconditions.checkState(removedShm == shm);
full.put(shmId, shm);
} else {
LOG.trace("{}: pulled slot {} out of {}", this, slot.getSlotIdx(), shm);
}
return slot;
}
/**
* Ask the DataNode for a new shared memory segment. This function must be
* called with the manager lock held. We will release the lock while
* communicating with the DataNode.
*
* @param clientName The current client name.
* @param peer The peer to use to talk to the DataNode.
*
* @return Null if the DataNode does not support shared memory
* segments, or experienced an error creating the
* shm. The shared memory segment itself on success.
* @throws IOException If there was an error communicating over the socket.
* We will not throw an IOException unless the socket
* itself (or the network) is the problem.
*/
private DfsClientShm requestNewShm(String clientName, DomainPeer peer)
throws IOException {
final DataOutputStream out =
new DataOutputStream(
new BufferedOutputStream(peer.getOutputStream()));
new Sender(out).requestShortCircuitShm(clientName);
ShortCircuitShmResponseProto resp =
ShortCircuitShmResponseProto.parseFrom(
PBHelperClient.vintPrefixed(peer.getInputStream()));
String error = resp.hasError() ? resp.getError() : "(unknown)";
switch (resp.getStatus()) {
case SUCCESS:
DomainSocket sock = peer.getDomainSocket();
byte buf[] = new byte[1];
FileInputStream[] fis = new FileInputStream[1];
if (sock.recvFileInputStreams(fis, buf, 0, buf.length) < 0) {
throw new EOFException("got EOF while trying to transfer the " +
"file descriptor for the shared memory segment.");
}
if (fis[0] == null) {
throw new IOException("the datanode " + datanode + " failed to " +
"pass a file descriptor for the shared memory segment.");
}
try {
DfsClientShm shm =
new DfsClientShm(PBHelperClient.convert(resp.getId()),
fis[0], this, peer);
LOG.trace("{}: createNewShm: created {}", this, shm);
return shm;
} finally {
try {
fis[0].close();
} catch (Throwable e) {
LOG.debug("Exception in closing " + fis[0], e);
}
}
case ERROR_UNSUPPORTED:
// The DataNode just does not support short-circuit shared memory
// access, and we should stop asking.
LOG.info(this + ": datanode does not support short-circuit " +
"shared memory access: " + error);
disabled = true;
return null;
default:
// The datanode experienced some kind of unexpected error when trying to
// create the short-circuit shared memory segment.
LOG.warn(this + ": error requesting short-circuit shared memory " +
"access: " + error);
return null;
}
}
/**
* Allocate a new shared memory slot connected to this datanode.
*
* Must be called with the EndpointShmManager lock held.
*
* @param peer The peer to use to talk to the DataNode.
* @param usedPeer (out param) Will be set to true if we used the peer.
* When a peer is used
*
* @param clientName The client name.
* @param blockId The block ID to use.
* @return null if the DataNode does not support shared memory
* segments, or experienced an error creating the
* shm. The shared memory segment itself on success.
* @throws IOException If there was an error communicating over the socket.
*/
Slot allocSlot(DomainPeer peer, MutableBoolean usedPeer,
String clientName, ExtendedBlockId blockId) throws IOException {
while (true) {
if (closed) {
LOG.trace("{}: the DfsClientShmManager has been closed.", this);
return null;
}
if (disabled) {
LOG.trace("{}: shared memory segment access is disabled.", this);
return null;
}
// Try to use an existing slot.
Slot slot = allocSlotFromExistingShm(blockId);
if (slot != null) {
return slot;
}
// There are no free slots. If someone is loading more slots, wait
// for that to finish.
if (loading) {
LOG.trace("{}: waiting for loading to finish...", this);
finishedLoading.awaitUninterruptibly();
} else {
// Otherwise, load the slot ourselves.
loading = true;
lock.unlock();
DfsClientShm shm;
try {
shm = requestNewShm(clientName, peer);
if (shm == null) continue;
// See #{DfsClientShmManager#domainSocketWatcher} for details
// about why we do this before retaking the manager lock.
domainSocketWatcher.add(peer.getDomainSocket(), shm);
// The DomainPeer is now our responsibility, and should not be
// closed by the caller.
usedPeer.setValue(true);
} finally {
lock.lock();
loading = false;
finishedLoading.signalAll();
}
if (shm.isDisconnected()) {
// If the peer closed immediately after the shared memory segment
// was created, the DomainSocketWatcher callback might already have
// fired and marked the shm as disconnected. In this case, we
// obviously don't want to add the SharedMemorySegment to our list
// of valid not-full segments.
LOG.debug("{}: the UNIX domain socket associated with this "
+ "short-circuit memory closed before we could make use of "
+ "the shm.", this);
} else {
notFull.put(shm.getShmId(), shm);
}
}
}
}
/**
* Stop tracking a slot.
*
* Must be called with the EndpointShmManager lock held.
*
* @param slot The slot to release.
*/
void freeSlot(Slot slot) {
DfsClientShm shm = (DfsClientShm)slot.getShm();
shm.unregisterSlot(slot.getSlotIdx());
if (shm.isDisconnected()) {
// Stale shared memory segments should not be tracked here.
Preconditions.checkState(!full.containsKey(shm.getShmId()));
Preconditions.checkState(!notFull.containsKey(shm.getShmId()));
if (shm.isEmpty()) {
LOG.trace("{}: freeing empty stale {}", this, shm);
shm.free();
}
} else {
ShmId shmId = shm.getShmId();
full.remove(shmId); // The shm can't be full if we just freed a slot.
if (shm.isEmpty()) {
notFull.remove(shmId);
// If the shared memory segment is now empty, we call shutdown(2) on
// the UNIX domain socket associated with it. The DomainSocketWatcher,
// which is watching this socket, will call DfsClientShm#handle,
// cleaning up this shared memory segment.
//
// See #{DfsClientShmManager#domainSocketWatcher} for details about why
// we don't want to call DomainSocketWatcher#remove directly here.
//
// Note that we could experience 'fragmentation' here, where the
// DFSClient allocates a bunch of slots in different shared memory
// segments, and then frees most of them, but never fully empties out
// any segment. We make some attempt to avoid this fragmentation by
// always allocating new slots out of the shared memory segment with the
// lowest ID, but it could still occur. In most workloads,
// fragmentation should not be a major concern, since it doesn't impact
// peak file descriptor usage or the speed of allocation.
LOG.trace("{}: shutting down UNIX domain socket for empty {}",
this, shm);
shutdown(shm);
} else {
notFull.put(shmId, shm);
}
}
}
/**
* Unregister a shared memory segment.
*
* Once a segment is unregistered, we will not allocate any more slots
* inside that segment.
*
* The DomainSocketWatcher calls this while holding the DomainSocketWatcher
* lock.
*
* @param shmId The ID of the shared memory segment to unregister.
*/
void unregisterShm(ShmId shmId) {
lock.lock();
try {
full.remove(shmId);
notFull.remove(shmId);
} finally {
lock.unlock();
}
}
@Override
public String toString() {
return String.format("EndpointShmManager(%s, parent=%s)",
datanode, DfsClientShmManager.this);
}
PerDatanodeVisitorInfo getVisitorInfo() {
return new PerDatanodeVisitorInfo(full, notFull, disabled);
}
final void shutdown(DfsClientShm shm) {
try {
shm.getPeer().getDomainSocket().shutdown();
} catch (IOException e) {
LOG.warn(this + ": error shutting down shm: got IOException calling " +
"shutdown(SHUT_RDWR)", e);
}
}
}
private boolean closed = false;
private final ReentrantLock lock = new ReentrantLock();
/**
* A condition variable which is signalled when we finish loading a segment
* from the Datanode.
*/
private final Condition finishedLoading = lock.newCondition();
/**
* Information about each Datanode.
*/
private final HashMap<DatanodeInfo, EndpointShmManager> datanodes =
new HashMap<>(1);
/**
* The DomainSocketWatcher which keeps track of the UNIX domain socket
* associated with each shared memory segment.
*
* Note: because the DomainSocketWatcher makes callbacks into this
* DfsClientShmManager object, you must MUST NOT attempt to take the
* DomainSocketWatcher lock while holding the DfsClientShmManager lock,
* or else deadlock might result. This means that most DomainSocketWatcher
* methods are off-limits unless you release the manager lock first.
*/
private final DomainSocketWatcher domainSocketWatcher;
DfsClientShmManager(int interruptCheckPeriodMs) throws IOException {
this.domainSocketWatcher = new DomainSocketWatcher(interruptCheckPeriodMs,
"client");
}
public Slot allocSlot(DatanodeInfo datanode, DomainPeer peer,
MutableBoolean usedPeer, ExtendedBlockId blockId,
String clientName) throws IOException {
lock.lock();
try {
if (closed) {
LOG.trace(this + ": the DfsClientShmManager isclosed.");
return null;
}
EndpointShmManager shmManager = datanodes.get(datanode);
if (shmManager == null) {
shmManager = new EndpointShmManager(datanode);
datanodes.put(datanode, shmManager);
}
return shmManager.allocSlot(peer, usedPeer, clientName, blockId);
} finally {
lock.unlock();
}
}
public void freeSlot(Slot slot) {
lock.lock();
try {
DfsClientShm shm = (DfsClientShm)slot.getShm();
shm.getEndpointShmManager().freeSlot(slot);
} finally {
lock.unlock();
}
}
@VisibleForTesting
public static | EndpointShmManager |
java | apache__flink | flink-python/src/main/java/org/apache/flink/table/runtime/arrow/writers/TimeWriter.java | {
"start": 1397,
"end": 3268
} | class ____<T> extends ArrowFieldWriter<T> {
public static TimeWriter<RowData> forRow(ValueVector valueVector) {
return new TimeWriterForRow(valueVector);
}
public static TimeWriter<ArrayData> forArray(ValueVector valueVector) {
return new TimeWriterForArray(valueVector);
}
// ------------------------------------------------------------------------------------------
private TimeWriter(ValueVector valueVector) {
super(valueVector);
Preconditions.checkState(
valueVector instanceof TimeSecVector
|| valueVector instanceof TimeMilliVector
|| valueVector instanceof TimeMicroVector
|| valueVector instanceof TimeNanoVector);
}
abstract boolean isNullAt(T in, int ordinal);
abstract int readTime(T in, int ordinal);
@Override
public void doWrite(T in, int ordinal) {
ValueVector valueVector = getValueVector();
if (isNullAt(in, ordinal)) {
((BaseFixedWidthVector) valueVector).setNull(getCount());
} else if (valueVector instanceof TimeSecVector) {
((TimeSecVector) valueVector).setSafe(getCount(), readTime(in, ordinal) / 1000);
} else if (valueVector instanceof TimeMilliVector) {
((TimeMilliVector) valueVector).setSafe(getCount(), readTime(in, ordinal));
} else if (valueVector instanceof TimeMicroVector) {
((TimeMicroVector) valueVector).setSafe(getCount(), readTime(in, ordinal) * 1000L);
} else {
((TimeNanoVector) valueVector).setSafe(getCount(), readTime(in, ordinal) * 1000000L);
}
}
// ------------------------------------------------------------------------------------------
/** {@link TimeWriter} for {@link RowData} input. */
public static final | TimeWriter |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/annotations/Filter.java | {
"start": 1855,
"end": 3715
} | interface ____ {
/**
* The name of the filter declared using {@link FilterDef}.
*/
String name();
/**
* The filter condition, a SQL expression used for filtering
* the rows returned by a query when the filter is enabled.
* If not specified, the default filter condition given by
* {@link FilterDef#defaultCondition} is used.
* <p>
* By default, aliases of filtered tables are automatically
* interpolated into the filter condition, before any token
* that looks like a column name. Occasionally, when the
* interpolation algorithm encounters ambiguity, the process
* of alias interpolation produces broken SQL. In such cases,
* alias interpolation may be controlled explicitly using
* either {@link #deduceAliasInjectionPoints} or
* {@link #aliases}.
*/
String condition() default "";
/**
* Determines how tables aliases are interpolated into the
* {@link #condition} SQL expression.
* <ul>
* <li>if {@code true}, and by default, an alias is added
* automatically to every column occurring in the SQL
* expression, but
* <li>if {@code false}, aliases are only interpolated where
* an explicit placeholder of form {@code {alias}} occurs
* in the SQL expression.
* <li>Finally, if {@link #aliases explicit aliases} are
* specified, then alias interpolation happens only for
* the specified aliases.
* </ul>
*/
boolean deduceAliasInjectionPoints() default true;
/**
* Explicitly specifies how aliases are interpolated into
* the {@linkplain #condition SQL expression}. Each listed
* {@link SqlFragmentAlias} specifies a placeholder name
* and the table whose alias should be interpolated.
* Placeholders are of form {@code {name}} where {@code name}
* matches a given {@link SqlFragmentAlias#alias alias}.
*/
SqlFragmentAlias[] aliases() default {};
}
| Filter |
java | spring-projects__spring-framework | spring-jdbc/src/main/java/org/springframework/jdbc/core/DataClassRowMapper.java | {
"start": 1657,
"end": 1805
} | class ____ has a constructor with named parameters
* that are intended to be mapped to corresponding column names.
*
* <p>When combining a data | which |
java | quarkusio__quarkus | independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/json/JsonBuilder.java | {
"start": 747,
"end": 881
} | interface ____<T> {
T build();
/**
* Make sure a JsonBuilder is built before being serialized
*/
public | JsonBuilder |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/mapper/BlockSourceReader.java | {
"start": 11306,
"end": 11942
} | class ____ extends SourceBlockLoader {
public IntsBlockLoader(ValueFetcher fetcher, LeafIteratorLookup lookup) {
super(fetcher, lookup);
}
@Override
public Builder builder(BlockFactory factory, int expectedCount) {
return factory.ints(expectedCount);
}
@Override
public RowStrideReader rowStrideReader(LeafReaderContext context, DocIdSetIterator iter) throws IOException {
return new Ints(fetcher, iter);
}
@Override
protected String name() {
return "Ints";
}
}
private static | IntsBlockLoader |
java | FasterXML__jackson-core | src/main/java/tools/jackson/core/io/BigDecimalParser.java | {
"start": 954,
"end": 7441
} | class ____
{
final static int MAX_CHARS_TO_REPORT = 1000;
private final static int SIZE_FOR_SWITCH_TO_FASTDOUBLEPARSER = 500;
private BigDecimalParser() {}
/**
* Internal Jackson method. Please do not use.
*<p>
* Note: Caller MUST pre-validate that given String represents a valid representation
* of {@link BigDecimal} value: parsers in {@code jackson-core} do that; other
* code must do the same.
*
* @param valueStr Value to parse
*
* @return BigDecimal value
*
* @throws NumberFormatException for decoding failures
*/
public static BigDecimal parse(String valueStr) {
try {
if (valueStr.length() < SIZE_FOR_SWITCH_TO_FASTDOUBLEPARSER) {
return new BigDecimal(valueStr);
}
return JavaBigDecimalParser.parseBigDecimal(valueStr);
// 20-Aug-2022, tatu: Although "new BigDecimal(...)" only throws NumberFormatException
// operations by "parseBigDecimal()" can throw "ArithmeticException", so handle both:
} catch (ArithmeticException | NumberFormatException e) {
throw _parseFailure(e, valueStr);
}
}
/**
* Internal Jackson method. Please do not use.
*<p>
* Note: Caller MUST pre-validate that given String represents a valid representation
* of {@link BigDecimal} value: parsers in {@code jackson-core} do that; other
* code must do the same.
*
* @param chars Buffer that contains value to parse
* @param off Offset of the first character to decode
* @param len Length of value to parse in buffer
*
* @return BigDecimal value
*
* @throws NumberFormatException for decoding failures
*/
public static BigDecimal parse(final char[] chars, final int off, final int len) {
try {
if (len < SIZE_FOR_SWITCH_TO_FASTDOUBLEPARSER) {
return new BigDecimal(chars, off, len);
}
return JavaBigDecimalParser.parseBigDecimal(chars, off, len);
// 20-Aug-2022, tatu: Although "new BigDecimal(...)" only throws NumberFormatException
// operations by "parseBigDecimal()" can throw "ArithmeticException", so handle both:
} catch (ArithmeticException | NumberFormatException e) {
throw _parseFailure(e, chars, off, len);
}
}
/**
* Internal Jackson method. Please do not use.
*<p>
* Note: Caller MUST pre-validate that given String represents a valid representation
* of {@link BigDecimal} value: parsers in {@code jackson-core} do that; other
* code must do the same.
*
* @param chars Value to parse
* @return BigDecimal value
* @throws NumberFormatException for decoding failures
*/
public static BigDecimal parse(char[] chars) {
return parse(chars, 0, chars.length);
}
/**
* Internal Jackson method. Please do not use.
*<p>
* Note: Caller MUST pre-validate that given String represents a valid representation
* of {@link BigDecimal} value: parsers in {@code jackson-core} do that; other
* code must do the same.
*
* @param valueStr Value to parse
*
* @return BigDecimal value
*
* @throws NumberFormatException for decoding failures
*/
public static BigDecimal parseWithFastParser(final String valueStr) {
try {
return JavaBigDecimalParser.parseBigDecimal(valueStr);
} catch (ArithmeticException | NumberFormatException e) {
throw _parseFailure(e, valueStr);
}
}
/**
* Internal Jackson method. Please do not use.
*<p>
* Note: Caller MUST pre-validate that given String represents a valid representation
* of {@link BigDecimal} value: parsers in {@code jackson-core} do that; other
* code must do the same.
*
* @return BigDecimal value
*
* @throws NumberFormatException for decoding failures
*/
public static BigDecimal parseWithFastParser(final char[] ch, final int off, final int len) {
try {
return JavaBigDecimalParser.parseBigDecimal(ch, off, len);
} catch (ArithmeticException | NumberFormatException e) {
throw _parseFailure(e, ch, off, len);
}
}
private static NumberFormatException _parseFailure(Exception e, String fullValue) {
String desc = e.getMessage();
// 05-Feb-2021, tatu: Alas, JDK mostly has null message so:
if (desc == null) {
desc = "Not a valid number representation";
}
String valueToReport = _getValueDesc(fullValue);
return new NumberFormatException(_generateExceptionMessage(valueToReport, desc));
}
private static NumberFormatException _parseFailure(final Exception e,
final char[] array,
final int offset,
final int len) {
String desc = e.getMessage();
// 05-Feb-2021, tatu: Alas, JDK mostly has null message so:
if (desc == null) {
desc = "Not a valid number representation";
}
String valueToReport = _getValueDesc(array, offset, len);
return new NumberFormatException(_generateExceptionMessage(valueToReport, desc));
}
private static String _getValueDesc(final String fullValue) {
final int len = fullValue.length();
if (len <= MAX_CHARS_TO_REPORT) {
return String.format("\"%s\"", fullValue);
}
return String.format("\"%s\" (truncated to %d chars (from %d))",
fullValue.substring(0, MAX_CHARS_TO_REPORT),
MAX_CHARS_TO_REPORT, len);
}
private static String _getValueDesc(final char[] array, final int offset, final int len) {
if (len <= MAX_CHARS_TO_REPORT) {
return String.format("\"%s\"", new String(array, offset, len));
}
return String.format("\"%s\" (truncated to %d chars (from %d))",
new String(array, offset, MAX_CHARS_TO_REPORT),
MAX_CHARS_TO_REPORT, len);
}
private static String _generateExceptionMessage(final String valueToReport, final String desc) {
return String.format("Value %s cannot be deserialized as `java.math.BigDecimal`, reason: %s" ,
valueToReport, desc);
}
}
| BigDecimalParser |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/functions/Action.java | {
"start": 666,
"end": 769
} | interface ____ to Runnable but allows throwing a checked exception.
*/
@FunctionalInterface
public | similar |
java | apache__flink | flink-clients/src/test/java/org/apache/flink/client/cli/CliFrontendITCase.java | {
"start": 1778,
"end": 4925
} | class ____ {
private PrintStream originalPrintStream;
private ByteArrayOutputStream testOutputStream;
@BeforeEach
void before() {
originalPrintStream = System.out;
testOutputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(testOutputStream));
}
@AfterEach
void tearDown() {
System.setOut(originalPrintStream);
}
private String getStdoutString() {
return testOutputStream.toString();
}
@Test
void configurationIsForwarded() throws Exception {
Configuration config = new Configuration();
CustomCommandLine commandLine = new DefaultCLI();
config.set(PipelineOptions.AUTO_WATERMARK_INTERVAL, Duration.ofMillis(42L));
CliFrontend cliFrontend = new CliFrontend(config, Collections.singletonList(commandLine));
cliFrontend.parseAndRun(
new String[] {
"run", "-c", TestingJob.class.getName(), CliFrontendTestUtils.getTestJarPath()
});
assertThat(getStdoutString()).contains("Watermark interval is 42");
}
@Test
void commandlineOverridesConfiguration() throws Exception {
Configuration config = new Configuration();
// we use GenericCli because it allows specifying arbitrary options via "-Dfoo=bar" syntax
CustomCommandLine commandLine = new GenericCLI(config, "/dev/null");
config.set(PipelineOptions.AUTO_WATERMARK_INTERVAL, Duration.ofMillis(42L));
CliFrontend cliFrontend = new CliFrontend(config, Collections.singletonList(commandLine));
cliFrontend.parseAndRun(
new String[] {
"run",
"-t",
LocalExecutor.NAME,
"-c",
TestingJob.class.getName(),
"-D" + PipelineOptions.AUTO_WATERMARK_INTERVAL.key() + "=142",
CliFrontendTestUtils.getTestJarPath()
});
assertThat(getStdoutString()).contains("Watermark interval is 142");
}
@Test
void mainShouldPrintHelpWithoutArgs(@TempDir Path tempFolder) throws Exception {
Map<String, String> originalEnv = System.getenv();
try {
File confFolder = Files.createTempDirectory(tempFolder, "conf").toFile();
File confYaml = new File(confFolder, "config.yaml");
if (!confYaml.createNewFile()) {
throw new IOException("Can't create testing config.yaml file.");
}
Map<String, String> map = new HashMap<>(System.getenv());
map.put(ENV_FLINK_CONF_DIR, confFolder.getAbsolutePath());
CommonTestUtils.setEnv(map);
assertThat(CliFrontend.mainInternal(new String[0])).isEqualTo(1);
assertThat(getStdoutString()).contains("The following actions are available");
} finally {
CommonTestUtils.setEnv(originalEnv);
}
}
/**
* Testing job that the watermark interval from the {@link
* org.apache.flink.api.common.ExecutionConfig}.
*/
public static | CliFrontendITCase |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/metrics/CollectingMetricsReporter.java | {
"start": 1387,
"end": 3245
} | class ____ extends TestReporter {
@Nullable private final CharacterFilter characterFilter;
private final List<MetricGroupAndName> addedMetrics = new ArrayList<>();
private final List<MetricGroupAndName> removedMetrics = new ArrayList<>();
public CollectingMetricsReporter() {
this(null);
}
public CollectingMetricsReporter(@Nullable CharacterFilter characterFilter) {
this.characterFilter = characterFilter;
}
@Override
public String filterCharacters(String input) {
return characterFilter == null ? input : characterFilter.filterCharacters(input);
}
@Override
public void notifyOfAddedMetric(Metric metric, String metricName, MetricGroup group) {
addedMetrics.add(new MetricGroupAndName(metricName, group));
}
@Override
public void notifyOfRemovedMetric(Metric metric, String metricName, MetricGroup group) {
removedMetrics.add(new MetricGroupAndName(metricName, group));
}
public List<MetricGroupAndName> getAddedMetrics() {
return unmodifiableList(addedMetrics);
}
public List<MetricGroupAndName> getRemovedMetrics() {
return unmodifiableList(removedMetrics);
}
public MetricGroupAndName findAdded(String name) {
return getMetricGroupAndName(name, addedMetrics);
}
MetricGroupAndName findRemoved(String name) {
return getMetricGroupAndName(name, removedMetrics);
}
@SuppressWarnings("OptionalGetWithoutIsPresent")
private MetricGroupAndName getMetricGroupAndName(
String name, List<MetricGroupAndName> metricsList) {
return metricsList.stream()
.filter(groupAndName -> groupAndName.name.equals(name))
.findAny()
.get();
}
/** Metric group and name. */
public static | CollectingMetricsReporter |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-nativetask/src/main/java/org/apache/hadoop/mapred/nativetask/TaskContext.java | {
"start": 1086,
"end": 2633
} | class ____ {
private final JobConf conf;
private Class<?> iKClass;
private Class<?> iVClass;
private Class<?> oKClass;
private Class<?> oVClass;
private final TaskReporter reporter;
private final TaskAttemptID taskAttemptID;
public TaskContext(JobConf conf, Class<?> iKClass, Class<?> iVClass,
Class<?> oKClass, Class<?> oVClass, TaskReporter reporter,
TaskAttemptID id) {
this.conf = conf;
this.iKClass = iKClass;
this.iVClass = iVClass;
this.oKClass = oKClass;
this.oVClass = oVClass;
this.reporter = reporter;
this.taskAttemptID = id;
}
public Class<?> getInputKeyClass() {
return iKClass;
}
public void setInputKeyClass(Class<?> klass) {
this.iKClass = klass;
}
public Class<?> getInputValueClass() {
return iVClass;
}
public void setInputValueClass(Class<?> klass) {
this.iVClass = klass;
}
public Class<?> getOutputKeyClass() {
return this.oKClass;
}
public void setOutputKeyClass(Class<?> klass) {
this.oKClass = klass;
}
public Class<?> getOutputValueClass() {
return this.oVClass;
}
public void setOutputValueClass(Class<?> klass) {
this.oVClass = klass;
}
public TaskReporter getTaskReporter() {
return this.reporter;
}
public TaskAttemptID getTaskAttemptId() {
return this.taskAttemptID;
}
public JobConf getConf() {
return this.conf;
}
public TaskContext copyOf() {
return new TaskContext(conf, iKClass, iVClass, oKClass, oVClass, reporter, taskAttemptID);
}
}
| TaskContext |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/spatial/SpatialWithinCartesianSourceAndSourceEvaluator.java | {
"start": 3859,
"end": 4712
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final Source source;
private final EvalOperator.ExpressionEvaluator.Factory left;
private final EvalOperator.ExpressionEvaluator.Factory right;
public Factory(Source source, EvalOperator.ExpressionEvaluator.Factory left,
EvalOperator.ExpressionEvaluator.Factory right) {
this.source = source;
this.left = left;
this.right = right;
}
@Override
public SpatialWithinCartesianSourceAndSourceEvaluator get(DriverContext context) {
return new SpatialWithinCartesianSourceAndSourceEvaluator(source, left.get(context), right.get(context), context);
}
@Override
public String toString() {
return "SpatialWithinCartesianSourceAndSourceEvaluator[" + "left=" + left + ", right=" + right + "]";
}
}
}
| Factory |
java | apache__flink | flink-filesystems/flink-gs-fs-hadoop/src/main/java/org/apache/flink/fs/gs/writer/GSCommitRecoverable.java | {
"start": 1356,
"end": 4415
} | class ____ implements RecoverableWriter.CommitRecoverable {
private static final Logger LOGGER = LoggerFactory.getLogger(GSCommitRecoverable.class);
/** The blob id to which the recoverable write operation is writing. */
public final GSBlobIdentifier finalBlobIdentifier;
/**
* The object ids for the temporary objects that should be composed to form the final blob. This
* is an unmodifiable list.
*/
public final List<UUID> componentObjectIds;
GSCommitRecoverable(GSBlobIdentifier finalBlobIdentifier, List<UUID> componentObjectIds) {
LOGGER.trace(
"Creating GSCommitRecoverable for blob {} and componentObjectIds={}",
finalBlobIdentifier,
componentObjectIds);
this.finalBlobIdentifier = Preconditions.checkNotNull(finalBlobIdentifier);
this.componentObjectIds =
Collections.unmodifiableList(
new ArrayList<>(Preconditions.checkNotNull(componentObjectIds)));
}
/**
* Returns the list of component blob ids, which have to be resolved from the temporary bucket
* name, prefix, and component ids. Resolving them this way vs. storing the blob ids directly
* allows us to move in-progress blobs by changing options to point to new in-progress
* locations.
*
* @param options The GS file system options
* @return The list of component blob ids
*/
List<GSBlobIdentifier> getComponentBlobIds(GSFileSystemOptions options) {
String temporaryBucketName = BlobUtils.getTemporaryBucketName(finalBlobIdentifier, options);
List<GSBlobIdentifier> componentBlobIdentifiers =
componentObjectIds.stream()
.map(
temporaryObjectId ->
options.isFileSinkEntropyEnabled()
? BlobUtils.getTemporaryObjectNameWithEntropy(
finalBlobIdentifier, temporaryObjectId)
: BlobUtils.getTemporaryObjectName(
finalBlobIdentifier, temporaryObjectId))
.map(
temporaryObjectName ->
new GSBlobIdentifier(
temporaryBucketName, temporaryObjectName))
.collect(Collectors.toList());
LOGGER.trace(
"Resolved component blob identifiers for blob {}: {}",
finalBlobIdentifier,
componentBlobIdentifiers);
return componentBlobIdentifiers;
}
@Override
public String toString() {
return "GSCommitRecoverable{"
+ "finalBlobIdentifier="
+ finalBlobIdentifier
+ ", componentObjectIds="
+ componentObjectIds
+ '}';
}
}
| GSCommitRecoverable |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/Hamlet.java | {
"start": 541504,
"end": 552791
} | class ____<T extends __> extends EImp<T> implements HamletSpec.CODE {
public CODE(String name, T parent, EnumSet<EOpt> opts) {
super(name, parent, opts);
}
@Override
public CODE<T> $id(String value) {
addAttr("id", value);
return this;
}
@Override
public CODE<T> $class(String value) {
addAttr("class", value);
return this;
}
@Override
public CODE<T> $title(String value) {
addAttr("title", value);
return this;
}
@Override
public CODE<T> $style(String value) {
addAttr("style", value);
return this;
}
@Override
public CODE<T> $lang(String value) {
addAttr("lang", value);
return this;
}
@Override
public CODE<T> $dir(Dir value) {
addAttr("dir", value);
return this;
}
@Override
public CODE<T> $onclick(String value) {
addAttr("onclick", value);
return this;
}
@Override
public CODE<T> $ondblclick(String value) {
addAttr("ondblclick", value);
return this;
}
@Override
public CODE<T> $onmousedown(String value) {
addAttr("onmousedown", value);
return this;
}
@Override
public CODE<T> $onmouseup(String value) {
addAttr("onmouseup", value);
return this;
}
@Override
public CODE<T> $onmouseover(String value) {
addAttr("onmouseover", value);
return this;
}
@Override
public CODE<T> $onmousemove(String value) {
addAttr("onmousemove", value);
return this;
}
@Override
public CODE<T> $onmouseout(String value) {
addAttr("onmouseout", value);
return this;
}
@Override
public CODE<T> $onkeypress(String value) {
addAttr("onkeypress", value);
return this;
}
@Override
public CODE<T> $onkeydown(String value) {
addAttr("onkeydown", value);
return this;
}
@Override
public CODE<T> $onkeyup(String value) {
addAttr("onkeyup", value);
return this;
}
@Override
public CODE<T> __(Object... lines) {
_p(true, lines);
return this;
}
@Override
public CODE<T> _r(Object... lines) {
_p(false, lines);
return this;
}
@Override
public B<CODE<T>> b() {
closeAttrs();
return b_(this, true);
}
@Override
public CODE<T> b(String cdata) {
return b().__(cdata).__();
}
@Override
public CODE<T> b(String selector, String cdata) {
return setSelector(b(), selector).__(cdata).__();
}
@Override
public I<CODE<T>> i() {
closeAttrs();
return i_(this, true);
}
@Override
public CODE<T> i(String cdata) {
return i().__(cdata).__();
}
@Override
public CODE<T> i(String selector, String cdata) {
return setSelector(i(), selector).__(cdata).__();
}
@Override
public SMALL<CODE<T>> small() {
closeAttrs();
return small_(this, true);
}
@Override
public CODE<T> small(String cdata) {
return small().__(cdata).__();
}
@Override
public CODE<T> small(String selector, String cdata) {
return setSelector(small(), selector).__(cdata).__();
}
@Override
public CODE<T> em(String cdata) {
return em().__(cdata).__();
}
@Override
public EM<CODE<T>> em() {
closeAttrs();
return em_(this, true);
}
@Override
public CODE<T> em(String selector, String cdata) {
return setSelector(em(), selector).__(cdata).__();
}
@Override
public STRONG<CODE<T>> strong() {
closeAttrs();
return strong_(this, true);
}
@Override
public CODE<T> strong(String cdata) {
return strong().__(cdata).__();
}
@Override
public CODE<T> strong(String selector, String cdata) {
return setSelector(strong(), selector).__(cdata).__();
}
@Override
public DFN<CODE<T>> dfn() {
closeAttrs();
return dfn_(this, true);
}
@Override
public CODE<T> dfn(String cdata) {
return dfn().__(cdata).__();
}
@Override
public CODE<T> dfn(String selector, String cdata) {
return setSelector(dfn(), selector).__(cdata).__();
}
@Override
public CODE<CODE<T>> code() {
closeAttrs();
return code_(this, true);
}
@Override
public CODE<T> code(String cdata) {
return code().__(cdata).__();
}
@Override
public CODE<T> code(String selector, String cdata) {
return setSelector(code(), selector).__(cdata).__();
}
@Override
public CODE<T> samp(String cdata) {
return samp().__(cdata).__();
}
@Override
public SAMP<CODE<T>> samp() {
closeAttrs();
return samp_(this, true);
}
@Override
public CODE<T> samp(String selector, String cdata) {
return setSelector(samp(), selector).__(cdata).__();
}
@Override
public KBD<CODE<T>> kbd() {
closeAttrs();
return kbd_(this, true);
}
@Override
public CODE<T> kbd(String cdata) {
return kbd().__(cdata).__();
}
@Override
public CODE<T> kbd(String selector, String cdata) {
return setSelector(kbd(), selector).__(cdata).__();
}
@Override
public VAR<CODE<T>> var() {
closeAttrs();
return var_(this, true);
}
@Override
public CODE<T> var(String cdata) {
return var().__(cdata).__();
}
@Override
public CODE<T> var(String selector, String cdata) {
return setSelector(var(), selector).__(cdata).__();
}
@Override
public CITE<CODE<T>> cite() {
closeAttrs();
return cite_(this, true);
}
@Override
public CODE<T> cite(String cdata) {
return cite().__(cdata).__();
}
@Override
public CODE<T> cite(String selector, String cdata) {
return setSelector(cite(), selector).__(cdata).__();
}
@Override
public ABBR<CODE<T>> abbr() {
closeAttrs();
return abbr_(this, true);
}
@Override
public CODE<T> abbr(String cdata) {
return abbr().__(cdata).__();
}
@Override
public CODE<T> abbr(String selector, String cdata) {
return setSelector(abbr(), selector).__(cdata).__();
}
@Override
public A<CODE<T>> a() {
closeAttrs();
return a_(this, true);
}
@Override
public A<CODE<T>> a(String selector) {
return setSelector(a(), selector);
}
@Override
public CODE<T> a(String href, String anchorText) {
return a().$href(href).__(anchorText).__();
}
@Override
public CODE<T> a(String selector, String href, String anchorText) {
return setSelector(a(), selector).$href(href).__(anchorText).__();
}
@Override
public IMG<CODE<T>> img() {
closeAttrs();
return img_(this, true);
}
@Override
public CODE<T> img(String src) {
return img().$src(src).__();
}
@Override
public OBJECT<CODE<T>> object() {
closeAttrs();
return object_(this, true);
}
@Override
public OBJECT<CODE<T>> object(String selector) {
return setSelector(object(), selector);
}
@Override
public SUB<CODE<T>> sub() {
closeAttrs();
return sub_(this, true);
}
@Override
public CODE<T> sub(String cdata) {
return sub().__(cdata).__();
}
@Override
public CODE<T> sub(String selector, String cdata) {
return setSelector(sub(), selector).__(cdata).__();
}
@Override
public SUP<CODE<T>> sup() {
closeAttrs();
return sup_(this, true);
}
@Override
public CODE<T> sup(String cdata) {
return sup().__(cdata).__();
}
@Override
public CODE<T> sup(String selector, String cdata) {
return setSelector(sup(), selector).__(cdata).__();
}
@Override
public MAP<CODE<T>> map() {
closeAttrs();
return map_(this, true);
}
@Override
public MAP<CODE<T>> map(String selector) {
return setSelector(map(), selector);
}
@Override
public CODE<T> q(String cdata) {
return q().__(cdata).__();
}
@Override
public CODE<T> q(String selector, String cdata) {
return setSelector(q(), selector).__(cdata).__();
}
@Override
public Q<CODE<T>> q() {
closeAttrs();
return q_(this, true);
}
@Override
public BR<CODE<T>> br() {
closeAttrs();
return br_(this, true);
}
@Override
public CODE<T> br(String selector) {
return setSelector(br(), selector).__();
}
@Override
public BDO<CODE<T>> bdo() {
closeAttrs();
return bdo_(this, true);
}
@Override
public CODE<T> bdo(Dir dir, String cdata) {
return bdo().$dir(dir).__(cdata).__();
}
@Override
public SPAN<CODE<T>> span() {
closeAttrs();
return span_(this, true);
}
@Override
public CODE<T> span(String cdata) {
return span().__(cdata).__();
}
@Override
public CODE<T> span(String selector, String cdata) {
return setSelector(span(), selector).__(cdata).__();
}
@Override
public SCRIPT<CODE<T>> script() {
closeAttrs();
return script_(this, true);
}
@Override
public CODE<T> script(String src) {
return setScriptSrc(script(), src).__();
}
@Override
public INS<CODE<T>> ins() {
closeAttrs();
return ins_(this, true);
}
@Override
public CODE<T> ins(String cdata) {
return ins().__(cdata).__();
}
@Override
public DEL<CODE<T>> del() {
closeAttrs();
return del_(this, true);
}
@Override
public CODE<T> del(String cdata) {
return del().__(cdata).__();
}
@Override
public LABEL<CODE<T>> label() {
closeAttrs();
return label_(this, true);
}
@Override
public CODE<T> label(String forId, String cdata) {
return label().$for(forId).__(cdata).__();
}
@Override
public INPUT<CODE<T>> input(String selector) {
return setSelector(input(), selector);
}
@Override
public INPUT<CODE<T>> input() {
closeAttrs();
return input_(this, true);
}
@Override
public SELECT<CODE<T>> select() {
closeAttrs();
return select_(this, true);
}
@Override
public SELECT<CODE<T>> select(String selector) {
return setSelector(select(), selector);
}
@Override
public TEXTAREA<CODE<T>> textarea(String selector) {
return setSelector(textarea(), selector);
}
@Override
public TEXTAREA<CODE<T>> textarea() {
closeAttrs();
return textarea_(this, true);
}
@Override
public CODE<T> textarea(String selector, String cdata) {
return setSelector(textarea(), selector).__(cdata).__();
}
@Override
public BUTTON<CODE<T>> button() {
closeAttrs();
return button_(this, true);
}
@Override
public BUTTON<CODE<T>> button(String selector) {
return setSelector(button(), selector);
}
@Override
public CODE<T> button(String selector, String cdata) {
return setSelector(button(), selector).__(cdata).__();
}
}
public | CODE |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/tofix/ExternalTypeIdWithUnwrapped2039Test.java | {
"start": 416,
"end": 936
} | class ____ {
public String text;
@JsonUnwrapped
public Wrapped2039 wrapped;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.EXTERNAL_PROPERTY, property = "subtype")
@JsonSubTypes({@JsonSubTypes.Type(value = SubA2039.class, name = "SubA")})
public SubType2039 sub;
public void setSub(SubType2039 s) {
sub = s;
}
public void setWrapped(Wrapped2039 w) {
wrapped = w;
}
}
static | MainType2039 |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvPercentile.java | {
"start": 6308,
"end": 6445
} | class ____ {
private static final int[] EMPTY = new int[0];
public int[] values = EMPTY;
}
static | IntSortingScratch |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/aggregate/window/processors/AbstractSliceSyncStateWindowAggProcessor.java | {
"start": 2062,
"end": 7900
} | class ____
extends AbstractSyncStateWindowAggProcessor<Long>
implements SlicingSyncStateWindowProcessor<Long> {
protected final WindowBuffer.Factory windowBufferFactory;
protected final SliceAssigner sliceAssigner;
protected final long windowInterval;
// ----------------------------------------------------------------------------------------
/** The next progress to trigger windows. */
private transient long nextTriggerProgress;
protected transient WindowBuffer windowBuffer;
public AbstractSliceSyncStateWindowAggProcessor(
GeneratedNamespaceAggsHandleFunction<Long> genAggsHandler,
WindowBuffer.Factory bufferFactory,
SliceAssigner sliceAssigner,
TypeSerializer<RowData> accSerializer,
int indexOfCountStar,
ZoneId shiftTimeZone) {
super(
genAggsHandler,
sliceAssigner,
accSerializer,
sliceAssigner.isEventTime(),
indexOfCountStar,
shiftTimeZone);
this.windowBufferFactory = bufferFactory;
this.sliceAssigner = sliceAssigner;
this.windowInterval = sliceAssigner.getSliceEndInterval();
}
@Override
public void open(SyncStateContext<Long> context) throws Exception {
super.open(context);
this.windowBuffer =
windowBufferFactory.create(
ctx.getOperatorOwner(),
ctx.getMemoryManager(),
ctx.getMemorySize(),
ctx.getRuntimeContext(),
windowTimerService,
ctx.getKeyedStateBackend(),
windowState,
isEventTime,
shiftTimeZone);
this.nextTriggerProgress = Long.MIN_VALUE;
}
@Override
protected WindowTimerService<Long> getWindowTimerService() {
return new SlicingWindowTimerServiceImpl(ctx.getTimerService(), shiftTimeZone);
}
@Override
public boolean processElement(RowData key, RowData element) throws Exception {
long sliceEnd = sliceAssigner.assignSliceEnd(element, clockService);
if (!isEventTime) {
// always register processing time for every element when processing time mode
windowTimerService.registerProcessingTimeWindowTimer(sliceEnd);
}
if (isEventTime && isWindowFired(sliceEnd, currentProgress, shiftTimeZone)) {
// the assigned slice has been triggered, which means current element is late,
// but maybe not need to drop
long lastWindowEnd = sliceAssigner.getLastWindowEnd(sliceEnd);
if (isWindowFired(lastWindowEnd, currentProgress, shiftTimeZone)) {
// the last window has been triggered, so the element can be dropped now
return true;
} else {
windowBuffer.addElement(key, sliceStateMergeTarget(sliceEnd), element);
// we need to register a timer for the next unfired window,
// because this may the first time we see elements under the key
long unfiredFirstWindow = sliceEnd;
while (isWindowFired(unfiredFirstWindow, currentProgress, shiftTimeZone)) {
unfiredFirstWindow += windowInterval;
}
windowTimerService.registerEventTimeWindowTimer(unfiredFirstWindow);
return false;
}
} else {
// the assigned slice hasn't been triggered, accumulate into the assigned slice
windowBuffer.addElement(key, sliceEnd, element);
return false;
}
}
/**
* Returns the slice state target to merge the given slice into when firing windows. For
* unshared windows, there should no merging happens, so the merge target should be just the
* given {@code sliceToMerge}. For shared windows, the merge target should be the shared slice
* state.
*
* @see SliceSharedAssigner#mergeSlices(long, MergeCallback)
*/
protected abstract long sliceStateMergeTarget(long sliceToMerge) throws Exception;
@Override
public void advanceProgress(long progress) throws Exception {
if (progress > currentProgress) {
currentProgress = progress;
if (currentProgress >= nextTriggerProgress) {
// in order to buffer as much as possible data, we only need to call
// advanceProgress() when currentWatermark may trigger window.
// this is a good optimization when receiving late but un-dropped events, because
// they will register small timers and normal watermark will flush the buffer
windowBuffer.advanceProgress(currentProgress);
nextTriggerProgress =
getNextTriggerWatermark(
currentProgress, windowInterval, shiftTimeZone, useDayLightSaving);
}
}
}
@Override
public void prepareCheckpoint() throws Exception {
windowBuffer.flush();
}
@Override
public void clearWindow(long timerTimestamp, Long windowEnd) throws Exception {
Iterable<Long> expires = sliceAssigner.expiredSlices(windowEnd);
for (Long slice : expires) {
windowState.clear(slice);
aggregator.cleanup(slice);
}
}
@Override
public void close() throws Exception {
super.close();
if (windowBuffer != null) {
windowBuffer.close();
}
}
@Override
public TypeSerializer<Long> createWindowSerializer() {
return LongSerializer.INSTANCE;
}
}
| AbstractSliceSyncStateWindowAggProcessor |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/onetomany/idclass/ManyToManyCompositeKey.java | {
"start": 2114,
"end": 3218
} | class ____ implements Serializable {
private OneToManyOwned oneToMany;
private ManyToOneOwned manyToOne;
ManyToManyId() {
}
ManyToManyId(OneToManyOwned oneToMany, ManyToOneOwned manyToOne) {
this.oneToMany = oneToMany;
this.manyToOne = manyToOne;
}
public OneToManyOwned getOneToMany() {
return this.oneToMany;
}
public ManyToOneOwned getManyToOne() {
return this.manyToOne;
}
@Override
public int hashCode() {
int result = 3;
result = 17 * result + ( oneToMany != null ? oneToMany.hashCode() : 0 );
result = 17 * result + ( manyToOne != null ? manyToOne.hashCode() : 0 );
return result;
}
@Override
public boolean equals(Object obj) {
if( this == obj ) {
return true;
}
if( !( obj instanceof ManyToManyId ) ) {
return false;
}
ManyToManyId m = (ManyToManyId) obj;
if ( oneToMany != null ? !oneToMany.equals( m.oneToMany ) : m.oneToMany != null ) {
return false;
}
if ( manyToOne != null ? !manyToOne.equals( m.manyToOne ) : m.manyToOne != null ) {
return false;
}
return true;
}
}
}
| ManyToManyId |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/annotations/sharedfk/ConcreteChild1.java | {
"start": 340,
"end": 454
} | class ____ extends AbstractChild {
@Basic(optional = false)
@Column(name = "VALUE1")
String value;
}
| ConcreteChild1 |
java | apache__maven | impl/maven-di/src/main/java/org/apache/maven/di/impl/InjectorImpl.java | {
"start": 16826,
"end": 18536
} | class ____ implements Scope {
Map<Key<?>, java.util.function.Supplier<?>> cache = new ConcurrentHashMap<>();
@Nonnull
@SuppressWarnings("unchecked")
@Override
public <T> java.util.function.Supplier<T> scope(
@Nonnull Key<T> key, @Nonnull java.util.function.Supplier<T> unscoped) {
return (java.util.function.Supplier<T>)
cache.computeIfAbsent(key, k -> new java.util.function.Supplier<T>() {
volatile T instance;
@Override
public T get() {
if (instance == null) {
synchronized (this) {
if (instance == null) {
instance = unscoped.get();
}
}
}
return instance;
}
});
}
}
/**
* Release all internal state so this Injector can be GC’d
* (and so that subsequent tests start from a clean slate).
* @since 4.1
*/
public void dispose() {
// First, clear any singleton‐scope caches
scopes.values().stream()
.map(Supplier::get)
.filter(scope -> scope instanceof SingletonScope)
.map(scope -> (SingletonScope) scope)
.forEach(singleton -> singleton.cache.clear());
// Now clear everything else
bindings.clear();
scopes.clear();
loadedUrls.clear();
resolutionStack.remove();
}
}
| SingletonScope |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/factory/config/ConfigurableListableBeanFactory.java | {
"start": 2115,
"end": 2408
} | interface ____ autowiring.
* <p>This will typically be used by application contexts to register
* dependencies that are resolved in other ways, like BeanFactory through
* BeanFactoryAware or ApplicationContext through ApplicationContextAware.
* <p>By default, only the BeanFactoryAware | for |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/onetomany/inheritance/joined/Library.java | {
"start": 501,
"end": 1377
} | class ____ {
@Id
@GeneratedValue
private int entid;
@OneToMany(mappedBy="library", cascade = CascadeType.ALL)
@MapKey(name="inventoryCode")
private Map<String,Book> booksOnInventory = new HashMap<>();
@OneToMany(mappedBy="library", cascade = CascadeType.ALL)
@MapKey(name="isbn")
private Map<String,Book> booksOnIsbn = new HashMap<>();
public int getEntid() {
return entid;
}
public Map<String,Book> getBooksOnInventory() {
return booksOnInventory;
}
public Map<String, Book> getBooksOnIsbn() {
return booksOnIsbn;
}
public void addBook(Book book) {
book.setLibrary( this );
booksOnInventory.put( book.getInventoryCode(), book );
booksOnIsbn.put( book.getIsbn(), book );
}
public void removeBook(Book book) {
book.setLibrary( null );
booksOnInventory.remove( book.getInventoryCode() );
booksOnIsbn.remove( book.getIsbn() );
}
}
| Library |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configuration/HttpSecurityConfigurationTests.java | {
"start": 34565,
"end": 34943
} | class ____ {
@Bean
SecurityFilterChain springSecurity(HttpSecurity http) throws Exception {
http.httpBasic(withDefaults());
return http.build();
}
@Bean
static Customizer<HttpSecurity> httpSecurityCustomizer() {
return mock(Customizer.class, withSettings().name("httpSecurityCustomizer"));
}
@RestController
static | HttpSecurityCustomizerBeanConfiguration |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/streaming/api/functions/source/FileProcessingMode.java | {
"start": 1198,
"end": 1389
} | enum ____ {
/** Processes the current contents of the path and exits. */
PROCESS_ONCE,
/** Periodically scans the path for new data. */
PROCESS_CONTINUOUSLY
}
| FileProcessingMode |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/util/LoaderUtil.java | {
"start": 7946,
"end": 8202
} | class ____ name. This method respects the {@link #IGNORE_TCCL_PROPERTY} Log4j property. If this property is
* specified and set to anything besides {@code false}, then the default ClassLoader will be used.
*
* @param className fully qualified | by |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/AntlrVersionTests.java | {
"start": 1501,
"end": 2173
} | class ____ {
@Test
@DisabledOnHibernate("6.2")
void antlrVersionConvergence() throws Exception {
ClassReader reader = new ClassReader(HqlParser.class.getName());
ExpectedAntlrVersionVisitor visitor = new ExpectedAntlrVersionVisitor();
reader.accept(visitor, 0);
String expectedVersion = visitor.getExpectedVersion();
String description = String.format("ANTLR version '%s' expected by Hibernate while our ANTLR version '%s'",
expectedVersion, RuntimeMetaData.VERSION);
assertThat(expectedVersion).isNotNull();
assertThat(RuntimeMetaData.VERSION) //
.describedAs(description) //
.isEqualTo(expectedVersion);
}
private static | AntlrVersionTests |
java | spring-projects__spring-boot | module/spring-boot-security-oauth2-client/src/test/java/org/springframework/boot/security/oauth2/client/autoconfigure/servlet/OAuth2ClientWebSecurityAutoConfigurationTests.java | {
"start": 9593,
"end": 9984
} | class ____ {
@Bean
InMemoryOAuth2AuthorizedClientService authorizedClientService(
ClientRegistrationRepository clientRegistrationRepository) {
return new InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository);
}
}
@Configuration(proxyBeanMethods = false)
@Import(OAuth2AuthorizedClientServiceConfiguration.class)
static | OAuth2AuthorizedClientServiceConfiguration |
java | apache__kafka | metadata/src/main/java/org/apache/kafka/controller/BrokersToElrs.java | {
"start": 1131,
"end": 5941
} | class ____ {
private final SnapshotRegistry snapshotRegistry;
// It maps from the broker id to the topic id partitions if the partition has ELR.
private final TimelineHashMap<Integer, TimelineHashMap<Uuid, int[]>> elrMembers;
BrokersToElrs(SnapshotRegistry snapshotRegistry) {
this.snapshotRegistry = snapshotRegistry;
this.elrMembers = new TimelineHashMap<>(snapshotRegistry, 0);
}
/**
* Update our records of a partition's ELR.
*
* @param topicId The topic ID of the partition.
* @param partitionId The partition ID of the partition.
* @param prevElr The previous ELR, or null if the partition is new.
* @param nextElr The new ELR, or null if the partition is being removed.
*/
void update(Uuid topicId, int partitionId, int[] prevElr, int[] nextElr) {
int[] prev;
if (prevElr == null) {
prev = NONE;
} else {
prev = Replicas.clone(prevElr);
Arrays.sort(prev);
}
int[] next;
if (nextElr == null) {
next = NONE;
} else {
next = Replicas.clone(nextElr);
Arrays.sort(next);
}
int i = 0, j = 0;
while (true) {
if (i == prev.length) {
if (j == next.length) {
break;
}
int newReplica = next[j];
add(newReplica, topicId, partitionId);
j++;
} else if (j == next.length) {
int prevReplica = prev[i];
remove(prevReplica, topicId, partitionId);
i++;
} else {
int prevReplica = prev[i];
int newReplica = next[j];
if (prevReplica < newReplica) {
remove(prevReplica, topicId, partitionId);
i++;
} else if (prevReplica > newReplica) {
add(newReplica, topicId, partitionId);
j++;
} else {
i++;
j++;
}
}
}
}
void removeTopicEntryForBroker(Uuid topicId, int brokerId) {
Map<Uuid, int[]> topicMap = elrMembers.get(brokerId);
if (topicMap != null) {
topicMap.remove(topicId);
}
}
private void add(int brokerId, Uuid topicId, int newPartition) {
TimelineHashMap<Uuid, int[]> topicMap = elrMembers.get(brokerId);
if (topicMap == null) {
topicMap = new TimelineHashMap<>(snapshotRegistry, 0);
elrMembers.put(brokerId, topicMap);
}
int[] partitions = topicMap.get(topicId);
int[] newPartitions;
if (partitions == null) {
newPartitions = new int[1];
} else {
newPartitions = new int[partitions.length + 1];
System.arraycopy(partitions, 0, newPartitions, 0, partitions.length);
}
newPartitions[newPartitions.length - 1] = newPartition;
topicMap.put(topicId, newPartitions);
}
private void remove(int brokerId, Uuid topicId, int removedPartition) {
TimelineHashMap<Uuid, int[]> topicMap = elrMembers.get(brokerId);
if (topicMap == null) {
throw new RuntimeException("Broker " + brokerId + " has no elrMembers " +
"entry, so we can't remove " + topicId + ":" + removedPartition);
}
int[] partitions = topicMap.get(topicId);
if (partitions == null) {
throw new RuntimeException("Broker " + brokerId + " has no " +
"entry in elrMembers for topic " + topicId);
}
if (partitions.length == 1) {
if (partitions[0] != removedPartition) {
throw new RuntimeException("Broker " + brokerId + " has no " +
"entry in elrMembers for " + topicId + ":" + removedPartition);
}
topicMap.remove(topicId);
if (topicMap.isEmpty()) {
elrMembers.remove(brokerId);
}
} else {
int[] newPartitions = new int[partitions.length - 1];
int i = 0;
for (int partition : partitions) {
if (partition != removedPartition) {
newPartitions[i++] = partition;
}
}
topicMap.put(topicId, newPartitions);
}
}
BrokersToIsrs.PartitionsOnReplicaIterator partitionsWithBrokerInElr(int brokerId) {
Map<Uuid, int[]> topicMap = elrMembers.get(brokerId);
if (topicMap == null) {
topicMap = Map.of();
}
return new BrokersToIsrs.PartitionsOnReplicaIterator(topicMap, false);
}
}
| BrokersToElrs |
java | google__dagger | javatests/dagger/internal/codegen/MembersInjectionTest.java | {
"start": 23597,
"end": 24105
} | class ____ extends BaseClass {",
" @Inject int field;",
" }",
"}");
CompilerTests.daggerCompiler(file)
.withProcessingOptions(compilerMode.processorOptions())
.compile(subject -> subject.hasErrorCount(0));
}
@Test
public void throwExceptionInjectedMethod() {
Source file =
CompilerTests.javaSource(
"test.",
"package test;",
"",
"import javax.inject.Inject;",
" | DerivedClass |
java | google__guava | android/guava-testlib/src/com/google/common/testing/AbstractPackageSanityTests.java | {
"start": 3803,
"end": 4186
} | class ____ IO because it scans the classpath and reads classpath resources.
*
* @author Ben Yu
* @since 14.0
*/
// TODO: Switch to JUnit 4 and use @Parameterized and @BeforeClass
// Note: @Test annotations are deliberate, as some subclasses specify @RunWith(JUnit4).
@GwtIncompatible
@J2ktIncompatible
@J2ObjCIncompatible // com.google.common.reflect.ClassPath
public abstract | incurs |
java | quarkusio__quarkus | core/processor/src/main/java/io/quarkus/annotation/processor/documentation/config/resolver/ConfigResolver.java | {
"start": 2940,
"end": 14226
} | class ____ {
private final Config config;
private final Utils utils;
private final ConfigCollector configCollector;
public ConfigResolver(Config config, Utils utils, ConfigCollector configCollector) {
this.config = config;
this.utils = utils;
this.configCollector = configCollector;
}
public JavadocElements resolveJavadoc() {
return new JavadocElements(config.getExtension(), configCollector.getJavadocElements());
}
public ResolvedModel resolveModel() {
List<ConfigRoot> configRoots = new ArrayList<>();
for (DiscoveryConfigRoot discoveryConfigRoot : configCollector.getConfigRoots()) {
ConfigRoot configRoot = new ConfigRoot(discoveryConfigRoot.getExtension(), discoveryConfigRoot.getPrefix(),
discoveryConfigRoot.getOverriddenDocPrefix(), discoveryConfigRoot.getOverriddenDocFileName());
Map<String, ConfigSection> existingRootConfigSections = new TreeMap<>();
configRoot.addQualifiedName(discoveryConfigRoot.getQualifiedName());
ResolutionContext context = new ResolutionContext(configRoot.getPrefix(), new ArrayList<>(), discoveryConfigRoot,
configRoot, 0, false, false, null);
for (DiscoveryConfigProperty discoveryConfigProperty : discoveryConfigRoot.getProperties().values()) {
resolveProperty(configRoot, existingRootConfigSections, discoveryConfigRoot.getPhase(), context,
discoveryConfigProperty);
}
configRoots.add(configRoot);
}
return new ResolvedModel(configRoots);
}
private void resolveProperty(ConfigRoot configRoot, Map<String, ConfigSection> existingRootConfigSections,
ConfigPhase phase, ResolutionContext context, DiscoveryConfigProperty discoveryConfigProperty) {
String path = appendPath(context.getPath(), discoveryConfigProperty.getPath());
List<String> additionalPaths = context.getAdditionalPaths().stream()
.map(p -> appendPath(p, discoveryConfigProperty.getPath()))
.collect(Collectors.toCollection(ArrayList::new));
Deprecation deprecation = discoveryConfigProperty.getDeprecation() != null ? discoveryConfigProperty.getDeprecation()
: context.getDeprecation();
String typeQualifiedName = discoveryConfigProperty.getType().qualifiedName();
if (configCollector.isResolvedConfigGroup(typeQualifiedName)) {
DiscoveryConfigGroup discoveryConfigGroup = configCollector.getResolvedConfigGroup(typeQualifiedName);
String potentiallyMappedPath = path;
if (discoveryConfigProperty.getType().isMap()) {
if (discoveryConfigProperty.isUnnamedMapKey()) {
ListIterator<String> additionalPathsIterator = additionalPaths.listIterator();
additionalPathsIterator
.add(path + ConfigNamingUtil.getMapKey(discoveryConfigProperty.getMapKey()));
while (additionalPathsIterator.hasNext()) {
additionalPathsIterator.add(additionalPathsIterator.next()
+ ConfigNamingUtil.getMapKey(discoveryConfigProperty.getMapKey()));
}
} else {
potentiallyMappedPath += ConfigNamingUtil.getMapKey(discoveryConfigProperty.getMapKey());
additionalPaths = additionalPaths.stream()
.map(p -> p + ConfigNamingUtil.getMapKey(discoveryConfigProperty.getMapKey()))
.collect(Collectors.toCollection(ArrayList::new));
}
}
ResolutionContext configGroupContext;
boolean isWithinMap = context.isWithinMap() || discoveryConfigProperty.getType().isMap();
boolean isWithMapWithUnnamedKey = context.isWithinMapWithUnnamedKey() || discoveryConfigProperty.isUnnamedMapKey();
if (discoveryConfigProperty.isSection()) {
ConfigSection configSection = existingRootConfigSections.get(path);
if (configSection != null) {
configSection.appendState(discoveryConfigProperty.isSectionGenerated(), deprecation);
} else {
configSection = new ConfigSection(discoveryConfigProperty.getSourceType(),
discoveryConfigProperty.getSourceElementName(), discoveryConfigProperty.getSourceElementType(),
new SectionPath(path), typeQualifiedName,
context.getSectionLevel(), discoveryConfigProperty.isSectionGenerated(), deprecation);
context.getItemCollection().addItem(configSection);
existingRootConfigSections.put(path, configSection);
}
configGroupContext = new ResolutionContext(potentiallyMappedPath, additionalPaths, discoveryConfigGroup,
configSection, context.getSectionLevel() + 1, isWithinMap, isWithMapWithUnnamedKey, deprecation);
} else {
configGroupContext = new ResolutionContext(potentiallyMappedPath, additionalPaths, discoveryConfigGroup,
context.getItemCollection(), context.getSectionLevel(), isWithinMap, isWithMapWithUnnamedKey,
deprecation);
}
for (DiscoveryConfigProperty configGroupProperty : discoveryConfigGroup.getProperties().values()) {
resolveProperty(configRoot, existingRootConfigSections, phase, configGroupContext, configGroupProperty);
}
} else {
String typeBinaryName = discoveryConfigProperty.getType().binaryName();
String typeSimplifiedName = discoveryConfigProperty.getType().simplifiedName();
// if the property has a converter, we don't hyphenate the values (per historical rules, not exactly sure of the reason)
boolean hyphenateEnumValues = discoveryConfigProperty.isEnforceHyphenateEnumValue() ||
!discoveryConfigProperty.isConverted();
String defaultValue = getDefaultValue(discoveryConfigProperty.getDefaultValue(),
discoveryConfigProperty.getDefaultValueForDoc(), discoveryConfigProperty.getType(), hyphenateEnumValues);
EnumAcceptedValues enumAcceptedValues = null;
if (discoveryConfigProperty.getType().isEnum()) {
EnumDefinition enumDefinition = configCollector.getResolvedEnum(typeQualifiedName);
Map<String, EnumAcceptedValue> localAcceptedValues = enumDefinition.constants().entrySet().stream()
.collect(Collectors.toMap(
e -> e.getKey(),
e -> new EnumAcceptedValue(e.getValue().hasExplicitValue() ? e.getValue().explicitValue()
: (hyphenateEnumValues ? ConfigNamingUtil.hyphenateEnumValue(e.getKey())
: e.getKey())),
(x, y) -> y, LinkedHashMap::new));
enumAcceptedValues = new EnumAcceptedValues(enumDefinition.qualifiedName(), localAcceptedValues);
}
String potentiallyMappedPath = path;
boolean optional = discoveryConfigProperty.getType().isOptional();
boolean secret = discoveryConfigProperty.getType().isSecret();
if (discoveryConfigProperty.getType().isMap()) {
// it is a leaf pass through map, it is always optional
optional = true;
typeQualifiedName = utils.element().getQualifiedName(discoveryConfigProperty.getType().wrapperType());
typeSimplifiedName = utils.element().simplifyGenericType(discoveryConfigProperty.getType().wrapperType());
potentiallyMappedPath += ConfigNamingUtil.getMapKey(discoveryConfigProperty.getMapKey());
additionalPaths = additionalPaths.stream()
.map(p -> p + ConfigNamingUtil.getMapKey(discoveryConfigProperty.getMapKey()))
.collect(Collectors.toCollection(ArrayList::new));
} else if (discoveryConfigProperty.getType().isList()) {
typeQualifiedName = utils.element().getQualifiedName(discoveryConfigProperty.getType().wrapperType());
}
PropertyPath propertyPath = new PropertyPath(potentiallyMappedPath,
ConfigNamingUtil.toEnvVarName(potentiallyMappedPath));
List<PropertyPath> additionalPropertyPaths = additionalPaths.stream()
.map(ap -> new PropertyPath(ap, ConfigNamingUtil.toEnvVarName(ap)))
.toList();
// this is a standard property
ConfigProperty configProperty = new ConfigProperty(phase,
discoveryConfigProperty.getSourceType(),
discoveryConfigProperty.getSourceElementName(),
discoveryConfigProperty.getSourceElementType(),
propertyPath, additionalPropertyPaths,
typeQualifiedName, typeSimplifiedName,
discoveryConfigProperty.getType().isMap(), discoveryConfigProperty.getType().isList(),
optional, secret, discoveryConfigProperty.getMapKey(),
discoveryConfigProperty.isUnnamedMapKey(), context.isWithinMap(),
discoveryConfigProperty.isConverted(),
discoveryConfigProperty.getType().isEnum(),
enumAcceptedValues, defaultValue, discoveryConfigProperty.isEscapeDefaultValueForDoc(),
JavadocUtil.getJavadocSiteLink(typeBinaryName),
deprecation);
context.getItemCollection().addItem(configProperty);
}
}
public static String getDefaultValue(String defaultValue, String defaultValueForDoc, ResolvedType type,
boolean hyphenateEnumValues) {
if (!Strings.isBlank(defaultValueForDoc)) {
return defaultValueForDoc;
}
if (defaultValue == null) {
return null;
}
if (type.isEnum() && hyphenateEnumValues) {
if (type.isList()) {
return Arrays.stream(defaultValue.split(Markers.COMMA))
.map(v -> ConfigNamingUtil.hyphenateEnumValue(v.trim()))
.collect(Collectors.joining(Markers.COMMA));
} else {
return ConfigNamingUtil.hyphenateEnumValue(defaultValue.trim());
}
}
return defaultValue;
}
public static String getType(TypeMirror typeMirror) {
if (typeMirror instanceof DeclaredType declaredType) {
TypeElement typeElement = (TypeElement) declaredType.asElement();
return typeElement.getQualifiedName().toString();
}
return typeMirror.toString();
}
public static String appendPath(String parentPath, String path) {
return Markers.PARENT.equals(path) ? parentPath : parentPath + Markers.DOT + path;
}
private static | ConfigResolver |
java | junit-team__junit5 | jupiter-tests/src/test/java/org/junit/jupiter/api/extension/CloseableResourceIntegrationTests.java | {
"start": 3110,
"end": 3321
} | class ____ implements ExtensionContext.Store.CloseableResource, AutoCloseable {
@Override
public void close() throws Exception {
throw new RuntimeException("Exception in onClose");
}
}
}
| ThrowingResource |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/resume/ResumeStrategy.java | {
"start": 1030,
"end": 1190
} | interface ____ extends Service {
/**
* A callback that can be executed after the last offset is updated
*/
@FunctionalInterface
| ResumeStrategy |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/FluxContextWriteRestoringThreadLocalsFuseable.java | {
"start": 979,
"end": 1896
} | class ____<T> extends FluxOperator<T, T>
implements Fuseable {
final Function<Context, Context> doOnContext;
FluxContextWriteRestoringThreadLocalsFuseable(Flux<? extends T> source,
Function<Context, Context> doOnContext) {
super(source);
this.doOnContext = Objects.requireNonNull(doOnContext, "doOnContext");
}
@SuppressWarnings("try")
@Override
public void subscribe(CoreSubscriber<? super T> actual) {
Context c = doOnContext.apply(actual.currentContext());
try (ContextSnapshot.Scope ignored = ContextPropagation.setThreadLocals(c)) {
source.subscribe(new FuseableContextWriteRestoringThreadLocalsSubscriber<>(actual, c));
}
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
if (key == InternalProducerAttr.INSTANCE) return true;
return super.scanUnsafe(key);
}
static | FluxContextWriteRestoringThreadLocalsFuseable |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/operator/topn/KeyExtractorForInt.java | {
"start": 647,
"end": 2208
} | class ____ implements KeyExtractor {
static KeyExtractorForInt extractorFor(TopNEncoder encoder, boolean ascending, byte nul, byte nonNul, IntBlock block) {
IntVector v = block.asVector();
if (v != null) {
return new KeyExtractorForInt.FromVector(encoder, nul, nonNul, v);
}
if (ascending) {
return block.mvSortedAscending()
? new KeyExtractorForInt.MinFromAscendingBlock(encoder, nul, nonNul, block)
: new KeyExtractorForInt.MinFromUnorderedBlock(encoder, nul, nonNul, block);
}
return block.mvSortedAscending()
? new KeyExtractorForInt.MaxFromAscendingBlock(encoder, nul, nonNul, block)
: new KeyExtractorForInt.MaxFromUnorderedBlock(encoder, nul, nonNul, block);
}
private final byte nul;
private final byte nonNul;
KeyExtractorForInt(TopNEncoder encoder, byte nul, byte nonNul) {
assert encoder == TopNEncoder.DEFAULT_SORTABLE;
this.nul = nul;
this.nonNul = nonNul;
}
protected final int nonNul(BreakingBytesRefBuilder key, int value) {
key.append(nonNul);
TopNEncoder.DEFAULT_SORTABLE.encodeInt(value, key);
return Integer.BYTES + 1;
}
protected final int nul(BreakingBytesRefBuilder key) {
key.append(nul);
return 1;
}
@Override
public final String toString() {
return String.format(Locale.ROOT, "KeyExtractorForInt%s(%s, %s)", getClass().getSimpleName(), nul, nonNul);
}
static | KeyExtractorForInt |
java | elastic__elasticsearch | x-pack/plugin/security/qa/profile/src/javaRestTest/java/org/elasticsearch/xpack/security/profile/ProfileIT.java | {
"start": 2100,
"end": 34772
} | class ____ extends ESRestTestCase {
@ClassRule
public static ElasticsearchCluster cluster = createCluster();
private static ElasticsearchCluster createCluster() {
LocalClusterSpecBuilder<ElasticsearchCluster> clusterBuilder = ElasticsearchCluster.local()
.nodes(2)
.distribution(DistributionType.DEFAULT)
.rolesFile(Resource.fromClasspath("roles.yml"))
.setting("xpack.license.self_generated.type", "trial")
.setting("xpack.security.enabled", "true")
.setting("xpack.ml.enabled", "false")
.setting("xpack.security.authc.token.enabled", "true")
.setting("xpack.security.authc.api_key.enabled", "true")
.setting("xpack.security.authc.realms.ldap.ldap1.enabled", "false")
.setting("xpack.security.authc.domains.my_domain.realms", "default_file,ldap1")
.setting("xpack.security.authc.realms.saml.saml1.enabled", "false")
.setting("xpack.security.authc.realms.active_directory.ad1.enabled", "false")
.setting("xpack.security.authc.domains.other_domain.realms", "saml1,ad1")
// Ensure new cache setting is recognised
.setting("xpack.security.authz.store.roles.has_privileges.cache.max_size", "100")
.user("test-admin", "x-pack-test-password")
.user("rac-user", "x-pack-test-password", "rac_user_role", false);
if (Booleans.parseBoolean(System.getProperty("test.literalUsername"))) {
clusterBuilder.setting("xpack.security.authc.domains.my_domain.uid_generation.literal_username", "true")
.setting("xpack.security.authc.domains.my_domain.uid_generation.suffix", "es");
}
return clusterBuilder.build();
}
@Override
protected String getTestRestCluster() {
return cluster.getHttpAddresses();
}
@Override
protected Settings restAdminSettings() {
return Settings.builder()
.put(
ThreadContext.PREFIX + ".Authorization",
basicAuthHeaderValue("test-admin", new SecureString("x-pack-test-password".toCharArray()))
)
.build();
}
public static final String SAMPLE_PROFILE_DOCUMENT_TEMPLATE = """
{
"user_profile": {
"uid": "%s",
"enabled": true,
"user": {
"username": "%s",
"roles": [
"role1",
"role2"
],
"realm": {
"name": "realm_name_1",
"type": "realm_type_1",
"domain": {
"name": "domainA",
"realms": [
{ "name": "realm_name_1", "type": "realm_type_1" },
{ "name": "realm_name_2", "type": "realm_type_2" }
]
},
"node_name": "node1"
},
"email": "foo@example.com",
"full_name": "User Foo"
},
"last_synchronized": %s,
"labels": {
},
"application_data": {
"app1": { "name": "app1" },
"app2": { "name": "app2" }
}
}
}
""";
public void testActivateProfile() throws IOException {
final Map<String, Object> activateProfileMap = doActivateProfile();
final String profileUid = (String) activateProfileMap.get("uid");
final Map<String, Object> profile1 = doGetProfile(profileUid);
assertThat(profile1, equalTo(activateProfileMap));
}
@SuppressWarnings("unchecked")
public void testProfileHasPrivileges() throws IOException {
final Map<String, Object> activateProfileMap = doActivateProfile();
final String profileUid = (String) activateProfileMap.get("uid");
final Request profileHasPrivilegesRequest = new Request("POST", "_security/profile/_has_privileges");
profileHasPrivilegesRequest.setJsonEntity(Strings.format("""
{
"uids": ["some_missing_profile", "%s"],
"privileges": {
"index": [
{
"names": [ "rac_index_1" ],
"privileges": [ "read" ]
}
],
"cluster": [
"cluster:monitor/health"
]
}
}""", profileUid));
final Response profileHasPrivilegesResponse = adminClient().performRequest(profileHasPrivilegesRequest);
assertOK(profileHasPrivilegesResponse);
Map<String, Object> profileHasPrivilegesResponseMap = responseAsMap(profileHasPrivilegesResponse);
assertThat(profileHasPrivilegesResponseMap.keySet(), contains("has_privilege_uids", "errors"));
assertThat(((List<String>) profileHasPrivilegesResponseMap.get("has_privilege_uids")), contains(profileUid));
assertThat(
profileHasPrivilegesResponseMap.get("errors"),
equalTo(
Map.of(
"count",
1,
"details",
Map.of("some_missing_profile", Map.of("type", "resource_not_found_exception", "reason", "profile document not found"))
)
)
);
}
public void testGetProfiles() throws IOException {
final List<String> uids = randomList(1, 3, () -> randomAlphaOfLength(20));
// Profile index does not exist yet
final Map<String, Object> responseMap0 = doGetProfiles(uids, null);
@SuppressWarnings("unchecked")
final List<Object> profiles0 = (List<Object>) responseMap0.get("profiles");
assertThat(profiles0, empty());
final Map<String, Object> errors0 = castToMap(responseMap0.get("errors"));
assertThat(errors0.get("count"), equalTo(uids.size()));
final Map<String, Object> errorDetails0 = castToMap(errors0.get("details"));
assertThat(errorDetails0.keySet(), equalTo(Set.copyOf(uids)));
errorDetails0.values().forEach(value -> assertThat(castToMap(value).get("reason"), equalTo("profile index does not exist")));
// Create the profile documents
for (String uid : uids) {
final String source = Strings.format(SAMPLE_PROFILE_DOCUMENT_TEMPLATE, uid, uid, Instant.now().toEpochMilli());
final Request indexRequest = new Request("PUT", ".security-profile/_doc/profile_" + uid);
indexRequest.setJsonEntity(source);
indexRequest.addParameter("refresh", "wait_for");
indexRequest.setOptions(
expectWarnings(
"this request accesses system indices: [.security-profile-8], but in a future major version, "
+ "direct access to system indices will be prevented by default"
).toBuilder().addHeader("X-elastic-product-origin", "elastic")
);
assertOK(adminClient().performRequest(indexRequest));
}
// Now retrieve profiles created above
final Map<String, Object> responseMap1 = doGetProfiles(uids, null);
@SuppressWarnings("unchecked")
final List<Map<String, Object>> profiles1 = (List<Map<String, Object>>) responseMap1.get("profiles");
assertThat(profiles1.size(), equalTo(uids.size()));
IntStream.range(0, profiles1.size()).forEach(i -> {
final Map<String, Object> profileMap = profiles1.get(i);
final String uid = uids.get(i);
assertThat(profileMap.get("uid"), equalTo(uid));
assertThat(castToMap(profileMap.get("user")).get("username"), equalTo(uid));
assertThat(castToMap(profileMap.get("user")).get("realm_name"), equalTo("realm_name_1"));
assertThat(castToMap(profileMap.get("user")).get("realm_domain"), equalTo("domainA"));
assertThat(castToMap(profileMap.get("data")), anEmptyMap());
});
// Retrieve application data along the profile
final Map<String, Object> responseMap2 = doGetProfiles(uids, "app1");
@SuppressWarnings("unchecked")
final List<Map<String, Object>> profiles2 = (List<Map<String, Object>>) responseMap2.get("profiles");
assertThat(profiles2.size(), equalTo(uids.size()));
IntStream.range(0, profiles2.size()).forEach(i -> {
final Map<String, Object> profileMap = profiles2.get(i);
assertThat(castToMap(profileMap.get("data")), equalTo(Map.of("app1", Map.of("name", "app1"))));
});
// Retrieve multiple application data
final Map<String, Object> responseMap3 = doGetProfiles(uids, randomFrom("app1,app2", "*", "app*"));
@SuppressWarnings("unchecked")
final List<Map<String, Object>> profiles3 = (List<Map<String, Object>>) responseMap3.get("profiles");
assertThat(profiles3.size(), equalTo(uids.size()));
IntStream.range(0, profiles3.size()).forEach(i -> {
final Map<String, Object> profileMap = profiles3.get(i);
assertThat(castToMap(profileMap.get("data")), equalTo(Map.of("app1", Map.of("name", "app1"), "app2", Map.of("name", "app2"))));
});
// Non-existing profiles
final List<String> notUids = uids.stream().map(uid -> "not_" + uid).toList();
final Map<String, Object> responseMap4 = doGetProfiles(notUids, null);
@SuppressWarnings("unchecked")
final List<Object> profiles4 = (List<Object>) responseMap4.get("profiles");
assertThat(profiles4, empty());
final Map<String, Object> errors4 = castToMap(responseMap4.get("errors"));
assertThat(errors4.get("count"), equalTo(notUids.size()));
final Map<String, Object> errorDetails4 = castToMap(errors4.get("details"));
assertThat(errorDetails4.keySet(), equalTo(Set.copyOf(notUids)));
errorDetails4.values().forEach(value -> assertThat(castToMap(value).get("type"), equalTo("resource_not_found_exception")));
}
public void testStoreProfileData() throws IOException {
final Map<String, Object> activateProfileMap = doActivateProfile();
final String uid = (String) activateProfileMap.get("uid");
final Request updateProfileRequest = new Request(randomFrom("PUT", "POST"), "_security/profile/" + uid + "/_data");
updateProfileRequest.setJsonEntity("""
{
"labels": {
"app1": { "tags": [ "prod", "east" ] }
},
"data": {
"app1": { "theme": "default" }
}
}""");
assertOK(adminClient().performRequest(updateProfileRequest));
final Map<String, Object> profileMap = doGetProfile(uid, "app1");
assertThat(castToMap(profileMap.get("labels")), equalTo(Map.of("app1", Map.of("tags", List.of("prod", "east")))));
assertThat(castToMap(profileMap.get("data")), equalTo(Map.of("app1", Map.of("theme", "default"))));
}
public void testModifyProfileData() throws IOException {
final Map<String, Object> activateProfileMap = doActivateProfile();
final String uid = (String) activateProfileMap.get("uid");
final String endpoint = "_security/profile/" + uid + "/_data";
final String appName1 = randomAlphaOfLengthBetween(3, 5);
final String appName2 = randomAlphaOfLengthBetween(6, 8);
final List<String> tags = randomList(1, 5, () -> randomAlphaOfLengthBetween(4, 12));
final String labelKey = randomAlphaOfLengthBetween(4, 6);
final String dataKey1 = randomAlphaOfLengthBetween(3, 5);
final String dataKey2 = randomAlphaOfLengthBetween(6, 8);
final String dataKey3 = randomAlphaOfLengthBetween(9, 10);
final String dataValue1a = randomAlphaOfLengthBetween(6, 9);
final String dataValue1b = randomAlphaOfLengthBetween(10, 12);
final String dataValue2 = randomAlphaOfLengthBetween(6, 12);
final String dataValue3 = randomAlphaOfLengthBetween(4, 10);
// Store the data
{
final Request updateProfileRequest = new Request(randomFrom("PUT", "POST"), endpoint);
final Map<String, String> dataBlock = Map.ofEntries(
// { k1: v1, k2: v2 }
Map.entry(dataKey1, dataValue1a),
Map.entry(dataKey2, dataValue2)
);
updateProfileRequest.setJsonEntity(
toJson(
Map.ofEntries(
Map.entry("labels", Map.of(appName1, Map.of(labelKey, tags))),
// Store the same data under both app-names
Map.entry("data", Map.of(appName1, dataBlock, appName2, dataBlock))
)
)
);
assertOK(adminClient().performRequest(updateProfileRequest));
final Map<String, Object> profileMap1 = doGetProfile(uid, appName1);
logger.info("Profile Map [{}][app={}] : {}", getTestName(), appName1, profileMap1);
assertThat(ObjectPath.eval("labels." + appName1 + "." + labelKey, profileMap1), equalTo(tags));
assertThat(ObjectPath.eval("data." + appName1 + "." + dataKey1, profileMap1), equalTo(dataValue1a));
assertThat(ObjectPath.eval("data." + appName1 + "." + dataKey2, profileMap1), equalTo(dataValue2));
final Map<String, Object> profileMap2 = doGetProfile(uid, appName2);
logger.info("Profile Map [{}][app={}] : {}", getTestName(), appName2, profileMap2);
assertThat(ObjectPath.eval("data." + appName2 + "." + dataKey1, profileMap2), equalTo(dataValue1a));
assertThat(ObjectPath.eval("data." + appName2 + "." + dataKey2, profileMap2), equalTo(dataValue2));
}
// Store modified data
{
// Add a new tag, remove an old one
final String newTag = randomValueOtherThanMany(tags::contains, () -> randomAlphaOfLengthBetween(3, 9));
tags.remove(randomFrom(tags));
tags.add(newTag);
final Request updateProfileRequest = new Request(randomFrom("PUT", "POST"), endpoint);
final Map<String, String> dataBlock = Map.ofEntries(
// { k1: v1b, k3: v3 }
Map.entry(dataKey1, dataValue1b),
Map.entry(dataKey3, dataValue3)
);
updateProfileRequest.setJsonEntity(
toJson(
Map.ofEntries(
Map.entry("labels", Map.of(appName1, Map.of(labelKey, tags))),
// We don't make any changes to appName2, so it should keep the original data
Map.entry("data", Map.of(appName1, dataBlock))
)
)
);
assertOK(adminClient().performRequest(updateProfileRequest));
final Map<String, Object> profileMap1 = doGetProfile(uid, appName1);
logger.info("Profile Map [{}][app={}] : {}", getTestName(), appName1, profileMap1);
assertThat(ObjectPath.eval("labels." + appName1 + "." + labelKey, profileMap1), equalTo(tags));
assertThat(ObjectPath.eval("data." + appName1 + "." + dataKey1, profileMap1), equalTo(dataValue1b));
assertThat(ObjectPath.eval("data." + appName1 + "." + dataKey2, profileMap1), equalTo(dataValue2));
assertThat(ObjectPath.eval("data." + appName1 + "." + dataKey3, profileMap1), equalTo(dataValue3));
final Map<String, Object> profileMap2 = doGetProfile(uid, appName2);
logger.info("Profile Map [{}][app={}] : {}", getTestName(), appName2, profileMap2);
assertThat(ObjectPath.eval("data." + appName2 + "." + dataKey1, profileMap2), equalTo(dataValue1a));
assertThat(ObjectPath.eval("data." + appName2 + "." + dataKey2, profileMap2), equalTo(dataValue2));
assertThat(ObjectPath.eval("data." + appName2 + "." + dataKey3, profileMap2), nullValue());
}
}
public void testRemoveProfileData() throws IOException {
final Map<String, Object> activateProfileMap = doActivateProfile();
final String uid = (String) activateProfileMap.get("uid");
{
final Request request = new Request(randomFrom("PUT", "POST"), "_security/profile/" + uid + "/_data");
request.setJsonEntity("""
{
"data": {
"app1": { "top": { "inner" : { "leaf": "data_value" } } }
}
}""");
assertOK(adminClient().performRequest(request));
final Map<String, Object> profileMap = doGetProfile(uid, "app1");
assertThat(ObjectPath.eval("data.app1.top.inner.leaf", profileMap), equalTo("data_value"));
}
{
final Request request = new Request(randomFrom("PUT", "POST"), "_security/profile/" + uid + "/_data");
request.setJsonEntity("""
{
"data": {
"app1": { "top": null }
}
}""");
assertOK(adminClient().performRequest(request));
final Map<String, Object> profileMap = doGetProfile(uid, "app1");
assertThat(ObjectPath.eval("data.app1.top", profileMap), nullValue());
}
}
public void testSuggestProfile() throws IOException {
final Map<String, Object> activateProfileMap = doActivateProfile();
final String uid = (String) activateProfileMap.get("uid");
final Request suggestProfilesRequest1 = new Request(randomFrom("GET", "POST"), "_security/profile/_suggest");
suggestProfilesRequest1.setJsonEntity("""
{
"name": "rac",
"size": 10
}""");
final Response suggestProfilesResponse1 = adminClient().performRequest(suggestProfilesRequest1);
assertOK(suggestProfilesResponse1);
final Map<String, Object> suggestProfileResponseMap1 = responseAsMap(suggestProfilesResponse1);
assertThat(suggestProfileResponseMap1, hasKey("took"));
assertThat(suggestProfileResponseMap1.get("total"), equalTo(Map.of("value", 1, "relation", "eq")));
@SuppressWarnings("unchecked")
final List<Map<String, Object>> users = (List<Map<String, Object>>) suggestProfileResponseMap1.get("profiles");
assertThat(users, hasSize(1));
assertThat(users.get(0).get("uid"), equalTo(uid));
}
// Purpose of this test is to ensure the hint field works in the REST layer, e.g. parsing correctly etc.
// It does not attempt to test whether the query works correctly once it reaches the transport and service layer
// (other than the behaviour that hint does not decide whether a record should be returned).
// More comprehensive tests for hint behaviours are performed in internal cluster test.
public void testSuggestProfileWithHint() throws IOException {
final Map<String, Object> activateProfileMap = doActivateProfile();
final String uid = (String) activateProfileMap.get("uid");
final Request suggestProfilesRequest1 = new Request(randomFrom("GET", "POST"), "_security/profile/_suggest");
final String payload;
switch (randomIntBetween(0, 2)) {
case 0 -> {
payload = Strings.format("""
{
"name": "rac",
"hint": {
"uids": ["%s"]
}
}
""", "not-" + uid);
}
case 1 -> {
Object[] args = new Object[] { randomBoolean() ? "\"demo\"" : "[\"demo\"]" };
payload = Strings.format("""
{
"name": "rac",
"hint": {
"labels": {
"kibana.spaces": %s
}
}
}
""", args);
}
default -> {
Object[] args = new Object[] { "not-" + uid, randomBoolean() ? "\"demo\"" : "[\"demo\"]" };
payload = Strings.format("""
{
"name": "rac",
"hint": {
"uids": ["%s"],
"labels": {
"kibana.spaces": %s
}
}
}""", args);
}
}
suggestProfilesRequest1.setJsonEntity(payload);
final Response suggestProfilesResponse1 = adminClient().performRequest(suggestProfilesRequest1);
final Map<String, Object> suggestProfileResponseMap1 = responseAsMap(suggestProfilesResponse1);
@SuppressWarnings("unchecked")
final List<Map<String, Object>> users = (List<Map<String, Object>>) suggestProfileResponseMap1.get("profiles");
assertThat(users, hasSize(1));
assertThat(users.get(0).get("uid"), equalTo(uid));
}
public void testSetEnabled() throws IOException {
final Map<String, Object> profileMap = doActivateProfile();
final String uid = (String) profileMap.get("uid");
doSetEnabled(uid, randomBoolean());
// 404 for non-existing uid
final ResponseException e1 = expectThrows(ResponseException.class, () -> doSetEnabled("not-" + uid, randomBoolean()));
assertThat(e1.getResponse().getStatusLine().getStatusCode(), equalTo(404));
}
public void testSettingsOutputIncludeDomain() throws IOException {
final Request getSettingsRequest = new Request("GET", "_cluster/settings");
getSettingsRequest.addParameter("include_defaults", "true");
getSettingsRequest.addParameter("filter_path", "**.security.authc.domains");
final Response getSettingsResponse = adminClient().performRequest(getSettingsRequest);
assertOK(getSettingsResponse);
final XContentTestUtils.JsonMapView settingsView = XContentTestUtils.createJsonMapView(
getSettingsResponse.getEntity().getContent()
);
final Map<String, Object> domainSettings1 = castToMap(settingsView.get("defaults.xpack.security.authc.domains.my_domain"));
@SuppressWarnings("unchecked")
final List<String> myDomainRealms = (List<String>) domainSettings1.get("realms");
assertThat(myDomainRealms, containsInAnyOrder("default_file", "ldap1"));
final Map<String, Object> domainSettings2 = castToMap(settingsView.get("defaults.xpack.security.authc.domains.other_domain"));
@SuppressWarnings("unchecked")
final List<String> otherDomainRealms = (List<String>) domainSettings2.get("realms");
assertThat(otherDomainRealms, containsInAnyOrder("saml1", "ad1"));
}
public void testXpackUsageOutput() throws IOException {
// Profile 1 that has not activated for more than 30 days
final String uid = randomAlphaOfLength(20);
final String source = String.format(
Locale.ROOT,
SAMPLE_PROFILE_DOCUMENT_TEMPLATE,
uid,
uid,
Instant.now().minus(31, ChronoUnit.DAYS).toEpochMilli()
);
final Request indexRequest = new Request("PUT", ".security-profile/_doc/profile_" + uid);
indexRequest.setJsonEntity(source);
indexRequest.addParameter("refresh", "wait_for");
indexRequest.setOptions(
expectWarnings(
"this request accesses system indices: [.security-profile-8], but in a future major version, "
+ "direct access to system indices will be prevented by default"
).toBuilder().addHeader("X-elastic-product-origin", "elastic")
);
assertOK(adminClient().performRequest(indexRequest));
// Profile 2 is disabled
final Map<String, Object> racUserProfile = doActivateProfile();
doSetEnabled((String) racUserProfile.get("uid"), false);
// Profile 3 is enabled and recently activated
doActivateProfile("test-admin", "x-pack-test-password");
final Request xpackUsageRequest = new Request("GET", "_xpack/usage");
xpackUsageRequest.addParameter("filter_path", "security");
final Response xpackUsageResponse = adminClient().performRequest(xpackUsageRequest);
assertOK(xpackUsageResponse);
final XContentTestUtils.JsonMapView xpackUsageView = XContentTestUtils.createJsonMapView(
xpackUsageResponse.getEntity().getContent()
);
final Map<String, Object> domainsUsage = castToMap(xpackUsageView.get("security.domains"));
assertThat(domainsUsage.keySet(), equalTo(Set.of("my_domain", "other_domain")));
@SuppressWarnings("unchecked")
final List<String> myDomainRealms = (List<String>) castToMap(domainsUsage.get("my_domain")).get("realms");
assertThat(myDomainRealms, containsInAnyOrder("default_file", "ldap1"));
@SuppressWarnings("unchecked")
final List<String> otherDomainRealms = (List<String>) castToMap(domainsUsage.get("other_domain")).get("realms");
assertThat(otherDomainRealms, containsInAnyOrder("saml1", "ad1"));
assertThat(castToMap(xpackUsageView.get("security.user_profile")), equalTo(Map.of("total", 3, "enabled", 2, "recent", 1)));
}
public void testActivateGracePeriodIsPerNode() throws IOException {
final Request activateProfileRequest = new Request("POST", "_security/profile/_activate");
activateProfileRequest.setJsonEntity("""
{
"grant_type": "password",
"username": "rac-user",
"password": "x-pack-test-password"
}""");
final RestClient client = adminClient();
final List<Node> originalNodes = client.getNodes();
assertThat(originalNodes.size(), greaterThan(1));
final Node node0 = originalNodes.get(0);
// Find a different node other than node0.
// Because all nodes of a testcluster runs on the same physical host, the different node
// should have the same hostname but listens on a different port.
// A single node can have both ipv4 and ipv6 addresses. If we do not filter for the
// same hostname, we might find the same node again (e.g. node0 but has an ipv6 address).
final Node node1 = originalNodes.subList(1, originalNodes.size())
.stream()
.filter(node -> node.getHost().getHostName().equals(node0.getHost().getHostName()))
.findFirst()
.orElseThrow();
try {
// Initial activate with node0
client.setNodes(List.of(node0));
final Map<String, Object> responseMap0 = responseAsMap(client.performRequest(activateProfileRequest));
final Instant start = Instant.now();
// Activate again with the same host (node0) should fall within the grace period and skip actual update
final Map<String, Object> responseMap1 = responseAsMap(client.performRequest(activateProfileRequest));
assumeTrue("Test is running too slow", start.plus(30, ChronoUnit.SECONDS).isAfter(Instant.now()));
assertThat(responseMap1.get("_doc"), equalTo(responseMap0.get("_doc")));
// Activate with different host (node1) should actually update since node name changes in RealmRef
client.setNodes(List.of(node1));
final Map<String, Object> responseMap2 = responseAsMap(client.performRequest(activateProfileRequest));
assumeTrue("Test is running too slow", start.plus(30, ChronoUnit.SECONDS).isAfter(Instant.now()));
assertThat(responseMap2.get("_doc"), not(equalTo(responseMap0.get("_doc"))));
// Activate again with node1 should see no update
final Map<String, Object> responseMap3 = responseAsMap(client.performRequest(activateProfileRequest));
assertTrue("Test is running too slow", Instant.now().toEpochMilli() - (long) responseMap2.get("last_synchronized") < 30_000L);
assertThat(responseMap3.get("_doc"), equalTo(responseMap2.get("_doc")));
} finally {
client.setNodes(originalNodes);
}
}
public void testGetUsersWithProfileUid() throws IOException {
final String username = randomAlphaOfLengthBetween(3, 8);
final Request putUserRequest = new Request("PUT", "_security/user/" + username);
putUserRequest.setJsonEntity("{\"password\":\"x-pack-test-password\",\"roles\":[\"superuser\"]}");
assertOK(adminClient().performRequest(putUserRequest));
// Get user with profile uid before profile index exists will not show any profile_uid
final Request getUserRequest = new Request("GET", "_security/user" + (randomBoolean() ? "/" + username : ""));
getUserRequest.addParameter("with_profile_uid", "true");
final Response getUserResponse1 = adminClient().performRequest(getUserRequest);
assertOK(getUserResponse1);
responseAsMap(getUserResponse1).forEach((k, v) -> assertThat(castToMap(v), not(hasKey("profile_uid"))));
// The profile_uid is retrieved for the user after the profile gets activated
final Map<String, Object> profile = doActivateProfile(username, "x-pack-test-password");
final Response getUserResponse2 = adminClient().performRequest(getUserRequest);
responseAsMap(getUserResponse2).forEach((k, v) -> {
if (username.equals(k)) {
assertThat(castToMap(v).get("profile_uid"), equalTo(profile.get("uid")));
} else {
assertThat(castToMap(v), not(hasKey("profile_uid")));
}
});
}
private Map<String, Object> doActivateProfile() throws IOException {
return doActivateProfile("rac-user", "x-pack-test-password");
}
private Map<String, Object> doActivateProfile(String username, String password) throws IOException {
final Request activateProfileRequest = new Request("POST", "_security/profile/_activate");
activateProfileRequest.setJsonEntity(Strings.format("""
{
"grant_type": "password",
"username": "%s",
"password": "%s"
}""", username, password));
final Response activateProfileResponse = adminClient().performRequest(activateProfileRequest);
assertOK(activateProfileResponse);
return responseAsMap(activateProfileResponse);
}
private Map<String, Object> doGetProfile(String uid) throws IOException {
return doGetProfile(uid, null);
}
private Map<String, Object> doGetProfile(String uid, @Nullable String dataKey) throws IOException {
final Map<String, Object> responseMap = doGetProfiles(List.of(uid), dataKey);
assertThat(responseMap.get("errors"), nullValue());
@SuppressWarnings("unchecked")
final List<Map<String, Object>> profiles = (List<Map<String, Object>>) responseMap.get("profiles");
assertThat(profiles.size(), equalTo(1));
final Map<String, Object> profileMap = profiles.get(0);
assertThat(profileMap.get("uid"), equalTo(uid));
return profileMap;
}
private Map<String, Object> doGetProfiles(List<String> uids, @Nullable String dataKey) throws IOException {
final Request getProfilesRequest = new Request("GET", "_security/profile/" + Strings.collectionToCommaDelimitedString(uids));
if (dataKey != null) {
getProfilesRequest.addParameter("data", dataKey);
}
final Response getProfilesResponse = adminClient().performRequest(getProfilesRequest);
assertOK(getProfilesResponse);
return responseAsMap(getProfilesResponse);
}
private void doSetEnabled(String uid, boolean enabled) throws IOException {
final Request setEnabledRequest = new Request(
randomFrom("PUT", "POST"),
"_security/profile/" + uid + "/_" + (enabled ? "enable" : "disable")
);
adminClient().performRequest(setEnabledRequest);
}
@SuppressWarnings("unchecked")
private Map<String, Object> castToMap(Object o) {
return (Map<String, Object>) o;
}
private static String toJson(Map<String, ? extends Object> map) throws IOException {
final XContentBuilder builder = XContentFactory.jsonBuilder().map(map);
final BytesReference bytes = BytesReference.bytes(builder);
return bytes.utf8ToString();
}
}
| ProfileIT |
java | spring-projects__spring-framework | spring-jms/src/test/java/org/springframework/jms/listener/endpoint/DefaultJmsActivationSpecFactoryTests.java | {
"start": 2990,
"end": 3109
} | class ____ extends StubResourceAdapter {
}
@SuppressWarnings("unused")
private static | StubWebSphereResourceAdapterImpl |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/test/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/capacity/conf/ConfigurationStoreBaseTest.java | {
"start": 1479,
"end": 3620
} | class ____ {
static final String TEST_USER = "testUser";
YarnConfigurationStore confStore = createConfStore();
Configuration conf;
Configuration schedConf;
RMContext rmContext;
abstract YarnConfigurationStore createConfStore();
@BeforeEach
public void setUp() throws Exception {
this.conf = new Configuration();
this.conf.setClass(YarnConfiguration.RM_SCHEDULER,
CapacityScheduler.class, CapacityScheduler.class);
this.schedConf = new Configuration(false);
}
@Test
public void testConfigurationUpdate() throws Exception {
schedConf.set("key1", "val1");
confStore.initialize(conf, schedConf, rmContext);
assertEquals("val1", confStore.retrieve().get("key1"));
confStore.confirmMutation(prepareLogMutation("keyUpdate1", "valUpdate1"),
true);
assertEquals("valUpdate1", confStore.retrieve().get("keyUpdate1"));
confStore.confirmMutation(prepareLogMutation("keyUpdate2", "valUpdate2"),
false);
assertNull(confStore.retrieve().get("keyUpdate2"),
"Configuration should not be updated");
confStore.close();
}
@Test
public void testNullConfigurationUpdate() throws Exception {
schedConf.set("key", "val");
confStore.initialize(conf, schedConf, rmContext);
assertEquals("val", confStore.retrieve().get("key"));
confStore.confirmMutation(prepareLogMutation("key", null), true);
assertNull(confStore.retrieve().get("key"));
confStore.close();
}
YarnConfigurationStore.LogMutation prepareLogMutation(String... values)
throws Exception {
Map<String, String> updates = new HashMap<>();
String key;
String value;
if (values.length % 2 != 0) {
throw new IllegalArgumentException("The number of parameters should be " +
"even.");
}
for (int i = 1; i <= values.length; i += 2) {
key = values[i - 1];
value = values[i];
updates.put(key, value);
}
YarnConfigurationStore.LogMutation mutation =
new YarnConfigurationStore.LogMutation(updates, TEST_USER);
confStore.logMutation(mutation);
return mutation;
}
}
| ConfigurationStoreBaseTest |
java | spring-projects__spring-framework | spring-beans/src/main/java/org/springframework/beans/factory/support/BeanDefinitionOverrideException.java | {
"start": 1280,
"end": 3504
} | class ____ extends BeanDefinitionStoreException {
private final BeanDefinition beanDefinition;
private final BeanDefinition existingDefinition;
/**
* Create a new BeanDefinitionOverrideException for the given new and existing definition.
* @param beanName the name of the bean
* @param beanDefinition the newly registered bean definition
* @param existingDefinition the existing bean definition for the same name
*/
public BeanDefinitionOverrideException(
String beanName, BeanDefinition beanDefinition, BeanDefinition existingDefinition) {
super(beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
"' since there is already [" + existingDefinition + "] bound.");
this.beanDefinition = beanDefinition;
this.existingDefinition = existingDefinition;
}
/**
* Create a new BeanDefinitionOverrideException for the given new and existing definition.
* @param beanName the name of the bean
* @param beanDefinition the newly registered bean definition
* @param existingDefinition the existing bean definition for the same name
* @param msg the detail message to include
* @since 6.2.1
*/
public BeanDefinitionOverrideException(
String beanName, BeanDefinition beanDefinition, BeanDefinition existingDefinition, String msg) {
super(beanDefinition.getResourceDescription(), beanName, msg);
this.beanDefinition = beanDefinition;
this.existingDefinition = existingDefinition;
}
/**
* Return the description of the resource that the bean definition came from.
*/
@Override
public String getResourceDescription() {
return String.valueOf(super.getResourceDescription());
}
/**
* Return the name of the bean.
*/
@Override
public String getBeanName() {
return String.valueOf(super.getBeanName());
}
/**
* Return the newly registered bean definition.
* @see #getBeanName()
*/
public BeanDefinition getBeanDefinition() {
return this.beanDefinition;
}
/**
* Return the existing bean definition for the same name.
* @see #getBeanName()
*/
public BeanDefinition getExistingDefinition() {
return this.existingDefinition;
}
}
| BeanDefinitionOverrideException |
java | apache__camel | components/camel-protobuf/src/test/java/org/apache/camel/dataformat/protobuf/ProtobufMarshalAndUnmarshalJsonTest.java | {
"start": 1188,
"end": 3125
} | class ____ extends CamelTestSupport {
private static final String PERSON_TEST_NAME = "Martin";
private static final String PERSON_TEST_JSON = "{\"name\": \"Martin\",\"id\": 1234}";
private static final int PERSON_TEST_ID = 1234;
@Test
public void testMarshalAndUnmarshal() throws Exception {
marshalAndUnmarshal("direct:in", "direct:back");
}
@Test
public void testMarshalAndUnmarshalWithDSL() throws Exception {
marshalAndUnmarshal("direct:marshal", "direct:unmarshalA");
}
private void marshalAndUnmarshal(String inURI, String outURI) throws Exception {
MockEndpoint mock = getMockEndpoint("mock:reverse");
mock.expectedMessageCount(1);
mock.message(0).body().isInstanceOf(Person.class);
Object marshalled = template.requestBody(inURI, PERSON_TEST_JSON);
template.sendBody(outURI, marshalled);
mock.assertIsSatisfied();
Person output = mock.getReceivedExchanges().get(0).getIn().getBody(Person.class);
assertEquals(PERSON_TEST_NAME, output.getName());
assertEquals(PERSON_TEST_ID, output.getId());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
ProtobufDataFormat format
= new ProtobufDataFormat(Person.getDefaultInstance(), ProtobufDataFormat.CONTENT_TYPE_FORMAT_JSON);
from("direct:in").unmarshal(format).to("mock:reverse");
from("direct:back").marshal(format);
from("direct:marshal").unmarshal()
.protobuf("org.apache.camel.dataformat.protobuf.generated.AddressBookProtos$Person", "json")
.to("mock:reverse");
from("direct:unmarshalA").marshal().protobuf();
}
};
}
}
| ProtobufMarshalAndUnmarshalJsonTest |
java | apache__kafka | metadata/src/main/java/org/apache/kafka/image/node/DelegationTokenDataNode.java | {
"start": 1040,
"end": 3273
} | class ____ implements MetadataNode {
private final DelegationTokenData data;
public DelegationTokenDataNode(DelegationTokenData data) {
this.data = data;
}
@Override
public boolean isDirectory() {
return false;
}
@Override
public void print(MetadataNodePrinter printer) {
TokenInformation tokenInformation = data.tokenInformation();
StringBuilder bld = new StringBuilder();
bld.append("DelegationTokenData");
bld.append("tokenId=");
if (printer.redactionCriteria().shouldRedactDelegationToken()) {
bld.append("[redacted]");
} else {
bld.append(tokenInformation.tokenId());
}
bld.append("(owner=");
if (printer.redactionCriteria().shouldRedactDelegationToken()) {
bld.append("[redacted]");
} else {
bld.append(tokenInformation.ownerAsString());
}
bld.append("(tokenRequester=");
if (printer.redactionCriteria().shouldRedactDelegationToken()) {
bld.append("[redacted]");
} else {
bld.append(tokenInformation.tokenRequesterAsString());
}
bld.append("(renewers=");
if (printer.redactionCriteria().shouldRedactDelegationToken()) {
bld.append("[redacted]");
} else {
bld.append(String.join(" ", tokenInformation.renewersAsString()));
}
bld.append(", issueTimestamp=");
if (printer.redactionCriteria().shouldRedactDelegationToken()) {
bld.append("[redacted]");
} else {
bld.append(tokenInformation.issueTimestamp());
}
bld.append(", maxTimestamp=");
if (printer.redactionCriteria().shouldRedactDelegationToken()) {
bld.append("[redacted]");
} else {
bld.append(tokenInformation.maxTimestamp());
}
bld.append(")");
bld.append(", expiryTimestamp=");
if (printer.redactionCriteria().shouldRedactDelegationToken()) {
bld.append("[redacted]");
} else {
bld.append(tokenInformation.expiryTimestamp());
}
printer.output(bld.toString());
}
}
| DelegationTokenDataNode |
java | apache__dubbo | dubbo-cluster/src/main/java/org/apache/dubbo/rpc/cluster/router/condition/matcher/ConditionMatcherFactory.java | {
"start": 1022,
"end": 1617
} | interface ____ {
/**
* Check if the key is of the form of the current matcher type which this factory instance represents..
*
* @param key the key of a particular form
* @return true if matches, otherwise false
*/
boolean shouldMatch(String key);
/**
* Create a matcher instance for the key.
*
* @param key the key value conforms to a specific matcher specification
* @param model module model
* @return the specific matcher instance
*/
ConditionMatcher createMatcher(String key, ModuleModel model);
}
| ConditionMatcherFactory |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/CanonicalDurationTest.java | {
"start": 2499,
"end": 3037
} | class ____ {
static final int CONST = 86400;
{
Duration.standardSeconds(86400);
org.joda.time.Duration.standardSeconds(86400);
Duration.standardSeconds(CONST);
Duration zero = Duration.standardSeconds(0);
Duration.standardDays(1);
}
}
""")
.addOutputLines(
"out/A.java",
"""
package a;
import org.joda.time.Duration;
public | A |
java | apache__flink | flink-filesystems/flink-gs-fs-hadoop/src/test/java/org/apache/flink/fs/gs/utils/BlobUtilsTest.java | {
"start": 1244,
"end": 6155
} | class ____ {
@Test
void shouldParseValidUri() {
GSBlobIdentifier blobIdentifier = BlobUtils.parseUri(URI.create("gs://bucket/foo/bar"));
assertThat(blobIdentifier.bucketName).isEqualTo("bucket");
assertThat(blobIdentifier.objectName).isEqualTo("foo/bar");
}
@Test
void shouldFailToParseUriBadScheme() {
assertThatThrownBy(() -> BlobUtils.parseUri(URI.create("s3://bucket/foo/bar")))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void shouldFailToParseUriMissingBucketName() {
assertThatThrownBy(() -> BlobUtils.parseUri(URI.create("gs:///foo/bar")))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void shouldFailToParseUriMissingObjectName() {
assertThatThrownBy(() -> BlobUtils.parseUri(URI.create("gs://bucket/")))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void shouldUseTemporaryBucketNameIfSpecified() {
Configuration flinkConfig = new Configuration();
flinkConfig.set(GSFileSystemOptions.WRITER_TEMPORARY_BUCKET_NAME, "temp");
GSFileSystemOptions options = new GSFileSystemOptions(flinkConfig);
GSBlobIdentifier identifier = new GSBlobIdentifier("foo", "bar");
String bucketName = BlobUtils.getTemporaryBucketName(identifier, options);
assertThat(bucketName).isEqualTo("temp");
}
@Test
void shouldUseIdentifierBucketNameNameIfTemporaryBucketNotSpecified() {
Configuration flinkConfig = new Configuration();
GSFileSystemOptions options = new GSFileSystemOptions(flinkConfig);
GSBlobIdentifier identifier = new GSBlobIdentifier("foo", "bar");
String bucketName = BlobUtils.getTemporaryBucketName(identifier, options);
assertThat(bucketName).isEqualTo("foo");
}
@Test
void shouldProperlyConstructTemporaryObjectPartialName() {
GSBlobIdentifier identifier = new GSBlobIdentifier("foo", "bar");
String partialName = BlobUtils.getTemporaryObjectPartialName(identifier);
assertThat(partialName).isEqualTo(".inprogress/foo/bar/");
}
@Test
void shouldProperlyConstructTemporaryObjectName() {
GSBlobIdentifier identifier = new GSBlobIdentifier("foo", "bar");
UUID temporaryObjectId = UUID.fromString("f09c43e5-ea49-4537-a406-0586f8f09d47");
String partialName = BlobUtils.getTemporaryObjectName(identifier, temporaryObjectId);
assertThat(partialName)
.isEqualTo(".inprogress/foo/bar/f09c43e5-ea49-4537-a406-0586f8f09d47");
}
@Test
void shouldProperlyConstructTemporaryObjectNameWithEntropy() {
Configuration flinkConfig = new Configuration();
flinkConfig.set(GSFileSystemOptions.ENABLE_FILESINK_ENTROPY, Boolean.TRUE);
GSBlobIdentifier identifier = new GSBlobIdentifier("foo", "bar");
UUID temporaryObjectId = UUID.fromString("f09c43e5-ea49-4537-a406-0586f8f09d47");
String partialName =
BlobUtils.getTemporaryObjectNameWithEntropy(identifier, temporaryObjectId);
assertThat(
"f09c43e5-ea49-4537-a406-0586f8f09d47.inprogress/foo/bar/f09c43e5-ea49-4537-a406-0586f8f09d47")
.isEqualTo(partialName);
}
@Test
void shouldProperlyConstructTemporaryBlobIdentifierWithDefaultBucket() {
Configuration flinkConfig = new Configuration();
GSFileSystemOptions options = new GSFileSystemOptions(flinkConfig);
GSBlobIdentifier identifier = new GSBlobIdentifier("foo", "bar");
UUID temporaryObjectId = UUID.fromString("f09c43e5-ea49-4537-a406-0586f8f09d47");
GSBlobIdentifier temporaryBlobIdentifier =
BlobUtils.getTemporaryBlobIdentifier(identifier, temporaryObjectId, options);
assertThat(temporaryBlobIdentifier.bucketName).isEqualTo("foo");
assertThat(temporaryBlobIdentifier.objectName)
.isEqualTo(".inprogress/foo/bar/f09c43e5-ea49-4537-a406-0586f8f09d47");
}
@Test
void shouldProperlyConstructTemporaryBlobIdentifierWithTemporaryBucket() {
Configuration flinkConfig = new Configuration();
flinkConfig.set(GSFileSystemOptions.WRITER_TEMPORARY_BUCKET_NAME, "temp");
GSFileSystemOptions options = new GSFileSystemOptions(flinkConfig);
GSBlobIdentifier identifier = new GSBlobIdentifier("foo", "bar");
UUID temporaryObjectId = UUID.fromString("f09c43e5-ea49-4537-a406-0586f8f09d47");
GSBlobIdentifier temporaryBlobIdentifier =
BlobUtils.getTemporaryBlobIdentifier(identifier, temporaryObjectId, options);
assertThat(temporaryBlobIdentifier.bucketName).isEqualTo("temp");
assertThat(temporaryBlobIdentifier.objectName)
.isEqualTo(".inprogress/foo/bar/f09c43e5-ea49-4537-a406-0586f8f09d47");
}
}
| BlobUtilsTest |
java | apache__camel | components/camel-metrics/src/test/java/org/apache/camel/component/metrics/MetricsComponentRouteTest.java | {
"start": 1449,
"end": 4499
} | class ____ extends CamelTestSupport {
@Produce("direct:start-1")
protected ProducerTemplate template1;
@Produce("direct:start-2")
protected ProducerTemplate template2;
@Test
public void testMetrics() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
mock.expectedMinimumMessageCount(1);
template1.sendBody(new Object());
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testMessageContentDelivery() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
String body = "Message Body";
String header1 = "Header 1";
String header2 = "Header 2";
Object value1 = new Date();
Object value2 = System.currentTimeMillis();
mock.expectedBodiesReceived(body);
mock.expectedHeaderReceived(header1, value1);
mock.expectedHeaderReceived(header2, value2);
Map<String, Object> headers = new HashMap<>();
headers.put(header1, value1);
headers.put(header2, value2);
template1.sendBodyAndHeaders(body, headers);
MockEndpoint.assertIsSatisfied(context);
}
@Test
public void testHeaderRemoval() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:result");
Object body = new Object();
Date now = new Date();
mock.expectedBodiesReceived(body);
mock.expectedHeaderReceived("." + HEADER_PREFIX, "value");
mock.expectedHeaderReceived("date", now);
Map<String, Object> headers = new HashMap<>();
headers.put(HEADER_METRIC_NAME, "a name");
headers.put(HEADER_HISTOGRAM_VALUE, 34L);
headers.put(HEADER_PREFIX + "notExistingHeader", "?");
headers.put("." + HEADER_PREFIX, "value");
headers.put("date", now);
template2.sendBodyAndHeaders(body, headers);
MockEndpoint.assertIsSatisfied(context);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start-1")
.to("metrics:timer:T?action=start")
.to("metrics:counter://A")
.to("metrics:counter://B")
.to("metrics:counter:C?increment=19291")
.to("metrics:counter:C?decrement=19292")
.to("metrics:counter:C")
.to("metrics:meter:D")
.to("metrics:meter:D?mark=90001")
.to("metrics:histogram:E")
.to("metrics:timer:T")
.to("metrics:histogram:E?value=12000000031")
.to("metrics:timer:T?action=stop")
.to("mock:result");
from("direct:start-2")
.to("metrics:meter:F?mark=88")
.to("mock:result");
}
};
}
}
| MetricsComponentRouteTest |
java | spring-projects__spring-boot | module/spring-boot-http-client/src/test/java/org/springframework/boot/http/client/autoconfigure/imperative/ImperativeHttpClientAutoConfigurationTests.java | {
"start": 2630,
"end": 7498
} | class ____ {
private static final AutoConfigurations autoConfigurations = AutoConfigurations
.of(ImperativeHttpClientAutoConfiguration.class, HttpClientAutoConfiguration.class, SslAutoConfiguration.class);
private final ApplicationContextRunner contextRunner = new ApplicationContextRunner()
.withConfiguration(autoConfigurations);
@Test
void configuresDetectedClientHttpRequestFactoryBuilder() {
this.contextRunner.run((context) -> assertThat(context).hasSingleBean(ClientHttpRequestFactoryBuilder.class));
}
@Test
void configuresDefinedClientHttpRequestFactoryBuilder() {
this.contextRunner.withPropertyValues("spring.http.clients.imperative.factory=simple")
.run((context) -> assertThat(context.getBean(ClientHttpRequestFactoryBuilder.class))
.isInstanceOf(SimpleClientHttpRequestFactoryBuilder.class));
}
@Test
void configuresClientHttpRequestFactorySettings() {
this.contextRunner.withPropertyValues(sslPropertyValues().toArray(String[]::new))
.withPropertyValues("spring.http.clients.redirects=dont-follow", "spring.http.clients.connect-timeout=10s",
"spring.http.clients.read-timeout=20s", "spring.http.clients.ssl.bundle=test")
.run((context) -> {
HttpClientSettings settings = context.getBean(HttpClientSettings.class);
assertThat(settings.redirects()).isEqualTo(HttpRedirects.DONT_FOLLOW);
assertThat(settings.connectTimeout()).isEqualTo(Duration.ofSeconds(10));
assertThat(settings.readTimeout()).isEqualTo(Duration.ofSeconds(20));
SslBundle sslBundle = settings.sslBundle();
assertThat(sslBundle).isNotNull();
assertThat(sslBundle.getKey().getAlias()).isEqualTo("alias1");
});
}
private List<String> sslPropertyValues() {
List<String> propertyValues = new ArrayList<>();
String location = "classpath:org/springframework/boot/autoconfigure/ssl/";
propertyValues.add("spring.ssl.bundle.pem.test.key.alias=alias1");
propertyValues.add("spring.ssl.bundle.pem.test.truststore.type=PKCS12");
propertyValues.add("spring.ssl.bundle.pem.test.truststore.certificate=" + location + "rsa-cert.pem");
propertyValues.add("spring.ssl.bundle.pem.test.truststore.private-key=" + location + "rsa-key.pem");
return propertyValues;
}
@Test
void whenHttpComponentsIsUnavailableThenJettyClientBeansAreDefined() {
this.contextRunner
.withClassLoader(new FilteredClassLoader(org.apache.hc.client5.http.impl.classic.HttpClients.class))
.run((context) -> assertThat(context.getBean(ClientHttpRequestFactoryBuilder.class))
.isExactlyInstanceOf(JettyClientHttpRequestFactoryBuilder.class));
}
@Test
void whenHttpComponentsAndJettyAreUnavailableThenReactorClientBeansAreDefined() {
this.contextRunner
.withClassLoader(new FilteredClassLoader(org.apache.hc.client5.http.impl.classic.HttpClients.class,
org.eclipse.jetty.client.HttpClient.class))
.run((context) -> assertThat(context.getBean(ClientHttpRequestFactoryBuilder.class))
.isExactlyInstanceOf(ReactorClientHttpRequestFactoryBuilder.class));
}
@Test
void whenHttpComponentsAndJettyAndReactorAreUnavailableThenJdkClientBeansAreDefined() {
this.contextRunner
.withClassLoader(new FilteredClassLoader(org.apache.hc.client5.http.impl.classic.HttpClients.class,
org.eclipse.jetty.client.HttpClient.class, reactor.netty.http.client.HttpClient.class))
.run((context) -> assertThat(context.getBean(ClientHttpRequestFactoryBuilder.class))
.isExactlyInstanceOf(JdkClientHttpRequestFactoryBuilder.class));
}
@Test
void whenReactiveWebApplicationBeansAreNotConfigured() {
new ReactiveWebApplicationContextRunner().withConfiguration(autoConfigurations)
.run((context) -> assertThat(context).doesNotHaveBean(ClientHttpRequestFactoryBuilder.class)
.hasSingleBean(HttpClientSettings.class));
}
@Test
void clientHttpRequestFactoryBuilderCustomizersAreApplied() {
this.contextRunner.withUserConfiguration(ClientHttpRequestFactoryBuilderCustomizersConfiguration.class)
.run((context) -> {
ClientHttpRequestFactory factory = context.getBean(ClientHttpRequestFactoryBuilder.class).build();
assertThat(factory).extracting("readTimeout").isEqualTo(5L);
});
}
@Test
@EnabledForJreRange(min = JRE.JAVA_21)
void whenVirtualThreadsEnabledAndUsingJdkHttpClientUsesVirtualThreadExecutor() {
this.contextRunner
.withPropertyValues("spring.http.clients.imperative.factory=jdk", "spring.threads.virtual.enabled=true")
.run((context) -> {
ClientHttpRequestFactory factory = context.getBean(ClientHttpRequestFactoryBuilder.class).build();
HttpClient httpClient = (HttpClient) ReflectionTestUtils.getField(factory, "httpClient");
assertThat(httpClient).isNotNull();
assertThat(httpClient.executor()).containsInstanceOf(VirtualThreadTaskExecutor.class);
});
}
@Configuration(proxyBeanMethods = false)
static | ImperativeHttpClientAutoConfigurationTests |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/ContainerAllocationHistory.java | {
"start": 1334,
"end": 2646
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(AMRMClientRelayer.class);
private int maxEntryCount;
// Allocate timing history <AllocateTimeStamp, AllocateLatency>
private Queue<Entry<Long, Long>> relaxableG = new LinkedList<>();
public ContainerAllocationHistory(Configuration conf) {
this.maxEntryCount = conf.getInt(
YarnConfiguration.FEDERATION_ALLOCATION_HISTORY_MAX_ENTRY,
YarnConfiguration.DEFAULT_FEDERATION_ALLOCATION_HISTORY_MAX_ENTRY);
}
/**
* Record the allocation history for the container.
*
* @param container to add record for
* @param requestSet resource request ask set
* @param fulfillTimeStamp time at which allocation happened
* @param fulfillLatency time elapsed in allocating since asked
*/
public synchronized void addAllocationEntry(Container container,
ResourceRequestSet requestSet, long fulfillTimeStamp, long fulfillLatency){
if (!requestSet.isANYRelaxable()) {
LOG.info("allocation history ignoring {}, relax locality is false", container);
return;
}
this.relaxableG.add(new AbstractMap.SimpleEntry<>(
fulfillTimeStamp, fulfillLatency));
if (this.relaxableG.size() > this.maxEntryCount) {
this.relaxableG.remove();
}
}
}
| ContainerAllocationHistory |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/cascade2/ParentInfoAssigned.java | {
"start": 213,
"end": 688
} | class ____ {
private Long id;
private ParentAssigned owner;
private String info;
public ParentInfoAssigned() {
}
public ParentInfoAssigned(String info) {
this.info = info;
}
public Long getId() {
return id;
}
public ParentAssigned getOwner() {
return owner;
}
public void setOwner(ParentAssigned owner) {
this.owner = owner;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
}
| ParentInfoAssigned |
java | apache__hadoop | hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/services/AbfsHttpClientConnectionFactory.java | {
"start": 1315,
"end": 1889
} | class ____ extends ManagedHttpClientConnectionFactory {
/**
* Creates a new {@link AbfsManagedApacheHttpConnection} instance which has to
* be connected.
* @param route route for which connection is required.
* @param config connection configuration.
* @return new {@link AbfsManagedApacheHttpConnection} instance.
*/
@Override
public ManagedHttpClientConnection create(final HttpRoute route,
final ConnectionConfig config) {
return new AbfsManagedApacheHttpConnection(super.create(route, config), route);
}
}
| AbfsHttpClientConnectionFactory |
java | elastic__elasticsearch | x-pack/plugin/esql/src/test/java/org/elasticsearch/xpack/esql/expression/function/scalar/convert/UrlEncodeComponentTests.java | {
"start": 811,
"end": 1356
} | class ____ extends AbstractUrlEncodeDecodeTestCase {
public UrlEncodeComponentTests(@Name("TestCase") Supplier<TestCaseSupplier.TestCase> testCaseSupplier) {
this.testCase = testCaseSupplier.get();
}
@ParametersFactory
public static Iterable<Object[]> parameters() {
return createParameters(PercentCodecTestType.ENCODE_COMPONENT);
}
@Override
protected Expression build(Source source, List<Expression> args) {
return new UrlEncodeComponent(source, args.get(0));
}
}
| UrlEncodeComponentTests |
java | FasterXML__jackson-core | src/test/java/tools/jackson/core/unittest/testutil/failure/JacksonTestFailureExpectedInterceptor.java | {
"start": 483,
"end": 3821
} | class ____
implements InvocationInterceptor
{
@Override
public void interceptTestMethod(Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext)
throws Throwable
{
try {
invocation.proceed();
} catch (Throwable t) {
// do-nothing, we do expect an exception
return;
}
handleUnexpectePassingTest(invocationContext);
}
/**
* Interceptor API method that is called to intercept test template
* method invocation, like {@link org.junit.jupiter.params.ParameterizedTest}.
*<p>
* Before failing passing test case, it checks if the test should pass according to the
* {@link ExpectedPassingTestCasePredicate} provided in the
* {@link JacksonTestFailureExpected} annotation.
*/
@Override
public void interceptTestTemplateMethod(Invocation<Void> invocation,
ReflectiveInvocationContext<Method> invocationContext, ExtensionContext extensionContext)
throws Throwable
{
try {
invocation.proceed();
} catch (Throwable t) {
// do-nothing, we do expect an exception
return;
}
// Before we fail the test for passing,
// check if the test should pass according to the predicate given
ExpectedPassingTestCasePredicate predicate = findzExpectedPassingTestCasePredicate(invocationContext);
if (predicate != null) {
if (predicate.shouldPass(invocationContext.getArguments())) {
// do-nothing, we do not expect an exception
return;
}
}
handleUnexpectePassingTest(invocationContext);
}
private void handleUnexpectePassingTest(ReflectiveInvocationContext<Method> invocationContext) {
// Collect information we need
Object targetClass = invocationContext.getTargetClass();
Object testMethod = invocationContext.getExecutable().getName();
//List<Object> arguments = invocationContext.getArguments();
// Create message
String message = String.format("Test method %s.%s() passed, but should have failed", targetClass, testMethod);
// throw exception
throw new JacksonTestShouldFailException(message);
}
/**
* @return null if the default predicate is found,
* otherwise instance of the {@link ExpectedPassingTestCasePredicate}.
*/
private ExpectedPassingTestCasePredicate findzExpectedPassingTestCasePredicate(
ReflectiveInvocationContext<Method> invocationContext)
throws InstantiationException, IllegalAccessException
{
JacksonTestFailureExpected annotation = invocationContext.getExecutable().getAnnotation(JacksonTestFailureExpected.class);
Class<? extends ExpectedPassingTestCasePredicate> predicate = annotation.expectedPassingTestCasePredicate();
if (ExpectedPassingTestCasePredicate.class.equals(predicate)) {
return null;
} else {
try {
return predicate.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
}
| JacksonTestFailureExpectedInterceptor |
java | spring-projects__spring-framework | spring-expression/src/main/java/org/springframework/expression/spel/ast/Assign.java | {
"start": 1218,
"end": 1852
} | class ____ extends SpelNodeImpl {
public Assign(int startPos, int endPos, SpelNodeImpl... operands) {
super(startPos, endPos, operands);
}
@Override
public TypedValue getValueInternal(ExpressionState state) throws EvaluationException {
if (!state.getEvaluationContext().isAssignmentEnabled()) {
throw new SpelEvaluationException(getStartPosition(), SpelMessage.NOT_ASSIGNABLE, toStringAST());
}
return this.children[0].setValueInternal(state, () -> this.children[1].getValueInternal(state));
}
@Override
public String toStringAST() {
return getChild(0).toStringAST() + "=" + getChild(1).toStringAST();
}
}
| Assign |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/CollectingErrorsTest.java | {
"start": 27603,
"end": 32250
} | class ____ {
@Test
@DisplayName("should validate positive maxProblems")
void validateMaxProblems() {
// when/then
assertThatThrownBy(() -> MAPPER.readerFor(Person.class).problemCollectingReader(0))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("maxProblems must be positive");
assertThatThrownBy(() -> MAPPER.readerFor(Person.class).problemCollectingReader(-1))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("should handle empty JSON")
void emptyJson() {
// setup
String json = "{}";
ObjectReader reader = MAPPER.readerFor(Person.class).problemCollectingReader();
// when
Person result = reader.readValueCollectingProblems(json);
// then
assertThat(result).isNotNull();
assertThat(result.name).isNull();
assertThat(result.age).isEqualTo(0);
}
@Test
@DisplayName("should handle null parser gracefully")
void nullParser() {
// setup
ObjectReader reader = MAPPER.readerFor(Person.class).problemCollectingReader();
// when/then
assertThatThrownBy(() -> reader.readValueCollectingProblems((String) null))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
@DisplayName("should collect errors via byte[] overload")
void collectFromByteArray() {
// setup
String jsonString = "{\"name\":\"Alice\",\"age\":\"invalid\"}";
byte[] jsonBytes = jsonString.getBytes(StandardCharsets.UTF_8);
ObjectReader reader = MAPPER.readerFor(Person.class).problemCollectingReader();
// when
DeferredBindingException ex = expectDeferredBinding(reader, jsonBytes);
// then
assertThat(ex).isNotNull();
assertThat(ex.getProblems()).hasSize(1);
assertThat(ex.getProblems().get(0).getPath().toString()).isEqualTo("/age");
}
@Test
@DisplayName("should collect errors via File overload")
void collectFromFile() throws Exception {
// setup
File tempFile = File.createTempFile("test", ".json");
try {
java.nio.file.Files.writeString(tempFile.toPath(),
"{\"name\":\"Bob\",\"age\":\"notANumber\"}");
ObjectReader reader = MAPPER.readerFor(Person.class).problemCollectingReader();
// when
DeferredBindingException ex = expectDeferredBinding(reader, tempFile);
// then
assertThat(ex).isNotNull();
assertThat(ex.getProblems()).hasSize(1);
assertThat(ex.getProblems().get(0).getMessage())
.contains("notANumber");
} finally {
java.nio.file.Files.deleteIfExists(tempFile.toPath());
}
}
@Test
@DisplayName("should collect errors via InputStream overload")
void collectFromInputStream() throws Exception {
// setup
String json = "{\"name\":\"Charlie\",\"age\":\"bad\"}";
ObjectReader reader = MAPPER.readerFor(Person.class).problemCollectingReader();
// when
DeferredBindingException ex;
try (InputStream input = new java.io.ByteArrayInputStream(
json.getBytes(StandardCharsets.UTF_8))) {
ex = expectDeferredBinding(reader, input);
}
// then
assertThat(ex).isNotNull();
assertThat(ex.getProblems()).hasSize(1);
assertThat(ex.getProblems().get(0).getPath().toString()).isEqualTo("/age");
}
@Test
@DisplayName("should collect errors via Reader overload")
void collectFromReader() throws Exception {
// setup
String json = "{\"name\":\"Diana\",\"age\":\"invalid\"}";
ObjectReader objectReader = MAPPER.readerFor(Person.class).problemCollectingReader();
// when
DeferredBindingException ex;
try (Reader reader = new java.io.StringReader(json)) {
ex = expectDeferredBinding(objectReader, reader);
}
// then
assertThat(ex).isNotNull();
assertThat(ex.getProblems()).hasSize(1);
assertThat(ex.getProblems().get(0).getPath().toString()).isEqualTo("/age");
}
}
}
| EdgeCaseTests |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/web/reactive/server/AbstractMockServerSpec.java | {
"start": 1375,
"end": 3603
} | class ____<B extends WebTestClient.MockServerSpec<B>>
implements WebTestClient.MockServerSpec<B> {
private @Nullable List<WebFilter> filters;
private @Nullable WebSessionManager sessionManager;
private @Nullable SslInfo sslInfo;
private @Nullable List<MockServerConfigurer> configurers;
AbstractMockServerSpec() {
// Default instance to be re-used across requests, unless one is configured explicitly
this.sessionManager = new DefaultWebSessionManager();
}
@Override
public <T extends B> T webFilter(WebFilter... filters) {
if (filters.length > 0) {
this.filters = (this.filters != null ? this.filters : new ArrayList<>(4));
this.filters.addAll(Arrays.asList(filters));
}
return self();
}
@Override
public <T extends B> T webSessionManager(WebSessionManager sessionManager) {
this.sessionManager = sessionManager;
return self();
}
@Override
public <T extends B> T sslInfo(@Nullable SslInfo info) {
this.sslInfo = info;
return self();
}
@Override
public <T extends B> T apply(MockServerConfigurer configurer) {
configurer.afterConfigureAdded(this);
this.configurers = (this.configurers != null ? this.configurers : new ArrayList<>(4));
this.configurers.add(configurer);
return self();
}
@SuppressWarnings("unchecked")
private <T extends B> T self() {
return (T) this;
}
@Override
public WebTestClient.Builder configureClient() {
WebHttpHandlerBuilder builder = initHttpHandlerBuilder();
if (!CollectionUtils.isEmpty(this.filters)) {
builder.filters(theFilters -> theFilters.addAll(0, this.filters));
}
if (!builder.hasSessionManager() && this.sessionManager != null) {
builder.sessionManager(this.sessionManager);
}
if (!CollectionUtils.isEmpty(this.configurers)) {
this.configurers.forEach(configurer -> configurer.beforeServerCreated(builder));
}
return new DefaultWebTestClientBuilder(builder, this.sslInfo);
}
/**
* Subclasses must create an {@code WebHttpHandlerBuilder} that will then
* be used to create the HttpHandler for the mock server.
*/
protected abstract WebHttpHandlerBuilder initHttpHandlerBuilder();
@Override
public WebTestClient build() {
return configureClient().build();
}
}
| AbstractMockServerSpec |
java | apache__kafka | connect/runtime/src/test/java/org/apache/kafka/connect/integration/RestExtensionIntegrationTest.java | {
"start": 7440,
"end": 8614
} | class ____ implements ConnectRestExtension {
private static IntegrationTestRestExtension instance;
public ConnectRestExtensionContext restPluginContext;
@Override
public void register(ConnectRestExtensionContext restPluginContext) {
instance = this;
this.restPluginContext = restPluginContext;
// Immediately request a list of connectors to confirm that the context and its fields
// has been fully initialized and there is no risk of deadlock
restPluginContext.clusterState().connectors();
// Install a new REST resource that can be used to confirm that the extension has been
// successfully registered
restPluginContext.configurable().register(new IntegrationTestRestExtensionResource());
}
@Override
public void close() {
}
@Override
public void configure(Map<String, ?> configs) {
}
@Override
public String version() {
return "test";
}
@Path("integration-test-rest-extension")
public static | IntegrationTestRestExtension |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/operator/mvdedupe/BatchEncoder.java | {
"start": 19615,
"end": 21074
} | class ____ extends MVEncoder {
protected BytesRefs(int batchSize) {
super(batchSize);
}
/**
* Is there capacity for {@code totalBytes} and spread across
* {@code #count} {@link BytesRef}s? You could call this with something
* like {@code hasCapacity(Arrays.stream(bytes).mapToInt(b -> b.length).sum(), bytes.length)}.
*/
protected final boolean hasCapacity(int totalBytes, int count) {
return bytes.length() + totalBytes + count * Integer.BYTES <= bytesCapacity();
}
/**
* Make sure there is capacity for {@code totalBytes} and spread across
* {@code #count} {@link BytesRef}s? You could call this with something
* like {@code ensureCapacity(Arrays.stream(bytes).mapToInt(b -> b.length).sum(), bytes.length)}.
*/
protected final void ensureCapacity(int totalBytes, int count) {
// TODO some protection against growing to gigabytes or whatever
bytes.grow(totalBytes + count * Integer.BYTES);
}
/**
* Encode a {@link BytesRef} and advance to the next position.
*/
protected final void encode(BytesRef v) {
addingValue();
intHandle.set(bytes.bytes(), bytes.length(), v.length);
bytes.setLength(bytes.length() + Integer.BYTES);
bytes.append(v);
}
}
protected static final | BytesRefs |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/FindIdentifiersTest.java | {
"start": 38698,
"end": 38871
} | class ____ {}
""")
.addSourceLines(
"Test.java",
"""
package pkg;
// BUG: Diagnostic contains:
| A |
java | grpc__grpc-java | api/src/test/java/io/grpc/MetadataTest.java | {
"start": 1676,
"end": 2098
} | class ____ {
private static final Metadata.BinaryMarshaller<Fish> FISH_MARSHALLER =
new Metadata.BinaryMarshaller<Fish>() {
@Override
public byte[] toBytes(Fish fish) {
return fish.name.getBytes(UTF_8);
}
@Override
public Fish parseBytes(byte[] serialized) {
return new Fish(new String(serialized, UTF_8));
}
};
private static | MetadataTest |
java | redisson__redisson | redisson/src/main/java/org/redisson/api/stream/StreamCountArgs.java | {
"start": 684,
"end": 887
} | interface ____ {
/**
* Defines messages count limit.
*
* @param count amount of messages
* @return next options
*/
StreamPendingRangeArgs count(int count);
}
| StreamCountArgs |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.