language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__camel | dsl/camel-kamelet-main/src/main/java/org/apache/camel/main/download/NoopRoutesBuilderLoader.java | {
"start": 999,
"end": 1426
} | class ____ extends RouteBuilderLoaderSupport {
protected NoopRoutesBuilderLoader(String extension) {
super(extension);
}
@Override
protected RouteBuilder doLoadRouteBuilder(Resource resource) throws Exception {
return new RouteBuilder() {
@Override
public void configure() throws Exception {
// noop
}
};
}
}
| NoopRoutesBuilderLoader |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/ext/javatime/deser/DurationDeserTest.java | {
"start": 986,
"end": 1253
} | class ____ extends DateTimeTestBase
{
private final ObjectReader READER = newMapper().readerFor(Duration.class);
private final TypeReference<Map<String, Duration>> MAP_TYPE_REF = new TypeReference<Map<String, Duration>>() { };
final static | DurationDeserTest |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/security/oauthbearer/internals/secured/BasicOAuthBearerToken.java | {
"start": 1460,
"end": 6218
} | class ____ implements OAuthBearerToken {
private final String token;
private final Set<String> scopes;
private final Long lifetimeMs;
private final String principalName;
private final Long startTimeMs;
/**
* Creates a new OAuthBearerToken instance around the given values.
*
* @param token Value containing the compact serialization as a base 64 string that
* can be parsed, decoded, and validated as a well-formed JWS. Must be
* non-<code>null</code>, non-blank, and non-whitespace only.
* @param scopes Set of non-<code>null</code> scopes. May contain case-sensitive
* "duplicates". The given set is copied and made unmodifiable so neither
* the caller of this constructor nor any downstream users can modify it.
* @param lifetimeMs The token's lifetime, expressed as the number of milliseconds since the
* epoch. Must be non-negative.
* @param principalName The name of the principal to which this credential applies. Must be
* non-<code>null</code>, non-blank, and non-whitespace only.
* @param startTimeMs The token's start time, expressed as the number of milliseconds since
* the epoch, if available, otherwise <code>null</code>. Must be
* non-negative if a non-<code>null</code> value is provided.
*/
public BasicOAuthBearerToken(String token,
Set<String> scopes,
long lifetimeMs,
String principalName,
Long startTimeMs) {
this.token = token;
this.scopes = scopes;
this.lifetimeMs = lifetimeMs;
this.principalName = principalName;
this.startTimeMs = startTimeMs;
}
/**
* The <code>b64token</code> value as defined in
* <a href="https://tools.ietf.org/html/rfc6750#section-2.1">RFC 6750 Section
* 2.1</a>
*
* @return <code>b64token</code> value as defined in
* <a href="https://tools.ietf.org/html/rfc6750#section-2.1">RFC 6750
* Section 2.1</a>
*/
@Override
public String value() {
return token;
}
/**
* The token's scope of access, as per
* <a href="https://tools.ietf.org/html/rfc6749#section-1.4">RFC 6749 Section
* 1.4</a>
*
* @return the token's (always non-null but potentially empty) scope of access,
* as per <a href="https://tools.ietf.org/html/rfc6749#section-1.4">RFC
* 6749 Section 1.4</a>. Note that all values in the returned set will
* be trimmed of preceding and trailing whitespace, and the result will
* never contain the empty string.
*/
@Override
public Set<String> scope() {
// Immutability of the set is performed in the constructor/validation utils class, so
// we don't need to repeat it here.
return scopes;
}
/**
* The token's lifetime, expressed as the number of milliseconds since the
* epoch, as per <a href="https://tools.ietf.org/html/rfc6749#section-1.4">RFC
* 6749 Section 1.4</a>
*
* @return the token's lifetime, expressed as the number of milliseconds since
* the epoch, as per
* <a href="https://tools.ietf.org/html/rfc6749#section-1.4">RFC 6749
* Section 1.4</a>.
*/
@Override
public long lifetimeMs() {
return lifetimeMs;
}
/**
* The name of the principal to which this credential applies
*
* @return the always non-null/non-empty principal name
*/
@Override
public String principalName() {
return principalName;
}
/**
* When the credential became valid, in terms of the number of milliseconds
* since the epoch, if known, otherwise null. An expiring credential may not
* necessarily indicate when it was created -- just when it expires -- so we
* need to support a null return value here.
*
* @return the time when the credential became valid, in terms of the number of
* milliseconds since the epoch, if known, otherwise null
*/
@Override
public Long startTimeMs() {
return startTimeMs;
}
@Override
public String toString() {
return new StringJoiner(", ", BasicOAuthBearerToken.class.getSimpleName() + "[", "]")
.add("token='" + token + "'")
.add("scopes=" + scopes)
.add("lifetimeMs=" + lifetimeMs)
.add("principalName='" + principalName + "'")
.add("startTimeMs=" + startTimeMs)
.toString();
}
}
| BasicOAuthBearerToken |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/deser/SettableBeanProperty.java | {
"start": 1166,
"end": 1919
} | class ____
extends ConcreteBeanPropertyBase
{
/**
* To avoid nasty NPEs, let's use a placeholder for _valueDeserializer,
* if real deserializer is not (yet) available.
*/
protected static final ValueDeserializer<Object> MISSING_VALUE_DESERIALIZER = new FailingDeserializer(
"No _valueDeserializer assigned");
/**
* Logical name of the property (often but not always derived
* from the setter method name)
*/
protected final PropertyName _propName;
/**
* Base type for property; may be a supertype of actual value.
*/
protected final JavaType _type;
protected final PropertyName _wrapperName;
/**
* Class that contains this property (either | SettableBeanProperty |
java | elastic__elasticsearch | x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/process/IndexingStateProcessor.java | {
"start": 6390,
"end": 11513
} | class ____.
*/
void findAppropriateIndexOrAliasAndPersist(BytesReference bytes) throws IOException {
String firstNonBlankLine = extractFirstNonBlankLine(bytes);
if (firstNonBlankLine == null) {
return;
}
String stateDocId = extractDocId(firstNonBlankLine);
String indexOrAlias = getConcreteIndexOrWriteAlias(stateDocId);
persist(indexOrAlias, bytes);
}
void persist(String indexOrAlias, BytesReference bytes) throws IOException {
BulkRequest bulkRequest = new BulkRequest().setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.requireAlias(AnomalyDetectorsIndex.jobStateIndexWriteAlias().equals(indexOrAlias));
bulkRequest.add(bytes, indexOrAlias, XContentType.JSON);
if (bulkRequest.numberOfActions() > 0) {
LOGGER.trace("[{}] Persisting job state document: index [{}], length [{}]", jobId, indexOrAlias, bytes.length());
try {
resultsPersisterService.bulkIndexWithRetry(
bulkRequest,
jobId,
() -> true,
retryMessage -> LOGGER.debug("[{}] Bulk indexing of state failed {}", jobId, retryMessage)
);
} catch (Exception ex) {
String msg = "failed indexing updated state docs";
LOGGER.error(() -> format("[%s] %s", jobId, msg), ex);
auditor.error(jobId, msg + " error: " + ex.getMessage());
}
}
}
private static int findNextZeroByte(BytesReference bytesRef, int searchFrom, int splitFrom) {
return bytesRef.indexOf((byte) 0, Math.max(searchFrom, splitFrom));
}
@SuppressWarnings("unchecked")
/*
* Extracts document id from the given {@code bytesRef}.
* Only first non-blank line is parsed and document id is assumed to be a nested "index._id" field of type String.
*/
static String extractDocId(String firstNonBlankLine) throws IOException {
try (XContentParser parser = JsonXContent.jsonXContent.createParser(XContentParserConfiguration.EMPTY, firstNonBlankLine)) {
Map<String, Object> map = parser.map();
if ((map.get("index") instanceof Map) == false) {
throw new IllegalStateException("Could not extract \"index\" field out of [" + firstNonBlankLine + "]");
}
map = (Map<String, Object>) map.get("index");
if ((map.get("_id") instanceof String) == false) {
throw new IllegalStateException("Could not extract \"index._id\" field out of [" + firstNonBlankLine + "]");
}
return (String) map.get("_id");
}
}
/**
* Extracts the first non-blank line from the given {@code bytesRef}.
* Lines are separated by the new line character ('\n').
* A line is considered blank if it only consists of space characters (' ').
*/
private static String extractFirstNonBlankLine(BytesReference bytesRef) {
for (int searchFrom = 0; searchFrom < bytesRef.length();) {
int newLineMarkerIndex = bytesRef.indexOf((byte) '\n', searchFrom);
int searchTo = newLineMarkerIndex != -1 ? newLineMarkerIndex : bytesRef.length();
if (isBlank(bytesRef, searchFrom, searchTo) == false) {
return bytesRef.slice(searchFrom, searchTo - searchFrom).utf8ToString();
}
searchFrom = newLineMarkerIndex != -1 ? newLineMarkerIndex + 1 : bytesRef.length();
}
return null;
}
/**
* Checks whether the line pointed to by a pair of indexes: {@code from} (inclusive) and {@code to} (exclusive) is blank.
* A line is considered blank if it only consists of space characters (' ').
*/
private static boolean isBlank(BytesReference bytesRef, int from, int to) {
for (int i = from; i < to; ++i) {
if (bytesRef.get(i) != ((byte) ' ')) {
return false;
}
}
return true;
}
private String getConcreteIndexOrWriteAlias(String documentId) {
Objects.requireNonNull(documentId);
SearchRequest searchRequest = new SearchRequest(AnomalyDetectorsIndex.jobStateIndexPattern()).allowPartialSearchResults(false)
.source(
new SearchSourceBuilder().size(1)
.fetchSource(false)
.trackTotalHits(false)
.query(new BoolQueryBuilder().filter(new IdsQueryBuilder().addIds(documentId)))
);
SearchResponse searchResponse = resultsPersisterService.searchWithRetry(
searchRequest,
jobId,
() -> true,
retryMessage -> LOGGER.debug("[{}] {} {}", jobId, documentId, retryMessage)
);
try {
return searchResponse.getHits().getHits().length > 0
? searchResponse.getHits().getHits()[0].getIndex()
: AnomalyDetectorsIndex.jobStateIndexWriteAlias();
} finally {
searchResponse.decRef();
}
}
}
| documentation |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/aggregation/ValuesLongAggregator.java | {
"start": 4900,
"end": 9541
} | class ____ implements Releasable {
private final BlockFactory blockFactory;
private final LongLongHash hashes;
private int[] selectedCounts = null;
private int[] ids = null;
private long extraMemoryUsed = 0;
private NextValues(BlockFactory blockFactory) {
this.blockFactory = blockFactory;
this.hashes = new LongLongHash(1, blockFactory.bigArrays());
}
void addValue(int groupId, long v) {
hashes.add(groupId, v);
}
long getValue(int index) {
return hashes.getKey2(ids[index]);
}
private void reserveBytesForIntArray(long numElements) {
long adjust = RamUsageEstimator.alignObjectSize(RamUsageEstimator.NUM_BYTES_ARRAY_HEADER + numElements * Integer.BYTES);
blockFactory.adjustBreaker(adjust);
extraMemoryUsed += adjust;
}
private void prepareForEmitting(IntVector selected) {
if (hashes.size() == 0) {
return;
}
/*
* Get a count of all groups less than the maximum selected group. Count
* *downwards* so that we can flip the sign on all of the actually selected
* groups. Negative values in this array are always unselected groups.
*/
int selectedCountsLen = selected.max() + 1;
reserveBytesForIntArray(selectedCountsLen);
this.selectedCounts = new int[selectedCountsLen];
for (int id = 0; id < hashes.size(); id++) {
int group = (int) hashes.getKey1(id);
if (group < selectedCounts.length) {
selectedCounts[group]--;
}
}
/*
* Total the selected groups and turn the counts into the start index into a sort-of
* off-by-one running count. It's really the number of values that have been inserted
* into the results before starting on this group. Unselected groups will still
* have negative counts.
*
* For example, if
* | Group | Value Count | Selected |
* |-------|-------------|----------|
* | 0 | 3 | <- |
* | 1 | 1 | <- |
* | 2 | 2 | |
* | 3 | 1 | <- |
* | 4 | 4 | <- |
*
* Then the total is 9 and the counts array will contain 0, 3, -2, 4, 5
*/
int total = 0;
for (int s = 0; s < selected.getPositionCount(); s++) {
int group = selected.getInt(s);
int count = -selectedCounts[group];
selectedCounts[group] = total;
total += count;
}
/*
* Build a list of ids to insert in order *and* convert the running
* count in selectedCounts[group] into the end index (exclusive) in
* ids for each group.
* Here we use the negative counts to signal that a group hasn't been
* selected and the id containing values for that group is ignored.
*
* For example, if
* | Group | Value Count | Selected |
* |-------|-------------|----------|
* | 0 | 3 | <- |
* | 1 | 1 | <- |
* | 2 | 2 | |
* | 3 | 1 | <- |
* | 4 | 4 | <- |
*
* Then the total is 9 and the counts array will start with 0, 3, -2, 4, 5.
* The counts will end with 3, 4, -2, 5, 9.
*/
reserveBytesForIntArray(total);
this.ids = new int[total];
for (int id = 0; id < hashes.size(); id++) {
int group = (int) hashes.getKey1(id);
ids[selectedCounts[group]++] = id;
}
}
@Override
public void close() {
Releasables.closeExpectNoException(hashes, () -> blockFactory.adjustBreaker(-extraMemoryUsed));
}
}
/**
* State for a grouped {@code VALUES} aggregation. This implementation
* emphasizes collect-time performance over result rendering performance.
* The first value in each group is collected in the {@code firstValues}
* array, and subsequent values for each group are collected in {@code nextValues}.
*/
public static | NextValues |
java | elastic__elasticsearch | x-pack/plugin/transform/qa/single-node-tests/src/javaRestTest/java/org/elasticsearch/xpack/transform/integration/TransformDeleteIT.java | {
"start": 829,
"end": 11740
} | class ____ extends TransformRestTestCase {
private static final String TEST_USER_NAME = "transform_user";
private static final String TEST_ADMIN_USER_NAME_1 = "transform_admin_1";
private static final String BASIC_AUTH_VALUE_TRANSFORM_ADMIN_1 = basicAuthHeaderValue(
TEST_ADMIN_USER_NAME_1,
TEST_PASSWORD_SECURE_STRING
);
private static final String DATA_ACCESS_ROLE = "test_data_access";
private static boolean indicesCreated = false;
// preserve indices in order to reuse source indices in several test cases
@Override
protected boolean preserveIndicesUponCompletion() {
return true;
}
@Override
protected boolean enableWarningsCheck() {
return false;
}
@Override
protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException {
RestClientBuilder builder = RestClient.builder(hosts);
configureClient(builder, settings);
builder.setStrictDeprecationMode(false);
return builder.build();
}
@Before
public void createIndexes() throws IOException {
setupDataAccessRole(DATA_ACCESS_ROLE, REVIEWS_INDEX_NAME);
setupUser(TEST_USER_NAME, Arrays.asList("transform_user", DATA_ACCESS_ROLE));
setupUser(TEST_ADMIN_USER_NAME_1, Arrays.asList("transform_admin", DATA_ACCESS_ROLE));
// it's not possible to run it as @BeforeClass as clients aren't initialized then, so we need this little hack
if (indicesCreated) {
return;
}
createReviewsIndex();
indicesCreated = true;
}
public void testDeleteDoesNotDeleteDestinationIndexByDefault() throws Exception {
String transformId = "transform-1";
String transformDest = transformId + "_idx";
String transformDestAlias = transformId + "_alias";
setupDataAccessRole(DATA_ACCESS_ROLE, REVIEWS_INDEX_NAME, transformDest, transformDestAlias);
createTransform(transformId, transformDest, transformDestAlias);
assertFalse(indexExists(transformDest));
assertFalse(aliasExists(transformDestAlias));
startTransform(transformId);
waitForTransformCheckpoint(transformId, 1);
stopTransform(transformId, false);
assertTrue(indexExists(transformDest));
assertTrue(aliasExists(transformDestAlias));
deleteTransform(transformId);
assertTrue(indexExists(transformDest));
assertTrue(aliasExists(transformDestAlias));
}
public void testDeleteWithParamDeletesAutoCreatedDestinationIndex() throws Exception {
String transformId = "transform-2";
String transformDest = transformId + "_idx";
String transformDestAlias = transformId + "_alias";
setupDataAccessRole(DATA_ACCESS_ROLE, REVIEWS_INDEX_NAME, transformDest, transformDestAlias);
createTransform(transformId, transformDest, transformDestAlias);
assertFalse(indexExists(transformDest));
assertFalse(aliasExists(transformDestAlias));
startTransform(transformId);
waitForTransformCheckpoint(transformId, 1);
stopTransform(transformId, false);
assertTrue(indexExists(transformDest));
assertTrue(aliasExists(transformDestAlias));
deleteTransform(transformId, false, true);
assertFalse(indexExists(transformDest));
assertFalse(aliasExists(transformDestAlias));
}
public void testDeleteWithParamDeletesManuallyCreatedDestinationIndex() throws Exception {
String transformId = "transform-3";
String transformDest = transformId + "_idx";
String transformDestAlias = transformId + "_alias";
setupDataAccessRole(DATA_ACCESS_ROLE, REVIEWS_INDEX_NAME, transformDest, transformDestAlias);
createIndex(transformDest);
assertTrue(indexExists(transformDest));
// The alias does not exist yet, it will be created when the transform starts
assertFalse(aliasExists(transformDestAlias));
createTransform(transformId, transformDest, transformDestAlias);
assertFalse(aliasExists(transformDestAlias));
startTransform(transformId);
waitForTransformCheckpoint(transformId, 1);
stopTransform(transformId, false);
assertTrue(indexExists(transformDest));
assertTrue(aliasExists(transformDestAlias));
deleteTransform(transformId, false, true);
assertFalse(indexExists(transformDest));
assertFalse(aliasExists(transformDestAlias));
}
public void testDeleteWithManuallyCreatedIndexAndManuallyCreatedAlias() throws Exception {
String transformId = "transform-4";
String transformDest = transformId + "_idx";
String transformDestAlias = transformId + "_alias";
setupDataAccessRole(DATA_ACCESS_ROLE, REVIEWS_INDEX_NAME, transformDest, transformDestAlias);
createIndex(transformDest, null, null, "\"" + transformDestAlias + "\": { \"is_write_index\": true }");
assertTrue(indexExists(transformDest));
assertTrue(aliasExists(transformDestAlias));
createTransform(transformId, transformDestAlias, null);
startTransform(transformId);
waitForTransformCheckpoint(transformId, 1);
stopTransform(transformId, false);
assertTrue(indexExists(transformDest));
assertTrue(aliasExists(transformDestAlias));
deleteTransform(transformId, false, true);
assertFalse(indexExists(transformDest));
assertFalse(aliasExists(transformDestAlias));
}
public void testDeleteDestinationIndexIsNoOpWhenNoDestinationIndexExists() throws Exception {
String transformId = "transform-5";
String transformDest = transformId + "_idx";
String transformDestAlias = transformId + "_alias";
setupDataAccessRole(DATA_ACCESS_ROLE, REVIEWS_INDEX_NAME, transformDest, transformDestAlias);
createTransform(transformId, transformDest, transformDestAlias);
assertFalse(indexExists(transformDest));
assertFalse(aliasExists(transformDestAlias));
deleteTransform(transformId, false, true);
assertFalse(indexExists(transformDest));
assertFalse(aliasExists(transformDestAlias));
}
public void testDeleteWithAliasPointingToManyIndices() throws Exception {
var transformId = "transform-6";
var transformDest = transformId + "_idx";
var otherIndex = "some-other-index-6";
String transformDestAlias = transformId + "_alias";
setupDataAccessRole(DATA_ACCESS_ROLE, REVIEWS_INDEX_NAME, transformDest, otherIndex, transformDestAlias);
createIndex(transformDest, null, null, "\"" + transformDestAlias + "\": { \"is_write_index\": true }");
createIndex(otherIndex, null, null, "\"" + transformDestAlias + "\": {}");
assertTrue(indexExists(transformDest));
assertTrue(indexExists(otherIndex));
assertTrue(aliasExists(transformDestAlias));
createTransform(transformId, transformDestAlias, null);
startTransform(transformId);
waitForTransformCheckpoint(transformId, 1);
stopTransform(transformId, false);
assertTrue(indexExists(transformDest));
assertTrue(indexExists(otherIndex));
assertTrue(aliasExists(transformDestAlias));
deleteTransform(transformId, false, true);
assertFalse(indexExists(transformDest));
assertTrue(indexExists(otherIndex));
assertTrue(aliasExists(transformDestAlias));
}
public void testDeleteWithNoWriteIndexThrowsException() throws Exception {
var transformId = "transform-7";
var transformDest = transformId + "_idx";
var otherIndex = "some-other-index-7";
String transformDestAlias = transformId + "_alias";
setupDataAccessRole(DATA_ACCESS_ROLE, REVIEWS_INDEX_NAME, transformDest, otherIndex, transformDestAlias);
createIndex(transformDest, null, null, "\"" + transformDestAlias + "\": {}");
assertTrue(indexExists(transformDest));
assertTrue(aliasExists(transformDestAlias));
createTransform(transformId, transformDestAlias, null);
createIndex(otherIndex, null, null, "\"" + transformDestAlias + "\": {}");
assertTrue(indexExists(otherIndex));
ResponseException e = expectThrows(ResponseException.class, () -> deleteTransform(transformId, false, true));
assertThat(
e.getMessage(),
containsString(
Strings.format(
"Cannot disambiguate destination index alias [%s]. Alias points to many indices with no clear write alias."
+ " Retry with delete_dest_index=false and manually clean up destination index.",
transformDestAlias
)
)
);
}
public void testDeleteWithAlreadyDeletedIndex() throws Exception {
var transformId = "transform-8";
var transformDest = transformId + "_idx";
setupDataAccessRole(DATA_ACCESS_ROLE, REVIEWS_INDEX_NAME, transformDest);
createIndex(transformDest);
assertTrue(indexExists(transformDest));
createTransform(transformId, transformDest, null);
deleteIndex(transformDest);
assertFalse(indexExists(transformDest));
deleteTransform(transformId, false, true);
assertFalse(indexExists(transformDest));
}
private void createTransform(String transformId, String destIndex, String destAlias) throws IOException {
final Request createTransformRequest = createRequestWithAuth(
"PUT",
getTransformEndpoint() + transformId,
BASIC_AUTH_VALUE_TRANSFORM_ADMIN_1
);
String destAliases = destAlias != null ? Strings.format("""
, "aliases": [{"alias": "%s"}]
""", destAlias) : "";
String config = Strings.format("""
{
"dest": {
"index": "%s"
%s
},
"source": {
"index": "%s"
},
"pivot": {
"group_by": {
"reviewer": {
"terms": {
"field": "user_id"
}
}
},
"aggregations": {
"avg_rating": {
"avg": {
"field": "stars"
}
}
}
}
}""", destIndex, destAliases, REVIEWS_INDEX_NAME);
createTransformRequest.setJsonEntity(config);
Map<String, Object> createTransformResponse = entityAsMap(client().performRequest(createTransformRequest));
assertThat(createTransformResponse.get("acknowledged"), equalTo(Boolean.TRUE));
}
}
| TransformDeleteIT |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/util/pool/StateVerifier.java | {
"start": 1236,
"end": 1918
} | class ____ extends StateVerifier {
// Keeps track of the stack trace where our state was set to recycled.
private volatile RuntimeException recycledAtStackTraceException;
@Synthetic
DebugStateVerifier() {}
@Override
public void throwIfRecycled() {
if (recycledAtStackTraceException != null) {
throw new IllegalStateException("Already released", recycledAtStackTraceException);
}
}
@Override
void setRecycled(boolean isRecycled) {
if (isRecycled) {
recycledAtStackTraceException = new RuntimeException("Released");
} else {
recycledAtStackTraceException = null;
}
}
}
}
| DebugStateVerifier |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/CamelEvent.java | {
"start": 11048,
"end": 11603
} | interface ____ extends RouteEvent, FailureEvent {
/**
* Failure attempt (0 = initial start, 1 = first restart attempt)
*/
long getAttempt();
/**
* Whether all restarts have failed and the route controller will not attempt to restart the route anymore due
* to maximum attempts reached and being exhausted.
*/
boolean isExhausted();
@Override
default Type getType() {
return Type.RouteRestartingFailure;
}
}
| RouteRestartingFailureEvent |
java | spring-projects__spring-boot | core/spring-boot-test/src/test/java/org/springframework/boot/test/util/ApplicationContextTestUtilsTests.java | {
"start": 1046,
"end": 1805
} | class ____ {
@Test
void closeNull() {
ApplicationContextTestUtils.closeAll(null);
}
@Test
void closeNonClosableContext() {
ApplicationContext mock = mock(ApplicationContext.class);
ApplicationContextTestUtils.closeAll(mock);
}
@Test
void closeContextAndParent() {
ConfigurableApplicationContext mock = mock(ConfigurableApplicationContext.class);
ConfigurableApplicationContext parent = mock(ConfigurableApplicationContext.class);
given(mock.getParent()).willReturn(parent);
given(parent.getParent()).willReturn(null);
ApplicationContextTestUtils.closeAll(mock);
then(mock).should().getParent();
then(mock).should().close();
then(parent).should().getParent();
then(parent).should().close();
}
}
| ApplicationContextTestUtilsTests |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/update/MySqlUpdateTest_8.java | {
"start": 1059,
"end": 2911
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "update haskell_function set `arity` = arity-'1' where id = 1;";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
print(statementList);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
stmt.accept(visitor);
// System.out.println("Tables : " + visitor.getTables());
// System.out.println("fields : " + visitor.getColumns());
// System.out.println("coditions : " + visitor.getConditions());
// System.out.println("orderBy : " + visitor.getOrderByColumns());
assertEquals(1, visitor.getTables().size());
assertEquals(2, visitor.getColumns().size());
assertEquals(1, visitor.getConditions().size());
assertTrue(visitor.getTables().containsKey(new TableStat.Name("haskell_function")));
assertTrue(visitor.getColumns().contains(new Column("haskell_function", "arity")));
assertTrue(visitor.getColumns().contains(new Column("haskell_function", "id")));
{
String output = SQLUtils.toMySqlString(stmt);
assertEquals("UPDATE haskell_function"
+ "\nSET `arity` = arity - '1'"
+ "\nWHERE id = 1;", //
output);
}
{
String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
assertEquals("update haskell_function"
+ "\nset `arity` = arity - '1'"
+ "\nwhere id = 1;", //
output);
}
}
}
| MySqlUpdateTest_8 |
java | quarkusio__quarkus | extensions/reactive-mysql-client/deployment/src/test/java/io/quarkus/reactive/mysql/client/MySQLPoolCreatorTest.java | {
"start": 268,
"end": 951
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClass(CustomCredentialsProvider.class)
.addClass(CredentialsTestResource.class)
.addClass(LocalhostMySQLPoolCreator.class)
.addAsResource("application-credentials-with-erroneous-url.properties", "application.properties"));
@Test
public void testConnect() {
given()
.when().get("/test")
.then()
.statusCode(200)
.body(CoreMatchers.equalTo("OK"));
}
}
| MySQLPoolCreatorTest |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/ErrorProneFlagsTest.java | {
"start": 4938,
"end": 6266
} | enum ____ {
RED,
YELLOW,
GREEN
}
@Test
public void enumFlags() {
ErrorProneFlags flags =
ErrorProneFlags.builder()
.parseFlag("-XepOpt:Colour=RED")
.parseFlag("-XepOpt:Colours=YELLOW,GREEN")
.parseFlag("-XepOpt:CaseInsensitiveColours=yellow,green")
.parseFlag("-XepOpt:EmptyColours=")
.build();
assertThat(flags.getEnum("Colour", Colour.class)).hasValue(Colour.RED);
assertThat(flags.getEnumSet("Colours", Colour.class))
.hasValue(ImmutableSet.of(Colour.YELLOW, Colour.GREEN));
assertThat(flags.getEnumSet("CaseInsensitiveColours", Colour.class))
.hasValue(ImmutableSet.of(Colour.YELLOW, Colour.GREEN));
assertThat(flags.getEnumSet("EmptyColours", Colour.class)).hasValue(ImmutableSet.of());
assertThat(flags.getEnumSet("NoSuchColours", Colour.class)).isEmpty();
}
@Test
public void invalidEnumFlags() {
ErrorProneFlags flags =
ErrorProneFlags.builder()
.parseFlag("-XepOpt:Colour=NOSUCH")
.parseFlag("-XepOpt:Colours=YELLOW,NOSUCH")
.build();
assertThrows(IllegalArgumentException.class, () -> flags.getEnum("Colour", Colour.class));
assertThrows(IllegalArgumentException.class, () -> flags.getEnumSet("Colours", Colour.class));
}
}
| Colour |
java | spring-projects__spring-security | oauth2/oauth2-client/src/test/java/org/springframework/security/oauth2/client/endpoint/RestClientAuthorizationCodeTokenResponseClientTests.java | {
"start": 3208,
"end": 15316
} | class ____ {
private RestClientAuthorizationCodeTokenResponseClient tokenResponseClient;
private MockWebServer server;
private ClientRegistration.Builder clientRegistration;
private OAuth2AuthorizationExchange authorizationExchange;
@BeforeEach
public void setUp() throws IOException {
this.tokenResponseClient = new RestClientAuthorizationCodeTokenResponseClient();
this.server = new MockWebServer();
this.server.start();
String tokenUri = this.server.url("/oauth2/token").toString();
this.clientRegistration = TestClientRegistrations.clientRegistration()
.clientId("client-1")
.clientSecret("secret")
.authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
.tokenUri(tokenUri)
.scope("read", "write");
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationRequest authorizationRequest = OAuth2AuthorizationRequest.authorizationCode()
.clientId("client-1")
.state("state")
.authorizationUri(clientRegistration.getProviderDetails().getAuthorizationUri())
.redirectUri(clientRegistration.getRedirectUri())
.scopes(clientRegistration.getScopes())
.build();
OAuth2AuthorizationResponse authorizationResponse = OAuth2AuthorizationResponse.success("code")
.state("state")
.redirectUri(clientRegistration.getRedirectUri())
.build();
this.authorizationExchange = new OAuth2AuthorizationExchange(authorizationRequest, authorizationResponse);
}
@AfterEach
public void cleanUp() throws IOException {
this.server.shutdown();
}
@Test
public void setRestClientWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.setRestClient(null))
.withMessage("restClient cannot be null");
// @formatter:on
}
@Test
public void setHeadersConverterWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.setHeadersConverter(null))
.withMessage("headersConverter cannot be null");
// @formatter:on
}
@Test
public void addHeadersConverterWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.addHeadersConverter(null))
.withMessage("headersConverter cannot be null");
// @formatter:on
}
@Test
public void setParametersConverterWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.setParametersConverter(null))
.withMessage("parametersConverter cannot be null");
// @formatter:on
}
@Test
public void addParametersConverterWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.addParametersConverter(null))
.withMessage("parametersConverter cannot be null");
// @formatter:on
}
@Test
public void setParametersCustomizerWhenNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.setParametersCustomizer(null))
.withMessage("parametersCustomizer cannot be null");
// @formatter:on
}
@Test
public void getTokenResponseWhenGrantRequestIsNullThenThrowIllegalArgumentException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(null))
.withMessage("grantRequest cannot be null");
// @formatter:on
}
@Test
public void getTokenResponseWhenSuccessResponseThenReturnAccessTokenResponse() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response-read-write.json"));
Instant expiresAtBefore = Instant.now().plusSeconds(3600);
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration,
this.authorizationExchange);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(grantRequest);
assertThat(accessTokenResponse).isNotNull();
Instant expiresAtAfter = Instant.now().plusSeconds(3600);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getMethod()).isEqualTo(HttpMethod.POST.toString());
assertThat(recordedRequest.getHeader(HttpHeaders.ACCEPT)).isEqualTo(MediaType.APPLICATION_JSON_VALUE);
assertThat(recordedRequest.getHeader(HttpHeaders.CONTENT_TYPE))
.isEqualTo(MediaType.APPLICATION_FORM_URLENCODED_VALUE);
String formParameters = recordedRequest.getBody().readUtf8();
// @formatter:off
assertThat(formParameters).contains(
param(OAuth2ParameterNames.GRANT_TYPE, AuthorizationGrantType.AUTHORIZATION_CODE.getValue()),
param(OAuth2ParameterNames.CODE, "code")
);
// @formatter:on
assertThat(accessTokenResponse.getAccessToken().getTokenValue()).isEqualTo("access-token-1234");
assertThat(accessTokenResponse.getAccessToken().getTokenType()).isEqualTo(OAuth2AccessToken.TokenType.BEARER);
assertThat(accessTokenResponse.getAccessToken().getExpiresAt()).isBetween(expiresAtBefore, expiresAtAfter);
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactlyInAnyOrder("read", "write");
assertThat(accessTokenResponse.getRefreshToken()).isNull();
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretBasicThenAuthorizationHeaderIsSent() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration,
this.authorizationExchange);
this.tokenResponseClient.getTokenResponse(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
assertThat(recordedRequest.getHeader(HttpHeaders.AUTHORIZATION)).startsWith("Basic ");
}
@Test
public void getTokenResponseWhenAuthenticationClientSecretPostThenFormParametersAreSent() throws Exception {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_POST)
.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration,
this.authorizationExchange);
this.tokenResponseClient.getTokenResponse(grantRequest);
RecordedRequest recordedRequest = this.server.takeRequest();
String formParameters = recordedRequest.getBody().readUtf8();
// @formatter:off
assertThat(formParameters).contains(
param(OAuth2ParameterNames.CLIENT_ID, "client-1"),
param(OAuth2ParameterNames.CLIENT_SECRET, "secret")
);
// @formatter:on
}
@Test
public void getTokenResponseWhenSuccessResponseAndNotBearerTokenTypeThenThrowOAuth2AuthorizationException() {
this.server.enqueue(MockResponses.json("invalid-token-type-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration,
this.authorizationExchange);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(grantRequest))
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response")
.havingRootCause().withMessage("tokenType cannot be null");
// @formatter:on
}
@Test
public void getTokenResponseWhenSuccessResponseIncludesScopeThenAccessTokenHasResponseScope() {
this.server.enqueue(MockResponses.json("access-token-response-read.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration,
this.authorizationExchange);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(grantRequest);
assertThat(accessTokenResponse).isNotNull();
assertThat(accessTokenResponse.getAccessToken().getScopes()).containsExactly("read");
}
@Test
public void getTokenResponseWhenSuccessResponseDoesNotIncludeScopeThenAccessTokenHasNoScope() {
this.server.enqueue(MockResponses.json("access-token-response.json"));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration,
this.authorizationExchange);
OAuth2AccessTokenResponse accessTokenResponse = this.tokenResponseClient.getTokenResponse(grantRequest);
assertThat(accessTokenResponse).isNotNull();
assertThat(accessTokenResponse.getAccessToken().getScopes()).isEmpty();
}
@Test
public void getTokenResponseWhenInvalidResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(new MockResponse().setResponseCode(301));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest request = new OAuth2AuthorizationCodeGrantRequest(clientRegistration,
this.authorizationExchange);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(request))
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessage("[invalid_token_response] Empty OAuth 2.0 Access Token Response");
// @formatter:on
}
@Test
public void getTokenResponseWhenServerErrorResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(MockResponses.json("server-error-response.json").setResponseCode(500));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest request = new OAuth2AuthorizationCodeGrantRequest(clientRegistration,
this.authorizationExchange);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(request))
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo("invalid_token_response"))
.withMessageContaining("[invalid_token_response] An error occurred while attempting to retrieve the OAuth 2.0 Access Token Response");
// @formatter:on
}
@Test
public void getTokenResponseWhenErrorResponseThenThrowOAuth2AuthorizationException() {
this.server.enqueue(MockResponses.json("invalid-grant-response.json").setResponseCode(400));
ClientRegistration clientRegistration = this.clientRegistration.build();
OAuth2AuthorizationCodeGrantRequest request = new OAuth2AuthorizationCodeGrantRequest(clientRegistration,
this.authorizationExchange);
// @formatter:off
assertThatExceptionOfType(OAuth2AuthorizationException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(request))
.satisfies((ex) -> assertThat(ex.getError().getErrorCode()).isEqualTo(OAuth2ErrorCodes.INVALID_GRANT))
.withMessage("[invalid_grant] Invalid grant");
// @formatter:on
}
@Test
public void getTokenResponseWhenCustomClientAuthenticationMethodThenIllegalArgument() {
ClientRegistration clientRegistration = this.clientRegistration
.clientAuthenticationMethod(new ClientAuthenticationMethod("basic"))
.build();
OAuth2AuthorizationCodeGrantRequest grantRequest = new OAuth2AuthorizationCodeGrantRequest(clientRegistration,
this.authorizationExchange);
// @formatter:off
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> this.tokenResponseClient.getTokenResponse(grantRequest))
.withMessageContaining("This | RestClientAuthorizationCodeTokenResponseClientTests |
java | bumptech__glide | library/src/main/java/com/bumptech/glide/load/resource/gif/GifDrawableResource.java | {
"start": 299,
"end": 883
} | class ____ extends DrawableResource<GifDrawable> implements Initializable {
// Public API.
@SuppressWarnings("WeakerAccess")
public GifDrawableResource(GifDrawable drawable) {
super(drawable);
}
@NonNull
@Override
public Class<GifDrawable> getResourceClass() {
return GifDrawable.class;
}
@Override
public int getSize() {
return drawable.getSize();
}
@Override
public void recycle() {
drawable.stop();
drawable.recycle();
}
@Override
public void initialize() {
drawable.getFirstFrame().prepareToDraw();
}
}
| GifDrawableResource |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_77_is_unkown.java | {
"start": 1086,
"end": 2842
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "select 0 in (20 = any (select col1 from t1)) is not null is not unknown as t;";
System.out.println(sql);
SQLStatementParser parser = SQLParserUtils.createSQLStatementParser(sql, JdbcConstants.MYSQL, SQLParserFeature.OptimizedForParameterized);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement stmt = statementList.get(0);
assertEquals(1, statementList.size());
SchemaStatVisitor visitor = SQLUtils.createSchemaStatVisitor(JdbcConstants.MYSQL);
stmt.accept(visitor);
{
String output = SQLUtils.toMySqlString(stmt);
assertEquals("SELECT 0 IN (20 = ANY (\n" +
"\t\tSELECT col1\n" +
"\t\tFROM t1\n" +
"\t)) IS NOT NULL IS NOT unknown AS t;", //
output);
}
{
String output = SQLUtils.toMySqlString(stmt, SQLUtils.DEFAULT_LCASE_FORMAT_OPTION);
assertEquals("select 0 in (20 = any (\n" +
"\t\tselect col1\n" +
"\t\tfrom t1\n" +
"\t)) is not null is not unknown as t;", //
output);
}
{
String output = SQLUtils.toMySqlString(stmt, new SQLUtils.FormatOption(true, true, true));
assertEquals("SELECT ? IN (? = ANY (\n" +
"\t\tSELECT col1\n" +
"\t\tFROM t1\n" +
"\t)) IS NOT NULL IS NOT unknown AS t;", //
output);
}
}
}
| MySqlSelectTest_77_is_unkown |
java | apache__camel | catalog/camel-route-parser/src/main/java/org/apache/camel/parser/model/RestConfigurationDetails.java | {
"start": 905,
"end": 9424
} | class ____ {
// source code details
private String fileName;
private String lineNumber;
private String lineNumberEnd;
private int linePosition;
// java source code details
private String className;
private String methodName;
// camel rest configuration details
private String component;
private String apiComponent;
private String producerComponent;
private String scheme;
private String host;
private String apiHost;
private String port;
private String producerApiDoc;
private String contextPath;
private String apiContextPath;
private String apiVendorExtension;
private String hostNameResolver;
private String bindingMode;
private String skipBindingOnErrorCode;
private String clientRequestValidation;
private String clientResponseValidation;
private String enableCORS;
private String jsonDataFormat;
private String xmlDataFormat;
private Map<String, String> componentProperties;
private Map<String, String> endpointProperties;
private Map<String, String> consumerProperties;
private Map<String, String> dataFormatProperties;
private Map<String, String> apiProperties;
private Map<String, String> corsHeaders;
public RestConfigurationDetails() {
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getLineNumber() {
return lineNumber;
}
public void setLineNumber(String lineNumber) {
this.lineNumber = lineNumber;
}
public String getLineNumberEnd() {
return lineNumberEnd;
}
public void setLineNumberEnd(String lineNumberEnd) {
this.lineNumberEnd = lineNumberEnd;
}
public int getLinePosition() {
return linePosition;
}
public void setLinePosition(int linePosition) {
this.linePosition = linePosition;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethodName() {
return methodName;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getComponent() {
return component;
}
public void setComponent(String component) {
this.component = component;
}
public String getApiComponent() {
return apiComponent;
}
public void setApiComponent(String apiComponent) {
this.apiComponent = apiComponent;
}
public String getProducerComponent() {
return producerComponent;
}
public void setProducerComponent(String producerComponent) {
this.producerComponent = producerComponent;
}
public String getScheme() {
return scheme;
}
public void setScheme(String scheme) {
this.scheme = scheme;
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public String getApiHost() {
return apiHost;
}
public void setApiHost(String apiHost) {
this.apiHost = apiHost;
}
public String getPort() {
return port;
}
public void setPort(String port) {
this.port = port;
}
public String getProducerApiDoc() {
return producerApiDoc;
}
public void setProducerApiDoc(String producerApiDoc) {
this.producerApiDoc = producerApiDoc;
}
public String getContextPath() {
return contextPath;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public String getApiContextPath() {
return apiContextPath;
}
public void setApiContextPath(String apiContextPath) {
this.apiContextPath = apiContextPath;
}
public String getApiVendorExtension() {
return apiVendorExtension;
}
public void setApiVendorExtension(String apiVendorExtension) {
this.apiVendorExtension = apiVendorExtension;
}
public String getHostNameResolver() {
return hostNameResolver;
}
public void setHostNameResolver(String hostNameResolver) {
this.hostNameResolver = hostNameResolver;
}
public String getBindingMode() {
return bindingMode;
}
public void setBindingMode(String bindingMode) {
this.bindingMode = bindingMode;
}
public String getSkipBindingOnErrorCode() {
return skipBindingOnErrorCode;
}
public void setSkipBindingOnErrorCode(String skipBindingOnErrorCode) {
this.skipBindingOnErrorCode = skipBindingOnErrorCode;
}
public String getClientRequestValidation() {
return clientRequestValidation;
}
public void setClientRequestValidation(String clientRequestValidation) {
this.clientRequestValidation = clientRequestValidation;
}
public String getClientResponseValidation() {
return clientResponseValidation;
}
public void setClientResponseValidation(String clientResponseValidation) {
this.clientResponseValidation = clientResponseValidation;
}
public String getEnableCORS() {
return enableCORS;
}
public void setEnableCORS(String enableCORS) {
this.enableCORS = enableCORS;
}
public String getJsonDataFormat() {
return jsonDataFormat;
}
public void setJsonDataFormat(String jsonDataFormat) {
this.jsonDataFormat = jsonDataFormat;
}
public String getXmlDataFormat() {
return xmlDataFormat;
}
public void setXmlDataFormat(String xmlDataFormat) {
this.xmlDataFormat = xmlDataFormat;
}
public Map<String, String> getComponentProperties() {
return componentProperties;
}
public void setComponentProperties(Map<String, String> componentProperties) {
this.componentProperties = componentProperties;
}
public Map<String, String> getEndpointProperties() {
return endpointProperties;
}
public void setEndpointProperties(Map<String, String> endpointProperties) {
this.endpointProperties = endpointProperties;
}
public Map<String, String> getConsumerProperties() {
return consumerProperties;
}
public void setConsumerProperties(Map<String, String> consumerProperties) {
this.consumerProperties = consumerProperties;
}
public Map<String, String> getDataFormatProperties() {
return dataFormatProperties;
}
public void setDataFormatProperties(Map<String, String> dataFormatProperties) {
this.dataFormatProperties = dataFormatProperties;
}
public Map<String, String> getApiProperties() {
return apiProperties;
}
public void setApiProperties(Map<String, String> apiProperties) {
this.apiProperties = apiProperties;
}
public Map<String, String> getCorsHeaders() {
return corsHeaders;
}
public void setCorsHeaders(Map<String, String> corsHeaders) {
this.corsHeaders = corsHeaders;
}
public void addComponentProperty(String key, String value) {
if (componentProperties == null) {
componentProperties = new LinkedHashMap<>();
}
componentProperties.put(key, value);
}
public void addEndpointProperty(String key, String value) {
if (endpointProperties == null) {
endpointProperties = new LinkedHashMap<>();
}
endpointProperties.put(key, value);
}
public void addConsumerProperty(String key, String value) {
if (consumerProperties == null) {
consumerProperties = new LinkedHashMap<>();
}
consumerProperties.put(key, value);
}
public void addDataFormatProperty(String key, String value) {
if (dataFormatProperties == null) {
dataFormatProperties = new LinkedHashMap<>();
}
dataFormatProperties.put(key, value);
}
public void addApiProperty(String key, String value) {
if (apiProperties == null) {
apiProperties = new LinkedHashMap<>();
}
apiProperties.put(key, value);
}
public void addCorsHeader(String key, String value) {
if (corsHeaders == null) {
corsHeaders = new LinkedHashMap<>();
}
corsHeaders.put(key, value);
}
}
| RestConfigurationDetails |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/dos/StreamReadStringConstraintsTest.java | {
"start": 618,
"end": 3603
} | class ____
{
String string;
StringWrapper() { }
StringWrapper(String string) { this.string = string; }
void setString(String string) {
this.string = string;
}
}
/*
/**********************************************************************
/* Test methods
/**********************************************************************
*/
private final static int TOO_LONG_STRING_VALUE = StreamReadConstraints.DEFAULT_MAX_STRING_LEN + 100;
private final ObjectMapper MAPPER = newJsonMapper();
private ObjectMapper newJsonMapperWithUnlimitedStringSizeSupport() {
JsonFactory jsonFactory = JsonFactory.builder()
.streamReadConstraints(StreamReadConstraints.builder().maxStringLength(Integer.MAX_VALUE).build())
.build();
return JsonMapper.builder(jsonFactory).build();
}
@Test
public void testBigString() throws Exception
{
try {
MAPPER.readValue(generateJson("string", TOO_LONG_STRING_VALUE), StringWrapper.class);
fail("expected DatabindException");
} catch (StreamConstraintsException e) {
final String message = e.getMessage();
assertTrue(message.startsWith("String value length"), "unexpected exception message: " + message);
assertTrue(message.contains("exceeds the maximum allowed ("), "unexpected exception message: " + message);
}
}
@Test
public void testBiggerString() throws Exception
{
try {
MAPPER.readValue(generateJson("string", TOO_LONG_STRING_VALUE), StringWrapper.class);
fail("expected JsonMappingException");
} catch (StreamConstraintsException e) {
final String message = e.getMessage();
// this test fails when the TextBuffer is being resized, so we don't yet know just how big the string is
// so best not to assert that the String length value in the message is the full 6000000 value
assertTrue(message.startsWith("String value length"), "unexpected exception message: " + message);
assertTrue(message.contains("exceeds the maximum allowed ("), "unexpected exception message: " + message);
}
}
@Test
public void testUnlimitedString() throws Exception
{
final int len = TOO_LONG_STRING_VALUE;
StringWrapper sw = newJsonMapperWithUnlimitedStringSizeSupport()
.readValue(generateJson("string", len), StringWrapper.class);
assertEquals(len, sw.string.length());
}
private String generateJson(final String fieldName, final int len) {
final StringBuilder sb = new StringBuilder();
sb.append("{\"")
.append(fieldName)
.append("\": \"");
for (int i = 0; i < len; i++) {
sb.append('a');
}
sb.append("\"}");
return sb.toString();
}
}
| StringWrapper |
java | apache__logging-log4j2 | log4j-iostreams/src/main/java/org/apache/logging/log4j/io/internal/InternalPrintWriter.java | {
"start": 1170,
"end": 5424
} | class ____ extends PrintWriter {
public InternalPrintWriter(
final ExtendedLogger logger,
final boolean autoFlush,
final String fqcn,
final Level level,
final Marker marker) {
super(new InternalWriter(logger, fqcn, level, marker), autoFlush);
}
public InternalPrintWriter(
final Writer writer,
final boolean autoFlush,
final ExtendedLogger logger,
final String fqcn,
final Level level,
final Marker marker) {
super(new InternalFilterWriter(writer, logger, fqcn, level, marker), autoFlush);
}
@Override
public InternalPrintWriter append(final char c) {
super.append(c);
return this;
}
@Override
public InternalPrintWriter append(final CharSequence csq) {
super.append(csq);
return this;
}
@Override
public InternalPrintWriter append(final CharSequence csq, final int start, final int end) {
super.append(csq, start, end);
return this;
}
@Override
public boolean checkError() {
return super.checkError();
}
@Override
public void close() {
super.close();
}
@Override
public void flush() {
super.flush();
}
@Override
public InternalPrintWriter format(final Locale l, final String format, final Object... args) {
super.format(l, format, args);
return this;
}
@Override
public InternalPrintWriter format(final String format, final Object... args) {
super.format(format, args);
return this;
}
@Override
public void print(final boolean b) {
super.print(b);
}
@Override
public void print(final char c) {
super.print(c);
}
@Override
public void print(final char[] s) {
super.print(s);
}
@Override
public void print(final double d) {
super.print(d);
}
@Override
public void print(final float f) {
super.print(f);
}
@Override
public void print(final int i) {
super.print(i);
}
@Override
public void print(final long l) {
super.print(l);
}
@Override
public void print(final Object obj) {
super.print(obj);
}
@Override
public void print(final String s) {
super.print(s);
}
@Override
public InternalPrintWriter printf(final Locale l, final String format, final Object... args) {
super.printf(l, format, args);
return this;
}
@Override
public InternalPrintWriter printf(final String format, final Object... args) {
super.printf(format, args);
return this;
}
@Override
public void println() {
super.println();
}
@Override
public void println(final boolean x) {
super.println(x);
}
@Override
public void println(final char x) {
super.println(x);
}
@Override
public void println(final char[] x) {
super.println(x);
}
@Override
public void println(final double x) {
super.println(x);
}
@Override
public void println(final float x) {
super.println(x);
}
@Override
public void println(final int x) {
super.println(x);
}
@Override
public void println(final long x) {
super.println(x);
}
@Override
public void println(final Object x) {
super.println(x);
}
@Override
public void println(final String x) {
super.println(x);
}
@Override
public String toString() {
return "{stream=" + this.out + '}';
}
@Override
public void write(final char[] buf) {
super.write(buf);
}
@Override
public void write(final char[] buf, final int off, final int len) {
super.write(buf, off, len);
}
@Override
public void write(final int c) {
super.write(c);
}
@Override
public void write(final String s) {
super.write(s);
}
@Override
public void write(final String s, final int off, final int len) {
super.write(s, off, len);
}
}
| InternalPrintWriter |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/SmppEndpointBuilderFactory.java | {
"start": 102236,
"end": 105388
} | interface ____ {
/**
* SMPP (camel-smpp)
* Send and receive SMS messages using a SMSC (Short Message Service
* Center).
*
* Category: mobile
* Since: 2.2
* Maven coordinates: org.apache.camel:camel-smpp
*
* @return the dsl builder for the headers' name.
*/
default SmppHeaderNameBuilder smpp() {
return SmppHeaderNameBuilder.INSTANCE;
}
/**
* SMPP (camel-smpp)
* Send and receive SMS messages using a SMSC (Short Message Service
* Center).
*
* Category: mobile
* Since: 2.2
* Maven coordinates: org.apache.camel:camel-smpp
*
* Syntax: <code>smpp:host:port</code>
*
* Path parameter: host
* Hostname for the SMSC server to use.
* Default value: localhost
*
* Path parameter: port
* Port number for the SMSC server to use.
* Default value: 2775
*
* @param path host:port
* @return the dsl builder
*/
default SmppEndpointBuilder smpp(String path) {
return SmppEndpointBuilderFactory.endpointBuilder("smpp", path);
}
/**
* SMPP (camel-smpp)
* Send and receive SMS messages using a SMSC (Short Message Service
* Center).
*
* Category: mobile
* Since: 2.2
* Maven coordinates: org.apache.camel:camel-smpp
*
* Syntax: <code>smpp:host:port</code>
*
* Path parameter: host
* Hostname for the SMSC server to use.
* Default value: localhost
*
* Path parameter: port
* Port number for the SMSC server to use.
* Default value: 2775
*
* @param componentName to use a custom component name for the endpoint
* instead of the default name
* @param path host:port
* @return the dsl builder
*/
default SmppEndpointBuilder smpp(String componentName, String path) {
return SmppEndpointBuilderFactory.endpointBuilder(componentName, path);
}
/**
* SMPP (Secure) (camel-smpp)
* Send and receive SMS messages using a SMSC (Short Message Service
* Center).
*
* Category: mobile
* Since: 2.2
* Maven coordinates: org.apache.camel:camel-smpp
*
* Syntax: <code>smpps:host:port</code>
*
* Path parameter: host
* Hostname for the SMSC server to use.
* Default value: localhost
*
* Path parameter: port
* Port number for the SMSC server to use.
* Default value: 2775
*
* @param path host:port
* @return the dsl builder
*/
default SmppEndpointBuilder smpps(String path) {
return SmppEndpointBuilderFactory.endpointBuilder("smpps", path);
}
}
/**
* The builder of headers' name for the SMPP component.
*/
public static | SmppBuilders |
java | spring-projects__spring-boot | module/spring-boot-artemis/src/main/java/org/springframework/boot/artemis/autoconfigure/ArtemisXAConnectionFactoryConfiguration.java | {
"start": 1682,
"end": 2606
} | class ____ {
@Primary
@Bean(name = { "jmsConnectionFactory", "xaJmsConnectionFactory" })
ConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties,
ArtemisConnectionDetails connectionDetails, XAConnectionFactoryWrapper wrapper) throws Exception {
return wrapper
.wrapConnectionFactory(new ArtemisConnectionFactoryFactory(beanFactory, properties, connectionDetails)
.createConnectionFactory(ActiveMQXAConnectionFactory::new, ActiveMQXAConnectionFactory::new));
}
@Bean
ActiveMQXAConnectionFactory nonXaJmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties,
ArtemisConnectionDetails connectionDetails) {
return new ArtemisConnectionFactoryFactory(beanFactory, properties, connectionDetails)
.createConnectionFactory(ActiveMQXAConnectionFactory::new, ActiveMQXAConnectionFactory::new);
}
}
| ArtemisXAConnectionFactoryConfiguration |
java | apache__camel | components/camel-platform-http-vertx/src/generated/java/org/apache/camel/component/platform/http/vertx/VertxConverterLoader.java | {
"start": 895,
"end": 2247
} | class ____ implements TypeConverterLoader, CamelContextAware {
private CamelContext camelContext;
public VertxConverterLoader() {
}
@Override
public void setCamelContext(CamelContext camelContext) {
this.camelContext = camelContext;
}
@Override
public CamelContext getCamelContext() {
return camelContext;
}
@Override
public void load(TypeConverterRegistry registry) throws TypeConverterLoaderException {
registerConverters(registry);
}
private void registerConverters(TypeConverterRegistry registry) {
addTypeConverter(registry, java.lang.String.class, io.vertx.core.net.impl.SocketAddressImpl.class, false,
(type, exchange, value) -> {
Object answer = org.apache.camel.component.platform.http.vertx.VertxConverter.fromSocket((io.vertx.core.net.impl.SocketAddressImpl) value);
if (false && answer == null) {
answer = Void.class;
}
return answer;
});
}
private static void addTypeConverter(TypeConverterRegistry registry, Class<?> toType, Class<?> fromType, boolean allowNull, SimpleTypeConverter.ConversionMethod method) {
registry.addTypeConverter(toType, fromType, new SimpleTypeConverter(allowNull, method));
}
}
| VertxConverterLoader |
java | spring-projects__spring-security | rsocket/src/main/java/org/springframework/security/rsocket/authorization/AuthorizationPayloadInterceptor.java | {
"start": 1444,
"end": 2566
} | class ____ implements PayloadInterceptor, Ordered {
private final ReactiveAuthorizationManager<PayloadExchange> authorizationManager;
private int order;
public AuthorizationPayloadInterceptor(ReactiveAuthorizationManager<PayloadExchange> authorizationManager) {
Assert.notNull(authorizationManager, "authorizationManager cannot be null");
this.authorizationManager = authorizationManager;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
@Override
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
public Mono<Void> intercept(PayloadExchange exchange, PayloadInterceptorChain chain) {
return ReactiveSecurityContextHolder.getContext()
.mapNotNull(SecurityContext::getAuthentication)
.switchIfEmpty(Mono.error(() -> new AuthenticationCredentialsNotFoundException(
"An Authentication (possibly AnonymousAuthenticationToken) is required.")))
.as((authentication) -> this.authorizationManager.verify(authentication, exchange))
.then(chain.next(exchange));
}
}
| AuthorizationPayloadInterceptor |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/output/GeoWithinListOutputUnitTests.java | {
"start": 440,
"end": 2626
} | class ____ {
private GeoWithinListOutput<String, String> sut = new GeoWithinListOutput<>(StringCodec.UTF8, false, false, false);
@Test
void defaultSubscriberIsSet() {
sut.multi(1);
assertThat(sut.getSubscriber()).isNotNull().isInstanceOf(ListSubscriber.class);
}
@Test
void commandOutputKeyOnlyDecoded() {
sut.multi(1);
sut.set(ByteBuffer.wrap("key".getBytes()));
sut.set(ByteBuffer.wrap("4.567".getBytes()));
sut.complete(1);
assertThat(sut.get()).contains(new GeoWithin<>("key", null, null, null));
}
@Test
void commandOutputKeyAndDistanceDecoded() {
sut = new GeoWithinListOutput<>(StringCodec.UTF8, true, false, false);
sut.multi(1);
sut.set(ByteBuffer.wrap("key".getBytes()));
sut.set(ByteBuffer.wrap("4.567".getBytes()));
sut.complete(1);
assertThat(sut.get()).contains(new GeoWithin<>("key", 4.567, null, null));
}
@Test
void commandOutputKeyAndHashDecoded() {
sut = new GeoWithinListOutput<>(StringCodec.UTF8, false, true, false);
sut.multi(1);
sut.set(ByteBuffer.wrap("key".getBytes()));
sut.set(4567);
sut.complete(1);
assertThat(sut.get()).contains(new GeoWithin<>("key", null, 4567L, null));
}
@Test
void commandOutputLongKeyAndHashDecoded() {
GeoWithinListOutput<Long, Long> sut = new GeoWithinListOutput<>((RedisCodec) StringCodec.UTF8, false, true, false);
sut.multi(1);
sut.set(1234);
sut.set(4567);
sut.complete(1);
assertThat(sut.get()).contains(new GeoWithin<>(1234L, null, 4567L, null));
}
@Test
void commandOutputKeyAndCoordinatesDecoded() {
sut = new GeoWithinListOutput<>(StringCodec.UTF8, false, false, true);
sut.multi(1);
sut.set(ByteBuffer.wrap("key".getBytes()));
sut.set(ByteBuffer.wrap("1.234".getBytes()));
sut.set(ByteBuffer.wrap("4.567".getBytes()));
sut.complete(1);
assertThat(sut.get()).contains(new GeoWithin<>("key", null, null, new GeoCoordinates(1.234, 4.567)));
}
}
| GeoWithinListOutputUnitTests |
java | quarkusio__quarkus | integration-tests/jpa-postgresql-withxml/src/main/java/io/quarkus/it/jpa/postgresql/defaultpu/EntityWithXml.java | {
"start": 1065,
"end": 1594
} | class ____ {
@XmlElement
@XmlJavaTypeAdapter(value = LocalDateXmlAdapter.class)
LocalDate date;
public ToBeSerializedWithDateTime() {
}
public ToBeSerializedWithDateTime(LocalDate date) {
this.date = date;
}
@Override
public String toString() {
return "ToBeSerializedWithDateTime{" +
"date=" + date +
'}';
}
}
@RegisterForReflection
public static | ToBeSerializedWithDateTime |
java | spring-projects__spring-framework | spring-test/src/main/java/org/springframework/test/context/TestPropertySource.java | {
"start": 13189,
"end": 13821
} | class ____ {
* // ...
* }</pre>
* <h4>Precedence</h4>
* <p>Properties declared via this attribute have higher precedence than
* properties loaded from resource {@link #locations}.
* <p>This attribute may be used in conjunction with {@link #value}
* <em>or</em> {@link #locations}.
* @see #inheritProperties
* @see #locations
* @see org.springframework.core.env.PropertySource
*/
String[] properties() default {};
/**
* Whether inlined test {@link #properties} from superclasses and
* enclosing classes should be <em>inherited</em>.
* <p>The default value is {@code true}, which means that a test | MyTests |
java | spring-projects__spring-framework | spring-r2dbc/src/main/java/org/springframework/r2dbc/core/DataClassRowMapper.java | {
"start": 2569,
"end": 2873
} | class ____ designed to provide convenience rather than
* high performance. For best performance, consider using a custom readable mapping
* {@code Function} implementation.
*
* @author Simon Baslé
* @author Juergen Hoeller
* @author Sam Brannen
* @since 6.1
* @param <T> the result type
*/
public | is |
java | quarkusio__quarkus | extensions/cache/runtime/src/main/java/io/quarkus/cache/runtime/UnresolvedUniValue.java | {
"start": 342,
"end": 494
} | class ____ {
public static final UnresolvedUniValue INSTANCE = new UnresolvedUniValue();
private UnresolvedUniValue() {
}
}
| UnresolvedUniValue |
java | google__auto | service/processor/src/main/java/com/google/auto/service/processor/ServicesFiles.java | {
"start": 1623,
"end": 2295
} | class ____.
* @throws IOException
*/
static Set<String> readServiceFile(InputStream input) throws IOException {
HashSet<String> serviceClasses = new HashSet<String>();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(input, UTF_8))) {
String line;
while ((line = reader.readLine()) != null) {
int commentStart = line.indexOf('#');
if (commentStart >= 0) {
line = line.substring(0, commentStart);
}
line = line.trim();
if (!line.isEmpty()) {
serviceClasses.add(line);
}
}
return serviceClasses;
}
}
/**
* Writes the set of service | names |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/RootNameTest.java | {
"start": 606,
"end": 685
} | class ____ {
public int a = 3;
}
@JsonRootName("")
static | Bean |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/RemoveUnusedImportsTest.java | {
"start": 6373,
"end": 6775
} | class ____ {
List<String> xs = new ArrayList<>();
}
""")
.doTest();
}
@Test
public void useInJavadocParameter() {
testHelper
.addInputLines(
"in/Test.java",
"""
import java.util.List;
import java.util.Collection;
/** {@link List#containsAll(Collection)} */
public | Test |
java | google__auto | value/src/test/java/com/google/auto/value/processor/TypeEncoderTest.java | {
"start": 15848,
"end": 16655
} | class ____ nested types they will be in scope, and therefore a possible
* source of ambiguity.
*/
private TypeMirror baseWithoutContainedTypes() {
return typeMirrorOf(Object.class);
}
// This test checks that we correctly throw MissingTypeException if there is an ErrorType anywhere
// inside a type we are asked to simplify. There's no way to get an ErrorType from typeUtils or
// elementUtils, so we need to fire up the compiler with an erroneous source file and use an
// annotation processor to capture the resulting ErrorType. Then we can run tests within that
// annotation processor, and propagate any failures out of this test.
@Test
public void testErrorTypes() {
JavaFileObject source =
JavaFileObjects.forSourceString(
"ExtendsUndefinedType", " | has |
java | spring-projects__spring-framework | spring-context/src/main/java/org/springframework/cache/interceptor/BasicOperation.java | {
"start": 713,
"end": 820
} | interface ____ all cache operations must implement.
*
* @author Stephane Nicoll
* @since 4.1
*/
public | that |
java | apache__flink | flink-core-api/src/main/java/org/apache/flink/api/java/tuple/builder/Tuple1Builder.java | {
"start": 1350,
"end": 1678
} | class ____<T0> {
private List<Tuple1<T0>> tuples = new ArrayList<>();
public Tuple1Builder<T0> add(T0 f0) {
tuples.add(new Tuple1<>(f0));
return this;
}
@SuppressWarnings("unchecked")
public Tuple1<T0>[] build() {
return tuples.toArray(new Tuple1[tuples.size()]);
}
}
| Tuple1Builder |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/jaxb/internal/stax/XMLStreamConstantsUtils.java | {
"start": 438,
"end": 1381
} | class ____ {
private XMLStreamConstantsUtils() {
}
/**
* Get the human readable event name for the numeric event id
*/
public static String getEventName(int eventId) {
return switch ( eventId ) {
case XMLStreamConstants.START_ELEMENT -> "StartElementEvent";
case XMLStreamConstants.END_ELEMENT -> "EndElementEvent";
case XMLStreamConstants.PROCESSING_INSTRUCTION -> "ProcessingInstructionEvent";
case XMLStreamConstants.CHARACTERS -> "CharacterEvent";
case XMLStreamConstants.COMMENT -> "CommentEvent";
case XMLStreamConstants.START_DOCUMENT -> "StartDocumentEvent";
case XMLStreamConstants.END_DOCUMENT -> "EndDocumentEvent";
case XMLStreamConstants.ENTITY_REFERENCE -> "EntityReferenceEvent";
case XMLStreamConstants.ATTRIBUTE -> "AttributeBase";
case XMLStreamConstants.DTD -> "DTDEvent";
case XMLStreamConstants.CDATA -> "CDATA";
default -> "UNKNOWN_EVENT_TYPE";
};
}
}
| XMLStreamConstantsUtils |
java | google__error-prone | core/src/main/java/com/google/errorprone/bugpatterns/RedundantSetterCall.java | {
"start": 12931,
"end": 14745
} | interface ____ {
@Override
boolean equals(@Nullable Object other);
@Override
int hashCode();
boolean identicalValuesShouldBeRemoved();
String toString(Iterable<FieldWithValue> locations);
}
record SingleField(String name) implements Field {
@Override
public final String toString(Iterable<FieldWithValue> locations) {
return String.format("%s(..)", this.name());
}
@Override
public boolean identicalValuesShouldBeRemoved() {
return true;
}
}
record RepeatedField(String name, int index) implements Field {
@Override
public final String toString(Iterable<FieldWithValue> locations) {
return String.format("%s(%s, ..)", this.name(), this.index());
}
@Override
public boolean identicalValuesShouldBeRemoved() {
return true;
}
}
record MapField(String name, Object key) implements Field {
@Override
public final String toString(Iterable<FieldWithValue> locations) {
return String.format("%s(%s, ..)", this.name(), this.key());
}
@Override
public boolean identicalValuesShouldBeRemoved() {
return true;
}
}
record OneOfField(String oneOfName) implements Field {
@Override
public final String toString(Iterable<FieldWithValue> locations) {
return String.format(
"The oneof `%s` (set via %s)",
oneOfName(),
stream(locations)
.map(l -> getSymbol(l.methodInvocation()).getSimpleName().toString())
.distinct()
.sorted()
.collect(joining(", ")));
}
@Override
public boolean identicalValuesShouldBeRemoved() {
return false;
}
}
record FieldWithValue(
Field field, MethodInvocationTree methodInvocation, ExpressionTree argument) {}
}
| Field |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/operators/join/HashJoinOperator.java | {
"start": 21187,
"end": 21873
} | class ____ extends HashJoinOperator {
AntiHashJoinOperator(HashJoinParameter parameter) {
super(parameter);
}
@Override
public void join(RowIterator<BinaryRowData> buildIter, RowData probeRow) throws Exception {
checkNotNull(probeRow);
if (!buildIter.advanceNext()) {
collector.collect(probeRow);
}
}
}
/**
* BuildLeftSemiOrAnti join. BuildLeftSemiJoin: Output build side row when build side row
* matched probe side row. BuildLeftAntiJoin: Output build side row when build side row not
* matched probe side row.
*/
private static | AntiHashJoinOperator |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/factory/FactoryBeanLookupTests.java | {
"start": 2378,
"end": 2575
} | class ____ extends AbstractFactoryBean<Foo> {
@Override
protected Foo createInstance() {
return new Foo();
}
@Override
public Class<?> getObjectType() {
return Foo.class;
}
}
| FooFactoryBean |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/aot/AotContextLoaderRuntimeHintsTests.java | {
"start": 2222,
"end": 2352
} | class ____ {
public static void main(String[] args) {
// Mimics main() method for Spring Boot app
}
}
static | ConfigWithMain |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/MultipartDataInputTest.java | {
"start": 1019,
"end": 4041
} | class ____ {
@RegisterExtension
static QuarkusUnitTest test = new QuarkusUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(Resource.class, Item.class, Result.class);
}
});
private final File HTML_FILE = new File("./src/test/resources/test.html");
private final File XML_FILE = new File("./src/test/resources/test.xml");
@Test
public void empty() {
Result result = given()
.contentType("multipart/form-data")
.accept("application/json")
.when()
.post("/test/0")
.then()
.statusCode(200)
.extract().body().as(Result.class);
assertThat(result).satisfies(r -> {
assertThat(r.count).isEqualTo(0);
assertThat(r.items).isEmpty();
});
}
@Test
public void multipleParts() {
String status = "WORKING";
Result result = given()
.multiPart("status", status)
.multiPart("htmlFile", HTML_FILE, "text/html")
.multiPart("xmlFile", XML_FILE, "text/xml")
.accept("application/json")
.when()
.post("/test/3")
.then()
.statusCode(200)
.extract().body().as(Result.class);
assertThat(result).satisfies(r -> {
assertThat(r.count).isEqualTo(3);
assertThat(r.items).hasSize(3).satisfies(l -> {
assertThat(l).filteredOn(i -> i.name.equals("status")).singleElement().satisfies(i -> {
assertThat(i.size).isEqualTo(status.length());
assertThat(i.fileName).isNullOrEmpty();
assertThat(i.isFileItem).isFalse();
assertThat(i.headers).contains(entry("Content-Type", List.of("text/plain")));
});
assertThat(l).filteredOn(i -> i.name.equals("htmlFile")).singleElement().satisfies(i -> {
assertThat(i.size).isEqualTo(Files.size(HTML_FILE.toPath()));
assertThat(i.fileName).isEqualTo("test.html");
assertThat(i.isFileItem).isTrue();
assertThat(i.headers).contains(entry("Content-Type", List.of("text/html")));
});
assertThat(l).filteredOn(i -> i.name.equals("xmlFile")).singleElement().satisfies(i -> {
assertThat(i.size).isEqualTo(Files.size(XML_FILE.toPath()));
assertThat(i.fileName).isEqualTo("test.xml");
assertThat(i.isFileItem).isTrue();
assertThat(i.headers).contains(entry("Content-Type", List.of("text/xml")));
});
});
});
}
@Path("/test")
public static | MultipartDataInputTest |
java | google__dagger | javatests/dagger/functional/tck/TckTest.java | {
"start": 838,
"end": 1086
} | class ____ {
public static Test suite() {
CarShop carShopComponent = DaggerCarShop.create();
Car car = carShopComponent.make();
Convertible.localConvertible.set((Convertible) car);
return Tck.testsFor(car, false, false);
}
}
| TckTest |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoaderTest.java | {
"start": 16556,
"end": 17004
} | interface ____.apache.dubbo.common.extension.ext8_add.AddExt1)!"));
}
}
@Test
void test_addExtension_with_error_class() {
try {
getExtensionLoader(SimpleExt.class).addExtension("impl1", ExtensionLoaderTest.class);
} catch (IllegalStateException expected) {
assertThat(
expected.getMessage(),
containsString(
"Input type | org |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/processors/AsyncProcessorTest.java | {
"start": 1275,
"end": 8214
} | class ____ extends FlowableProcessorTest<Object> {
private final Throwable testException = new Throwable();
@Override
protected FlowableProcessor<Object> create() {
return AsyncProcessor.create();
}
@Test
public void neverCompleted() {
AsyncProcessor<String> processor = AsyncProcessor.create();
Subscriber<String> subscriber = TestHelper.mockSubscriber();
processor.subscribe(subscriber);
processor.onNext("one");
processor.onNext("two");
processor.onNext("three");
verify(subscriber, Mockito.never()).onNext(anyString());
verify(subscriber, Mockito.never()).onError(testException);
verify(subscriber, Mockito.never()).onComplete();
}
@Test
public void completed() {
AsyncProcessor<String> processor = AsyncProcessor.create();
Subscriber<String> subscriber = TestHelper.mockSubscriber();
processor.subscribe(subscriber);
processor.onNext("one");
processor.onNext("two");
processor.onNext("three");
processor.onComplete();
verify(subscriber, times(1)).onNext("three");
verify(subscriber, Mockito.never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void subscribeAfterCompleted() {
AsyncProcessor<String> processor = AsyncProcessor.create();
Subscriber<String> subscriber = TestHelper.mockSubscriber();
processor.onNext("one");
processor.onNext("two");
processor.onNext("three");
processor.onComplete();
processor.subscribe(subscriber);
verify(subscriber, times(1)).onNext("three");
verify(subscriber, Mockito.never()).onError(any(Throwable.class));
verify(subscriber, times(1)).onComplete();
}
@Test
public void subscribeAfterError() {
AsyncProcessor<String> processor = AsyncProcessor.create();
Subscriber<String> subscriber = TestHelper.mockSubscriber();
processor.onNext("one");
processor.onNext("two");
processor.onNext("three");
RuntimeException re = new RuntimeException("failed");
processor.onError(re);
processor.subscribe(subscriber);
verify(subscriber, times(1)).onError(re);
verify(subscriber, Mockito.never()).onNext(any(String.class));
verify(subscriber, Mockito.never()).onComplete();
}
@Test
@SuppressUndeliverable
public void error() {
AsyncProcessor<String> processor = AsyncProcessor.create();
Subscriber<String> subscriber = TestHelper.mockSubscriber();
processor.subscribe(subscriber);
processor.onNext("one");
processor.onNext("two");
processor.onNext("three");
processor.onError(testException);
processor.onNext("four");
processor.onError(new Throwable());
processor.onComplete();
verify(subscriber, Mockito.never()).onNext(anyString());
verify(subscriber, times(1)).onError(testException);
verify(subscriber, Mockito.never()).onComplete();
}
@Test
public void unsubscribeBeforeCompleted() {
AsyncProcessor<String> processor = AsyncProcessor.create();
Subscriber<String> subscriber = TestHelper.mockSubscriber();
TestSubscriber<String> ts = new TestSubscriber<>(subscriber);
processor.subscribe(ts);
processor.onNext("one");
processor.onNext("two");
ts.cancel();
verify(subscriber, Mockito.never()).onNext(anyString());
verify(subscriber, Mockito.never()).onError(any(Throwable.class));
verify(subscriber, Mockito.never()).onComplete();
processor.onNext("three");
processor.onComplete();
verify(subscriber, Mockito.never()).onNext(anyString());
verify(subscriber, Mockito.never()).onError(any(Throwable.class));
verify(subscriber, Mockito.never()).onComplete();
}
@Test
public void emptySubjectCompleted() {
AsyncProcessor<String> processor = AsyncProcessor.create();
Subscriber<String> subscriber = TestHelper.mockSubscriber();
processor.subscribe(subscriber);
processor.onComplete();
InOrder inOrder = inOrder(subscriber);
inOrder.verify(subscriber, never()).onNext(null);
inOrder.verify(subscriber, never()).onNext(any(String.class));
inOrder.verify(subscriber, times(1)).onComplete();
inOrder.verifyNoMoreInteractions();
}
/**
* Can receive timeout if subscribe never receives an onError/onComplete ... which reveals a race condition.
*/
@Test
public void subscribeCompletionRaceCondition() {
/*
* With non-threadsafe code this fails most of the time on my dev laptop and is non-deterministic enough
* to act as a unit test to the race conditions.
*
* With the synchronization code in place I can not get this to fail on my laptop.
*/
for (int i = 0; i < 50; i++) {
final AsyncProcessor<String> processor = AsyncProcessor.create();
final AtomicReference<String> value1 = new AtomicReference<>();
processor.subscribe(new Consumer<String>() {
@Override
public void accept(String t1) {
try {
// simulate a slow observer
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
value1.set(t1);
}
});
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
processor.onNext("value");
processor.onComplete();
}
});
SubjectSubscriberThread t2 = new SubjectSubscriberThread(processor);
SubjectSubscriberThread t3 = new SubjectSubscriberThread(processor);
SubjectSubscriberThread t4 = new SubjectSubscriberThread(processor);
SubjectSubscriberThread t5 = new SubjectSubscriberThread(processor);
t2.start();
t3.start();
t1.start();
t4.start();
t5.start();
try {
t1.join();
t2.join();
t3.join();
t4.join();
t5.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
assertEquals("value", value1.get());
assertEquals("value", t2.value.get());
assertEquals("value", t3.value.get());
assertEquals("value", t4.value.get());
assertEquals("value", t5.value.get());
}
}
private static | AsyncProcessorTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/properties/PropertiesComponentLookupListenerTest.java | {
"start": 2718,
"end": 3320
} | class ____ implements PropertiesLookupListener {
private final Map<String, String[]> map = new HashMap<>();
@Override
public void onLookup(String name, String value, String defaultValue, String source) {
map.put(name, new String[] { value, source });
}
public boolean hasName(String name) {
return map.containsKey(name);
}
public String getValue(String name) {
return map.get(name)[0];
}
public String getSource(String name) {
return map.get(name)[1];
}
}
}
| MyListener |
java | elastic__elasticsearch | x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/transport/ssl/SslIntegrationTests.java | {
"start": 2018,
"end": 5761
} | class ____ extends SecurityIntegTestCase {
@Override
protected boolean addMockHttpTransport() {
return false; // enable http
}
@Override
protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) {
final Settings.Builder builder = Settings.builder().put(super.nodeSettings(nodeOrdinal, otherSettings));
addSSLSettingsForNodePEMFiles(builder, "xpack.security.http.", randomBoolean());
return builder.put("xpack.security.http.ssl.enabled", true).build();
}
@Override
protected boolean transportSSLEnabled() {
return true;
}
public void testThatConnectionToHTTPWorks() throws Exception {
Settings.Builder builder = Settings.builder().put("xpack.security.http.ssl.enabled", true);
addSSLSettingsForPEMFiles(
builder,
"/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.pem",
"testclient",
"/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testclient.crt",
"xpack.security.http.",
Arrays.asList("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.crt")
);
SSLService service = new SSLService(TestEnvironment.newEnvironment(buildEnvSettings(builder.build())));
CredentialsProvider provider = new BasicCredentialsProvider();
provider.setCredentials(
AuthScope.ANY,
new UsernamePasswordCredentials(nodeClientUsername(), new String(nodeClientPassword().getChars()))
);
SslProfile sslProfile = service.profile("xpack.security.http.ssl");
try (
CloseableHttpClient client = HttpClients.custom()
.setSSLSocketFactory(
new SSLConnectionSocketFactory(sslProfile.socketFactory(), SSLConnectionSocketFactory.getDefaultHostnameVerifier())
)
.setDefaultCredentialsProvider(provider)
.build();
CloseableHttpResponse response = SocketAccess.doPrivileged(() -> client.execute(new HttpGet(getNodeUrl())))
) {
assertThat(response.getStatusLine().getStatusCode(), is(200));
String data = Streams.copyToString(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
assertThat(data, containsString("You Know, for Search"));
}
}
public void testThatHttpUsingSSLv3IsRejected() throws Exception {
assumeFalse("Can't run in a FIPS JVM as we can't even get an instance of SSL SSL Context", inFipsJvm());
SSLContext sslContext = SSLContext.getInstance("SSL");
TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
factory.init((KeyStore) null);
sslContext.init(null, factory.getTrustManagers(), new SecureRandom());
SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(
sslContext,
new String[] { "SSLv3" },
null,
NoopHostnameVerifier.INSTANCE
);
try (CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sf).build()) {
expectThrows(SSLHandshakeException.class, () -> SocketAccess.doPrivileged(() -> client.execute(new HttpGet(getNodeUrl()))));
}
}
private String getNodeUrl() {
TransportAddress transportAddress = randomFrom(
internalCluster().getInstance(HttpServerTransport.class).boundAddress().boundAddresses()
);
final InetSocketAddress inetSocketAddress = transportAddress.address();
return Strings.format("https://%s/", NetworkAddress.format(inetSocketAddress));
}
}
| SslIntegrationTests |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/EmbeddedForeignKeyDescriptorSide.java | {
"start": 314,
"end": 847
} | class ____ implements ForeignKeyDescriptor.Side {
private final ForeignKeyDescriptor.Nature nature;
private final EmbeddableValuedModelPart modelPart;
public EmbeddedForeignKeyDescriptorSide(
ForeignKeyDescriptor.Nature nature,
EmbeddableValuedModelPart modelPart) {
this.nature = nature;
this.modelPart = modelPart;
}
@Override
public ForeignKeyDescriptor.Nature getNature() {
return nature;
}
@Override
public EmbeddableValuedModelPart getModelPart() {
return modelPart;
}
}
| EmbeddedForeignKeyDescriptorSide |
java | apache__dubbo | dubbo-metrics/dubbo-metrics-registry/src/test/java/org/apache/dubbo/metrics/registry/metrics/collector/RegistryMetricsCollectorTest.java | {
"start": 11023,
"end": 14691
} | interface
____.assertEquals(
1,
metricSamples.stream()
.filter(metricSample ->
serviceName.equals(metricSample.getTags().get("interface")))
.count());
return null;
});
// push finish rt +1
List<MetricSample> metricSamples = collector.collect();
// App(7) + rt(5) + service(total/success) = 14
Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 5 + 2, metricSamples.size());
long c1 = subscribeEvent.getTimePair().calc();
subscribeEvent = RegistryEvent.toSsEvent(applicationModel, serviceName, Collections.singletonList("demo1"));
TimePair lastTimePair = subscribeEvent.getTimePair();
MetricsEventBus.post(
subscribeEvent,
() -> {
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
},
Objects::nonNull);
// push error rt +1
long c2 = lastTimePair.calc();
metricSamples = collector.collect();
// App(7) + rt(5) + service(total/success/failed) = 15
Assertions.assertEquals(RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 5 + 3, metricSamples.size());
// calc rt
for (MetricSample sample : metricSamples) {
Map<String, String> tags = sample.getTags();
Assertions.assertEquals(tags.get(TAG_APPLICATION_NAME), applicationModel.getApplicationName());
}
@SuppressWarnings("rawtypes")
Map<String, Long> sampleMap = metricSamples.stream()
.collect(Collectors.toMap(MetricSample::getName, k -> ((GaugeMetricSample) k).applyAsLong()));
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_LAST, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()),
lastTimePair.calc());
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MIN, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()),
Math.min(c1, c2));
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_MAX, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()),
Math.max(c1, c2));
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_AVG, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()),
(c1 + c2) / 2);
Assertions.assertEquals(
sampleMap.get(new MetricsKeyWrapper(MetricsKey.METRIC_RT_SUM, OP_TYPE_SUBSCRIBE_SERVICE).targetKey()),
c1 + c2);
}
@Test
public void testNotify() {
Map<String, Integer> lastNumMap = new HashMap<>();
MetricsEventBus.post(RegistryEvent.toNotifyEvent(applicationModel), () -> {
try {
Thread.sleep(50L);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 1 different services
lastNumMap.put("demo.service1", 3);
lastNumMap.put("demo.service2", 4);
lastNumMap.put("demo.service3", 5);
return lastNumMap;
});
List<MetricSample> metricSamples = collector.collect();
// App(7) + num(service*3) + rt(5) = 9
Assertions.assertEquals((RegistryMetricsConstants.APP_LEVEL_KEYS.size() + 3 + 5), metricSamples.size());
}
}
| Assertions |
java | apache__hadoop | hadoop-cloud-storage-project/hadoop-tos/src/main/java/org/apache/hadoop/fs/tosfs/common/Tasks.java | {
"start": 15652,
"end": 17727
} | class ____ implements Iterable<Integer> {
private final int size;
Range(int size) {
this.size = size;
}
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private int current = 0;
@Override
public boolean hasNext() {
return current < size;
}
@Override
public Integer next() {
if (!hasNext()) {
throw new NoSuchElementException("No more items.");
}
int ret = current;
current += 1;
return ret;
}
};
}
}
public static Builder<Integer> range(int upTo) {
return new Builder<>(new Range(upTo));
}
public static <I> Builder<I> foreach(Iterator<I> items) {
return new Builder<>(() -> items);
}
public static <I> Builder<I> foreach(Iterable<I> items) {
return new Builder<>(items);
}
@SafeVarargs public static <I> Builder<I> foreach(I... items) {
return new Builder<>(Arrays.asList(items));
}
public static <I> Builder<I> foreach(Stream<I> items) {
return new Builder<>(items::iterator);
}
private static <E extends Exception> void throwOne(Collection<Throwable> exceptions,
Class<E> allowedException) throws E {
Iterator<Throwable> iter = exceptions.iterator();
Throwable exception = iter.next();
Class<? extends Throwable> exceptionClass = exception.getClass();
while (iter.hasNext()) {
Throwable other = iter.next();
if (!exceptionClass.isInstance(other)) {
exception.addSuppressed(other);
}
}
castAndThrow(exception, allowedException);
}
public static <E extends Exception> void castAndThrow(
Throwable exception, Class<E> exceptionClass) throws E {
if (exception instanceof RuntimeException) {
throw (RuntimeException) exception;
} else if (exception instanceof Error) {
throw (Error) exception;
} else if (exceptionClass.isInstance(exception)) {
throw (E) exception;
}
throw new RuntimeException(exception);
}
}
| Range |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/invoker/lookup/ArgumentLookupInvalidInjectionPointTest.java | {
"start": 854,
"end": 1799
} | class ____ {
@RegisterExtension
public ArcTestContainer container = ArcTestContainer.builder()
.beanClasses(MyService.class, MyDependency.class)
.beanRegistrars(new InvokerHelperRegistrar(MyService.class, (bean, factory, invokers) -> {
MethodInfo method = bean.getImplClazz().firstMethod("hello");
invokers.put(method.name(), factory.createInvoker(bean, method)
.withArgumentLookup(0)
.build());
}))
.shouldFail()
.build();
@Test
public void trigger() throws Exception {
Throwable error = container.getFailure();
assertNotNull(error);
assertInstanceOf(DefinitionException.class, error);
assertTrue(error.getMessage().contains("@Named without value may not be used on method parameter"));
}
@Singleton
static | ArgumentLookupInvalidInjectionPointTest |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ImportAwareTests.java | {
"start": 11870,
"end": 11942
} | interface ____ {
FeaturePolicy[] policies() default {};
@ | EnableFeature |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/io/network/partition/hybrid/tiered/shuffle/TierFactoryInitializerTest.java | {
"start": 4947,
"end": 5121
} | class ____ extends TestingTierFactory {
@Override
public void setup(Configuration configuration) {
// noop
}
}
}
| ExternalRemoteTierFactory |
java | netty__netty | codec-http3/src/main/java/io/netty/handler/codec/http3/DefaultHttp3DataFrame.java | {
"start": 808,
"end": 2059
} | class ____ extends DefaultByteBufHolder implements Http3DataFrame {
public DefaultHttp3DataFrame(ByteBuf data) {
super(data);
}
@Override
public Http3DataFrame copy() {
return new DefaultHttp3DataFrame(content().copy());
}
@Override
public Http3DataFrame duplicate() {
return new DefaultHttp3DataFrame(content().duplicate());
}
@Override
public Http3DataFrame retainedDuplicate() {
return new DefaultHttp3DataFrame(content().retainedDuplicate());
}
@Override
public Http3DataFrame replace(ByteBuf content) {
return new DefaultHttp3DataFrame(content);
}
@Override
public Http3DataFrame retain() {
super.retain();
return this;
}
@Override
public Http3DataFrame retain(int increment) {
super.retain(increment);
return this;
}
@Override
public Http3DataFrame touch() {
super.touch();
return this;
}
@Override
public Http3DataFrame touch(Object hint) {
super.touch(hint);
return this;
}
@Override
public String toString() {
return StringUtil.simpleClassName(this) + "(content=" + content() + ')';
}
}
| DefaultHttp3DataFrame |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/publisher/FluxOnErrorResumeTest.java | {
"start": 8843,
"end": 11314
} | class ____ extends Exception {}
@Test
public void mapError() {
StepVerifier.create(Flux.<Integer>error(new TestException())
.onErrorMap(TestException.class, e -> new Exception("test")))
.verifyErrorMessage("test");
}
@Test
public void onErrorResumeErrorPredicate() {
StepVerifier.create(Flux.<Integer>error(new TestException())
.onErrorResume(TestException.class, e -> Mono.just(1)))
.expectNext(1)
.verifyComplete();
}
@Test
public void onErrorResumeErrorPredicateNot() {
StepVerifier.create(Flux.<Integer>error(new TestException())
.onErrorResume(RuntimeException.class, e -> Mono.just(1)))
.verifyError(TestException.class);
}
@Test
public void onErrorReturnErrorPredicate() {
StepVerifier.create(Flux.<Integer>error(new TestException())
.onErrorReturn(TestException.class, 1))
.expectNext(1)
.verifyComplete();
}
@Test
public void onErrorReturnErrorPredicateNot() {
StepVerifier.create(Flux.<Integer>error(new TestException())
.onErrorReturn(RuntimeException.class, 1))
.verifyError(TestException.class);
}
@Test
public void onErrorReturnErrorPredicate2() {
StepVerifier.create(Flux.<Integer>error(new TestException())
.onErrorReturn(TestException.class::isInstance, 1))
.expectNext(1)
.verifyComplete();
}
@Test
public void onErrorReturnErrorPredicateNot2() {
StepVerifier.create(Flux.<Integer>error(new TestException())
.onErrorReturn(RuntimeException.class::isInstance, 1))
.verifyError(TestException.class);
}
@Test
public void scanOperator(){
Flux<Integer> parent = just(1);
FluxOnErrorResume<Integer> test = new FluxOnErrorResume<>(parent, (e) -> just(10));
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
}
@Test
public void scanSubscriber(){
@SuppressWarnings("unchecked")
Fuseable.ConditionalSubscriber<Integer> actual = Mockito.mock(MockUtils.TestScannableConditionalSubscriber.class);
FluxOnErrorResume.ResumeSubscriber<Integer> test = new FluxOnErrorResume.ResumeSubscriber<>(actual, (e) -> just(10));
Subscription parent = Operators.emptySubscription();
test.onSubscribe(parent);
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
}
}
| TestException |
java | apache__logging-log4j2 | log4j-core-test/src/main/java/org/apache/logging/log4j/core/test/smtp/SmtpMessage.java | {
"start": 1187,
"end": 4924
} | class ____ {
/**
* Headers: Map of List of String hashed on header name.
*/
private final Map<String, List<String>> headers;
/**
* Message body.
*/
private final StringBuffer body;
/**
* Constructor. Initializes headers Map and body buffer.
*/
public SmtpMessage() {
headers = new HashMap<>(10);
body = new StringBuffer();
}
/**
* Update the headers or body depending on the SmtpResponse object and line of input.
*
* @param response SmtpResponse object
* @param params remainder of input line after SMTP command has been removed
*/
public void store(final SmtpResponse response, final String params) {
if (params != null) {
if (SmtpState.DATA_HDR.equals(response.getNextState())) {
final int headerNameEnd = params.indexOf(':');
if (headerNameEnd >= 0) {
final String name = params.substring(0, headerNameEnd).trim();
final String value = params.substring(headerNameEnd + 1).trim();
addHeader(name, value);
}
} else if (SmtpState.DATA_BODY == response.getNextState()) {
body.append(params);
}
}
}
/**
* Get an Iterator over the header names.
*
* @return an Iterator over the set of header names (String)
*/
public Iterator<String> getHeaderNames() {
final Set<String> nameSet = headers.keySet();
return nameSet.iterator();
}
/**
* Get the value(s) associated with the given header name.
*
* @param name header name
* @return value(s) associated with the header name
*/
public String[] getHeaderValues(final String name) {
final List<String> values = headers.get(name);
if (values == null) {
return Strings.EMPTY_ARRAY;
}
return values.toArray(Strings.EMPTY_ARRAY);
}
/**
* Get the first values associated with a given header name.
*
* @param name header name
* @return first value associated with the header name
*/
public String getHeaderValue(final String name) {
final List<String> values = headers.get(name);
if (values == null) {
return null;
}
final Iterator<String> iterator = values.iterator();
return iterator.hasNext() ? iterator.next() : null;
}
/**
* Get the message body.
*
* @return message body
*/
public String getBody() {
return body.toString();
}
/**
* Adds a header to the Map.
*
* @param name header name
* @param value header value
*/
private void addHeader(final String name, final String value) {
List<String> valueList = headers.get(name);
if (valueList == null) {
valueList = new ArrayList<>(1);
headers.put(name, valueList);
}
valueList.add(value);
}
/**
* String representation of the SmtpMessage.
*
* @return a String
*/
@Override
public String toString() {
final StringBuilder msg = new StringBuilder();
for (final Map.Entry<String, List<String>> entry : headers.entrySet()) {
final String name = entry.getKey();
final List<String> values = entry.getValue();
for (final String value : values) {
msg.append(name);
msg.append(": ");
msg.append(value);
msg.append(LF);
}
}
msg.append(LF);
msg.append(body);
msg.append(LF);
return msg.toString();
}
}
| SmtpMessage |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestExternalBlockReader.java | {
"start": 1809,
"end": 3347
} | class ____ {
private static final Logger LOG =
LoggerFactory.getLogger(TestExternalBlockReader.class);
private static long SEED = 1234;
@Test
public void testMisconfiguredExternalBlockReader() throws Exception {
Configuration conf = new Configuration();
conf.set(HdfsClientConfigKeys.REPLICA_ACCESSOR_BUILDER_CLASSES_KEY,
"org.apache.hadoop.hdfs.NonExistentReplicaAccessorBuilderClass");
conf.setLong(HdfsClientConfigKeys.DFS_BLOCK_SIZE_KEY, 1024);
conf.setLong(DFSConfigKeys.DFS_NAMENODE_MIN_BLOCK_SIZE_KEY, 0);
MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf)
.numDataNodes(1)
.build();
final int TEST_LENGTH = 2048;
DistributedFileSystem dfs = cluster.getFileSystem();
try {
DFSTestUtil.createFile(dfs, new Path("/a"), TEST_LENGTH, (short)1, SEED);
FSDataInputStream stream = dfs.open(new Path("/a"));
byte buf[] = new byte[TEST_LENGTH];
IOUtils.readFully(stream, buf, 0, TEST_LENGTH);
byte expected[] = DFSTestUtil.
calculateFileContentsFromSeed(SEED, TEST_LENGTH);
assertArrayEquals(expected, buf);
stream.close();
} finally {
dfs.close();
cluster.shutdown();
}
}
private static final String SYNTHETIC_BLOCK_READER_TEST_UUID_KEY =
"synthetic.block.reader.test.uuid.key";
private static final HashMap<String, LinkedList<SyntheticReplicaAccessor>>
accessors = new HashMap<String, LinkedList<SyntheticReplicaAccessor>>(1);
public static | TestExternalBlockReader |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_1650/B.java | {
"start": 198,
"end": 329
} | class ____ {
private C c;
public C getC() {
return c;
}
public void setC(C c) {
this.c = c;
}
}
| B |
java | google__auto | value/src/main/java/com/google/auto/value/extension/serializable/serializer/interfaces/SerializerExtension.java | {
"start": 1107,
"end": 1843
} | class ____ be public with a public no-arg constructor, and its fully-qualified name
* must appear in a file called {@code
* META-INF/services/com.google.auto.value.extension.serializable.serializer.interfaces.SerializerExtension}
* in a jar that is on the compiler's {@code -classpath} or {@code -processorpath}.
*
* <p>When SerializableAutoValue maps each field in an AutoValue to a serializable proxy object, it
* asks each SerializerExtension whether it can generate code to make the given type serializable. A
* SerializerExtension replies that it can by returning a non-empty {@link Serializer}.
*
* <p>A SerializerExtension is also provided with a SerializerFactory, which it can use to query
* nested types.
*/
public | must |
java | apache__maven | impl/maven-core/src/main/java/org/apache/maven/classrealm/ClassRealmManager.java | {
"start": 1716,
"end": 1840
} | class ____ exposing the Maven API, never {@code null}.
*/
ClassRealm getMavenApiRealm();
/**
* Gets the | realm |
java | apache__rocketmq | test/src/main/java/org/apache/rocketmq/test/util/data/collect/impl/ListDataCollectorImpl.java | {
"start": 1075,
"end": 2720
} | class ____ implements DataCollector {
private List<Object> datas = new ArrayList<Object>();
private boolean lock = false;
public ListDataCollectorImpl() {
}
public ListDataCollectorImpl(Collection<Object> datas) {
for (Object data : datas) {
addData(data);
}
}
@Override
public Collection<Object> getAllData() {
return datas;
}
@Override
public synchronized void resetData() {
datas.clear();
unlockIncrement();
}
@Override
public long getDataSizeWithoutDuplicate() {
return getAllDataWithoutDuplicate().size();
}
@Override
public synchronized void addData(Object data) {
if (lock) {
return;
}
datas.add(data);
}
@Override
public long getDataSize() {
return datas.size();
}
@Override
public boolean isRepeatedData(Object data) {
return Collections.frequency(datas, data) == 1;
}
@Override
public synchronized Collection<Object> getAllDataWithoutDuplicate() {
return new HashSet<Object>(datas);
}
@Override
public int getRepeatedTimeForData(Object data) {
int res = 0;
for (Object obj : datas) {
if (obj.equals(data)) {
res++;
}
}
return res;
}
@Override
public synchronized void removeData(Object data) {
datas.remove(data);
}
@Override
public void lockIncrement() {
lock = true;
}
@Override
public void unlockIncrement() {
lock = false;
}
}
| ListDataCollectorImpl |
java | spring-projects__spring-framework | spring-aop/src/main/java/org/springframework/aop/config/PointcutEntry.java | {
"start": 837,
"end": 1171
} | class ____ implements ParseState.Entry {
private final String name;
/**
* Create a new {@code PointcutEntry} instance.
* @param name the bean name of the pointcut
*/
public PointcutEntry(String name) {
this.name = name;
}
@Override
public String toString() {
return "Pointcut '" + this.name + "'";
}
}
| PointcutEntry |
java | apache__camel | core/camel-support/src/main/java/org/apache/camel/support/management/DefaultManagementMBeanAssembler.java | {
"start": 1919,
"end": 5896
} | class ____ extends ServiceSupport implements ManagementMBeanAssembler {
private static final Logger LOG = LoggerFactory.getLogger(DefaultManagementMBeanAssembler.class);
protected final MBeanInfoAssembler assembler;
protected final CamelContext camelContext;
public DefaultManagementMBeanAssembler(CamelContext camelContext) {
this.camelContext = camelContext;
this.assembler = new MBeanInfoAssembler(camelContext);
}
@Override
public ModelMBean assemble(MBeanServer mBeanServer, Object obj, ObjectName name) throws JMException {
ModelMBeanInfo mbi = null;
ModelMBeanInfo standardMbi = null;
Object custom = null;
// prefer to use the managed instance if it has been annotated with JMX annotations
if (obj instanceof ManagedInstance managedInstance) {
// there may be a custom embedded instance which have additional methods
custom = managedInstance.getInstance();
if (custom != null && ObjectHelper.hasAnnotation(custom.getClass().getAnnotations(), ManagedResource.class)) {
LOG.trace("Assembling MBeanInfo for: {} from custom @ManagedResource object: {}", name, custom);
// get the mbean info into different groups (mbi = both, standard = standard out of the box mbi)
mbi = assembler.getMBeanInfo(camelContext, obj, custom, name.toString());
standardMbi = assembler.getMBeanInfo(camelContext, obj, null, name.toString());
}
}
if (mbi == null) {
// use the default provided mbean which has been annotated with JMX annotations
LOG.trace("Assembling MBeanInfo for: {} from @ManagedResource object: {}", name, obj);
mbi = assembler.getMBeanInfo(camelContext, obj, null, name.toString());
}
if (mbi == null) {
return null;
}
RequiredModelMBean mbean;
RequiredModelMBean mixinMBean = null;
boolean sanitize = camelContext.getManagementStrategy().getManagementAgent().getMask() != null
&& camelContext.getManagementStrategy().getManagementAgent().getMask();
// if we have a custom mbean then create a mixin mbean for the standard mbean which we would
// otherwise have created that contains the out of the box attributes and operations
// as we want a combined mbean that has both the custom and the standard
if (standardMbi != null) {
mixinMBean = (RequiredModelMBean) mBeanServer.instantiate(RequiredModelMBean.class.getName());
mixinMBean.setModelMBeanInfo(standardMbi);
try {
mixinMBean.setManagedResource(obj, "ObjectReference");
} catch (InvalidTargetObjectTypeException e) {
throw new JMException(e.getMessage());
}
// use custom as the object to call
obj = custom;
}
// use a mixin mbean model to combine the custom and standard (custom is optional)
mbean = new MixinRequiredModelMBean(mbi, sanitize, standardMbi, mixinMBean);
try {
mbean.setManagedResource(obj, "ObjectReference");
} catch (InvalidTargetObjectTypeException e) {
throw new JMException(e.getMessage());
}
// Allows the managed object to send notifications
if (obj instanceof NotificationSenderAware notificationSenderAware) {
notificationSenderAware.setNotificationSender(new NotificationSenderAdapter(mbean));
}
return mbean;
}
@Override
protected void doInit() throws Exception {
ServiceHelper.initService(assembler);
}
@Override
protected void doStart() throws Exception {
ServiceHelper.startService(assembler);
}
@Override
protected void doStop() throws Exception {
ServiceHelper.stopService(assembler);
}
}
| DefaultManagementMBeanAssembler |
java | quarkusio__quarkus | independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/catalog/selection/DefaultOriginSelector.java | {
"start": 337,
"end": 3961
} | class ____ implements OriginSelector {
private OriginCombination recommended;
private double recommendedScore = -1;
private int recommendedRegistryPreference = -1;
public DefaultOriginSelector(Collection<ExtensionOrigins> extOrigins) {
final List<ArtifactKey> extKeys = new ArrayList<>(extOrigins.size());
for (ExtensionOrigins eo : extOrigins) {
extKeys.add(eo.getExtensionKey());
}
int highestRegistryPreference = 0;
final TreeMap<OriginPreference, WorkingCombination> map = new TreeMap<>();
for (ExtensionOrigins eo : extOrigins) {
for (OriginWithPreference op : eo.getOrigins()) {
map.computeIfAbsent(op.getPreference(), k -> new WorkingCombination(k, extKeys))
.addExtension(eo.getExtensionKey(), op);
highestRegistryPreference = Math.max(op.getPreference().registryPreference, highestRegistryPreference);
}
}
final List<WorkingCombination> list = new ArrayList<>(map.values());
for (int i = 0; i < list.size(); ++i) {
WorkingCombination combination = list.get(i);
if (recommendedRegistryPreference >= 0
&& combination.preferences.get(0).registryPreference > recommendedRegistryPreference) {
break;
}
if (combination.isComplete()) {
evaluateCandidate(extOrigins, highestRegistryPreference, combination);
break;
}
combination = complete(combination, list, i + 1);
if (combination != null) {
evaluateCandidate(extOrigins, highestRegistryPreference, combination);
}
}
}
private void evaluateCandidate(Collection<ExtensionOrigins> extOrigins, int highestRegistryPreference,
WorkingCombination combination) {
if (recommended != null) {
if (recommendedScore < 0) {
recommendedScore = OriginCombination.calculateScore(recommended, highestRegistryPreference, extOrigins.size());
}
final OriginCombination candidate = combination.toCombination();
final double candidateScore = OriginCombination.calculateScore(candidate, highestRegistryPreference,
extOrigins.size());
if (recommendedScore < candidateScore) {
recommended = candidate;
recommendedScore = candidateScore;
}
} else {
recommended = combination.toCombination();
recommendedRegistryPreference = combination.preferences.get(0).registryPreference;
}
}
private static WorkingCombination complete(WorkingCombination combination, List<WorkingCombination> list, int fromIndex) {
for (int i = fromIndex; i < list.size(); ++i) {
final WorkingCombination candidate = list.get(i);
if (!combination.canBeCombinedWith(candidate.preferences)) {
continue;
}
WorkingCombination augmented = combination.addMissing(candidate);
if (augmented == null) {
continue;
}
if (augmented.isComplete()) {
return augmented;
}
augmented = complete(augmented, list, i + 1);
if (augmented != null) {
return augmented;
}
}
return null;
}
@Override
public OriginCombination calculateRecommendedCombination() {
return recommended;
}
private static | DefaultOriginSelector |
java | quarkusio__quarkus | independent-projects/arc/processor/src/main/java/io/quarkus/arc/processor/InvokerBuilder.java | {
"start": 5064,
"end": 5257
} | class ____,
* or a type variable that has no bound, or a type variable whose first bound (including
* an implicitly declared {@code java.lang.Object} bound in case all declared bounds are
* | type |
java | elastic__elasticsearch | x-pack/plugin/ent-search/src/test/java/org/elasticsearch/xpack/application/rules/action/ListQueryRulesetsActionResponseBWCSerializingTests.java | {
"start": 1013,
"end": 4116
} | class ____ extends AbstractBWCWireSerializationTestCase<
ListQueryRulesetsAction.Response> {
@Override
protected Writeable.Reader<ListQueryRulesetsAction.Response> instanceReader() {
return ListQueryRulesetsAction.Response::new;
}
private static List<QueryRulesetListItem> randomQueryRulesetList() {
return randomList(10, () -> {
QueryRuleset queryRuleset = EnterpriseSearchModuleTestUtils.randomQueryRuleset();
Map<QueryRuleCriteriaType, Integer> criteriaTypeToCountMap = Map.of(
randomFrom(QueryRuleCriteriaType.values()),
randomIntBetween(1, 10)
);
Map<QueryRule.QueryRuleType, Integer> ruleTypeToCountMap = Map.of(
randomFrom(QueryRule.QueryRuleType.values()),
randomIntBetween(1, 10)
);
return new QueryRulesetListItem(queryRuleset.id(), queryRuleset.rules().size(), criteriaTypeToCountMap, ruleTypeToCountMap);
});
}
@Override
protected ListQueryRulesetsAction.Response mutateInstance(ListQueryRulesetsAction.Response instance) {
QueryPage<QueryRulesetListItem> originalQueryPage = instance.queryPage();
QueryPage<QueryRulesetListItem> mutatedQueryPage = randomValueOtherThan(
originalQueryPage,
() -> new QueryPage<>(randomQueryRulesetList(), randomLongBetween(0, 1000), ListQueryRulesetsAction.Response.RESULT_FIELD)
);
return new ListQueryRulesetsAction.Response(mutatedQueryPage.results(), mutatedQueryPage.count());
}
@Override
protected ListQueryRulesetsAction.Response createTestInstance() {
return new ListQueryRulesetsAction.Response(randomQueryRulesetList(), randomLongBetween(0, 1000));
}
@Override
protected ListQueryRulesetsAction.Response mutateInstanceForVersion(
ListQueryRulesetsAction.Response instance,
TransportVersion version
) {
if (version.onOrAfter(TransportVersions.V_8_16_1)) {
return instance;
} else if (version.onOrAfter(QueryRulesetListItem.EXPANDED_RULESET_COUNT_TRANSPORT_VERSION)) {
List<QueryRulesetListItem> updatedResults = new ArrayList<>();
for (QueryRulesetListItem listItem : instance.queryPage.results()) {
updatedResults.add(
new QueryRulesetListItem(listItem.rulesetId(), listItem.ruleTotalCount(), listItem.criteriaTypeToCountMap(), Map.of())
);
}
return new ListQueryRulesetsAction.Response(updatedResults, instance.queryPage.count());
} else {
List<QueryRulesetListItem> updatedResults = new ArrayList<>();
for (QueryRulesetListItem listItem : instance.queryPage.results()) {
updatedResults.add(new QueryRulesetListItem(listItem.rulesetId(), listItem.ruleTotalCount(), Map.of(), Map.of()));
}
return new ListQueryRulesetsAction.Response(updatedResults, instance.queryPage.count());
}
}
}
| ListQueryRulesetsActionResponseBWCSerializingTests |
java | apache__logging-log4j2 | log4j-api-test/src/test/java/org/apache/logging/log4j/CloseableThreadContextTest.java | {
"start": 1607,
"end": 12382
} | class ____ {
private final String key = "key";
private final String value = "value";
@BeforeEach
@AfterEach
void clearThreadContext() {
ThreadContext.clearAll();
}
@Test
void shouldAddAnEntryToTheMap() {
try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.put(key, value)) {
assertNotNull(ignored);
assertEquals(value, ThreadContext.get(key));
}
}
@Test
void shouldAddTwoEntriesToTheMap() {
final String key2 = "key2";
final String value2 = "value2";
try (final CloseableThreadContext.Instance ignored =
CloseableThreadContext.put(key, value).put(key2, value2)) {
assertNotNull(ignored);
assertEquals(value, ThreadContext.get(key));
assertEquals(value2, ThreadContext.get(key2));
}
}
@Test
void shouldNestEntries() {
final String oldValue = "oldValue";
final String innerValue = "innerValue";
ThreadContext.put(key, oldValue);
try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.put(key, value)) {
assertNotNull(ignored);
assertEquals(value, ThreadContext.get(key));
try (final CloseableThreadContext.Instance ignored2 = CloseableThreadContext.put(key, innerValue)) {
assertNotNull(ignored2);
assertEquals(innerValue, ThreadContext.get(key));
}
assertEquals(value, ThreadContext.get(key));
}
assertEquals(oldValue, ThreadContext.get(key));
}
@Test
void shouldPreserveOldEntriesFromTheMapWhenAutoClosed() {
final String oldValue = "oldValue";
ThreadContext.put(key, oldValue);
try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.put(key, value)) {
assertNotNull(ignored);
assertEquals(value, ThreadContext.get(key));
}
assertEquals(oldValue, ThreadContext.get(key));
}
@Test
void ifTheSameKeyIsAddedTwiceTheOriginalShouldBeUsed() {
final String oldValue = "oldValue";
final String secondValue = "innerValue";
ThreadContext.put(key, oldValue);
try (final CloseableThreadContext.Instance ignored =
CloseableThreadContext.put(key, value).put(key, secondValue)) {
assertNotNull(ignored);
assertEquals(secondValue, ThreadContext.get(key));
}
assertEquals(oldValue, ThreadContext.get(key));
}
@Test
void shouldPushAndPopAnEntryToTheStack() {
final String message = "message";
try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.push(message)) {
assertNotNull(ignored);
assertEquals(message, ThreadContext.peek());
}
assertEquals("", ThreadContext.peek());
}
@Test
void shouldPushAndPopTwoEntriesToTheStack() {
final String message1 = "message1";
final String message2 = "message2";
try (final CloseableThreadContext.Instance ignored =
CloseableThreadContext.push(message1).push(message2)) {
assertNotNull(ignored);
assertEquals(message2, ThreadContext.peek());
}
assertEquals("", ThreadContext.peek());
}
@Test
void shouldPushAndPopAParameterizedEntryToTheStack() {
final String parameterizedMessage = "message {}";
final String parameterizedMessageParameter = "param";
final String formattedMessage = parameterizedMessage.replace("{}", parameterizedMessageParameter);
try (final CloseableThreadContext.Instance ignored =
CloseableThreadContext.push(parameterizedMessage, parameterizedMessageParameter)) {
assertNotNull(ignored);
assertEquals(formattedMessage, ThreadContext.peek());
}
assertEquals("", ThreadContext.peek());
}
@Test
void shouldRemoveAnEntryFromTheMapWhenAutoClosed() {
try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.put(key, value)) {
assertNotNull(ignored);
assertEquals(value, ThreadContext.get(key));
}
assertFalse(ThreadContext.containsKey(key));
}
@Test
void shouldAddEntriesToBothStackAndMap() {
final String stackValue = "something";
try (final CloseableThreadContext.Instance ignored =
CloseableThreadContext.put(key, value).push(stackValue)) {
assertNotNull(ignored);
assertEquals(value, ThreadContext.get(key));
assertEquals(stackValue, ThreadContext.peek());
}
assertFalse(ThreadContext.containsKey(key));
assertEquals("", ThreadContext.peek());
}
@Test
void canReuseCloseableThreadContext() {
final String stackValue = "something";
// Create a ctc and close it
final CloseableThreadContext.Instance ctc =
CloseableThreadContext.push(stackValue).put(key, value);
assertNotNull(ctc);
assertEquals(value, ThreadContext.get(key));
assertEquals(stackValue, ThreadContext.peek());
ctc.close();
assertFalse(ThreadContext.containsKey(key));
assertEquals("", ThreadContext.peek());
final String anotherKey = "key2";
final String anotherValue = "value2";
final String anotherStackValue = "something else";
// Use it again
ctc.push(anotherStackValue).put(anotherKey, anotherValue);
assertEquals(anotherValue, ThreadContext.get(anotherKey));
assertEquals(anotherStackValue, ThreadContext.peek());
ctc.close();
assertFalse(ThreadContext.containsKey(anotherKey));
assertEquals("", ThreadContext.peek());
}
@Test
void closeIsIdempotent() {
final String originalMapValue = "map to keep";
final String originalStackValue = "stack to keep";
ThreadContext.put(key, originalMapValue);
ThreadContext.push(originalStackValue);
final String newMapValue = "temp map value";
final String newStackValue = "temp stack to keep";
final CloseableThreadContext.Instance ctc =
CloseableThreadContext.push(newStackValue).put(key, newMapValue);
assertNotNull(ctc);
ctc.close();
assertEquals(originalMapValue, ThreadContext.get(key));
assertEquals(originalStackValue, ThreadContext.peek());
ctc.close();
assertEquals(originalMapValue, ThreadContext.get(key));
assertEquals(originalStackValue, ThreadContext.peek());
}
@Test
void putAllWillPutAllValues() {
final String oldValue = "oldValue";
ThreadContext.put(key, oldValue);
final Map<String, String> valuesToPut = new HashMap<>();
valuesToPut.put(key, value);
try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.putAll(valuesToPut)) {
assertNotNull(ignored);
assertEquals(value, ThreadContext.get(key));
}
assertEquals(oldValue, ThreadContext.get(key));
}
@Test
void pushAllWillPushAllValues() {
ThreadContext.push(key);
final List<String> messages = ThreadContext.getImmutableStack().asList();
ThreadContext.pop();
try (final CloseableThreadContext.Instance ignored = CloseableThreadContext.pushAll(messages)) {
assertNotNull(ignored);
assertEquals(key, ThreadContext.peek());
}
assertEquals("", ThreadContext.peek());
}
/**
* User provided test stressing nesting using {@link CloseableThreadContext#put(String, String)}.
*
* @see <a href="https://github.com/apache/logging-log4j2/issues/2946#issuecomment-2382935426">#2946</a>
*/
@Test
void testAutoCloseableThreadContextPut() {
try (final CloseableThreadContext.Instance ctc1 = CloseableThreadContext.put("outer", "one")) {
try (final CloseableThreadContext.Instance ctc2 = CloseableThreadContext.put("outer", "two")) {
assertEquals("two", ThreadContext.get("outer"));
try (final CloseableThreadContext.Instance ctc3 = CloseableThreadContext.put("inner", "one")) {
assertEquals("one", ThreadContext.get("inner"));
ThreadContext.put(
"not-in-closeable", "true"); // Remove this line, and closing context behaves as expected
assertEquals("two", ThreadContext.get("outer"));
}
assertEquals("two", ThreadContext.get("outer"));
assertNull(ThreadContext.get("inner")); // Test fails here
}
assertEquals("one", ThreadContext.get("outer"));
assertNull(ThreadContext.get("inner"));
}
assertEquals("true", ThreadContext.get("not-in-closeable"));
assertNull(ThreadContext.get("inner"));
assertNull(ThreadContext.get("outer"));
}
/**
* User provided test stressing nesting using {@link CloseableThreadContext#putAll(Map)}.
*
* @see <a href="https://github.com/apache/logging-log4j2/issues/2946#issuecomment-2382935426">#2946</a>
*/
@Test
void testAutoCloseableThreadContextPutAll() {
try (final CloseableThreadContext.Instance ctc1 = CloseableThreadContext.put("outer", "one")) {
try (final CloseableThreadContext.Instance ctc2 = CloseableThreadContext.put("outer", "two")) {
assertEquals("two", ThreadContext.get("outer"));
try (final CloseableThreadContext.Instance ctc3 = CloseableThreadContext.put("inner", "one")) {
assertEquals("one", ThreadContext.get("inner"));
ThreadContext.put(
"not-in-closeable", "true"); // Remove this line, and closing context behaves as expected
ThreadContext.putAll(Collections.singletonMap("inner", "two")); // But this is not a problem
assertEquals("two", ThreadContext.get("inner"));
assertEquals("two", ThreadContext.get("outer"));
}
assertEquals("two", ThreadContext.get("outer"));
assertNull(ThreadContext.get("inner")); // This is where the test fails
}
assertEquals("one", ThreadContext.get("outer"));
assertNull(ThreadContext.get("inner"));
}
assertEquals("true", ThreadContext.get("not-in-closeable"));
assertNull(ThreadContext.get("inner"));
assertNull(ThreadContext.get("outer"));
}
}
| CloseableThreadContextTest |
java | quarkusio__quarkus | extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/config/runtime/exporter/OtlpExporterRuntimeConfig.java | {
"start": 538,
"end": 899
} | interface ____ extends OtlpExporterConfig {
/**
* OTLP traces exporter configuration.
*/
OtlpExporterTracesConfig traces();
/**
* OTLP metrics exporter configuration.
*/
OtlpExporterMetricsConfig metrics();
/**
* OTLP logs exporter configuration.
*/
OtlpExporterLogsConfig logs();
}
| OtlpExporterRuntimeConfig |
java | apache__kafka | tools/src/test/java/org/apache/kafka/tools/EndToEndLatencyTest.java | {
"start": 2237,
"end": 3243
} | class ____ {
private static final byte[] RECORD_VALUE = "record-sent".getBytes(StandardCharsets.UTF_8);
private static final byte[] RECORD_VALUE_DIFFERENT = "record-received".getBytes(StandardCharsets.UTF_8);
private static final byte[] RECORD_KEY = "key-sent".getBytes(StandardCharsets.UTF_8);
private static final byte[] RECORD_KEY_DIFFERENT = "key-received".getBytes(StandardCharsets.UTF_8);
private static final String HEADER_KEY = "header-key-sent";
private static final String HEADER_KEY_DIFFERENT = "header-key-received";
private static final byte[] HEADER_VALUE = "header-value-sent".getBytes(StandardCharsets.UTF_8);
private static final byte[] HEADER_VALUE_DIFFERENT = "header-value-received".getBytes(StandardCharsets.UTF_8);
// legacy format test arguments
private static final String[] LEGACY_INVALID_ARGS_UNEXPECTED = {
"localhost:9092", "test", "10000", "1", "200", "propsfile.properties", "random"
};
private static | EndToEndLatencyTest |
java | apache__flink | flink-connectors/flink-connector-datagen/src/main/java/org/apache/flink/connector/datagen/source/GeneratorSourceReaderFactory.java | {
"start": 1667,
"end": 2893
} | class ____<OUT>
implements SourceReaderFactory<OUT, NumberSequenceSource.NumberSequenceSplit> {
private final GeneratorFunction<Long, OUT> generatorFunction;
private final RateLimiterStrategy rateLimiterStrategy;
/**
* Instantiates a new {@code GeneratorSourceReaderFactory}.
*
* @param generatorFunction The generator function.
* @param rateLimiterStrategy The rate limiter strategy.
*/
public GeneratorSourceReaderFactory(
GeneratorFunction<Long, OUT> generatorFunction,
RateLimiterStrategy rateLimiterStrategy) {
this.generatorFunction = checkNotNull(generatorFunction);
this.rateLimiterStrategy = checkNotNull(rateLimiterStrategy);
}
@Override
public SourceReader<OUT, NumberSequenceSource.NumberSequenceSplit> createReader(
SourceReaderContext readerContext) {
int parallelism = readerContext.currentParallelism();
RateLimiter rateLimiter = rateLimiterStrategy.createRateLimiter(parallelism);
return new RateLimitedSourceReader<>(
new GeneratingIteratorSourceReader<>(readerContext, generatorFunction),
rateLimiter);
}
}
| GeneratorSourceReaderFactory |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/metadata/ItemUsage.java | {
"start": 1004,
"end": 1087
} | class ____ the usage of a particular "thing" by something else
*/
public | encapsulating |
java | apache__camel | components/camel-google/camel-google-drive/src/test/java/org/apache/camel/component/google/drive/DriveRevisionsIT.java | {
"start": 1584,
"end": 3391
} | class ____ extends AbstractGoogleDriveTestSupport {
private static final Logger LOG = LoggerFactory.getLogger(DriveRevisionsIT.class);
private static final String PATH_PREFIX
= GoogleDriveApiCollection.getCollection().getApiName(DriveRevisionsApiMethod.class).getName();
@Test
public void testList() {
File testFile = uploadTestFile();
String fileId = testFile.getId();
// using String message body for single parameter "fileId"
final com.google.api.services.drive.model.RevisionList result = requestBody("direct://LIST", fileId);
assertNotNull(result, "list result");
LOG.debug("list: {}", result);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// test route for delete
from("direct://DELETE")
.to("google-drive://" + PATH_PREFIX + "/delete");
// test route for get
from("direct://GET")
.to("google-drive://" + PATH_PREFIX + "/get");
// test route for list
from("direct://LIST")
.to("google-drive://" + PATH_PREFIX + "/list?inBody=fileId");
// test route for patch
from("direct://PATCH")
.to("google-drive://" + PATH_PREFIX + "/patch");
// test route for update
from("direct://UPDATE")
.to("google-drive://" + PATH_PREFIX + "/update");
// just used to upload file for test
from("direct://INSERT_1")
.to("google-drive://drive-files/insert");
}
};
}
}
| DriveRevisionsIT |
java | reactor__reactor-core | reactor-core/src/main/java/reactor/core/publisher/FluxBufferWhen.java | {
"start": 12530,
"end": 14314
} | class ____<OPEN>
implements Disposable, InnerConsumer<OPEN> {
volatile @Nullable Subscription subscription;
// https://github.com/uber/NullAway/issues/1157
@SuppressWarnings({"rawtypes", "DataFlowIssue"})
static final AtomicReferenceFieldUpdater<BufferWhenOpenSubscriber, @Nullable Subscription> SUBSCRIPTION =
AtomicReferenceFieldUpdater.newUpdater(BufferWhenOpenSubscriber.class, Subscription.class, "subscription");
final BufferWhenMainSubscriber<?, OPEN, ?, ?> parent;
BufferWhenOpenSubscriber(BufferWhenMainSubscriber<?, OPEN, ?, ?> parent) {
this.parent = parent;
}
@Override
public Context currentContext() {
return parent.currentContext();
}
@Override
public void onSubscribe(Subscription s) {
if (Operators.setOnce(SUBSCRIPTION, this, s)) {
s.request(Long.MAX_VALUE);
}
}
@Override
public void dispose() {
Operators.terminate(SUBSCRIPTION, this);
}
@Override
public boolean isDisposed() {
return subscription == Operators.cancelledSubscription();
}
@Override
public void onNext(OPEN t) {
parent.open(t);
}
@Override
public void onError(Throwable t) {
SUBSCRIPTION.lazySet(this, Operators.cancelledSubscription());
parent.boundaryError(this, t);
}
@Override
public void onComplete() {
SUBSCRIPTION.lazySet(this, Operators.cancelledSubscription());
parent.openComplete(this);
}
@Override
public @Nullable Object scanUnsafe(Attr key) {
if (key == Attr.ACTUAL) return parent;
if (key == Attr.PARENT) return subscription;
if (key == Attr.REQUESTED_FROM_DOWNSTREAM) return Long.MAX_VALUE;
if (key == Attr.CANCELLED) return isDisposed();
if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC;
return null;
}
}
static final | BufferWhenOpenSubscriber |
java | apache__dubbo | dubbo-config/dubbo-config-spring/src/main/java/org/apache/dubbo/config/spring/beans/factory/annotation/AbstractAnnotationBeanPostProcessor.java | {
"start": 16667,
"end": 18979
} | class ____ extends InjectionMetadata.InjectedElement {
public final AnnotationAttributes attributes;
public volatile Object injectedObject;
public Class<?> injectedType;
protected AnnotatedInjectElement(Member member, PropertyDescriptor pd, AnnotationAttributes attributes) {
super(member, pd);
this.attributes = attributes;
}
@Override
protected void inject(Object bean, String beanName, PropertyValues pvs) throws Throwable {
Object injectedObject = getInjectedObject(attributes, bean, beanName, getInjectedType(), this);
if (member instanceof Field) {
Field field = (Field) member;
ReflectionUtils.makeAccessible(field);
field.set(bean, injectedObject);
} else if (member instanceof Method) {
Method method = (Method) member;
ReflectionUtils.makeAccessible(method);
method.invoke(bean, injectedObject);
}
}
public Class<?> getInjectedType() throws ClassNotFoundException {
if (injectedType == null) {
if (this.isField) {
injectedType = ((Field) this.member).getType();
} else if (this.pd != null) {
return this.pd.getPropertyType();
} else {
Method method = (Method) this.member;
if (method.getParameterTypes().length > 0) {
injectedType = method.getParameterTypes()[0];
} else {
throw new IllegalStateException("get injected type failed");
}
}
}
return injectedType;
}
public String getPropertyName() {
if (member instanceof Field) {
Field field = (Field) member;
return field.getName();
} else if (this.pd != null) {
// If it is method element, using propertyName of PropertyDescriptor
return pd.getName();
} else {
Method method = (Method) this.member;
return method.getName();
}
}
}
protected | AnnotatedInjectElement |
java | spring-projects__spring-boot | module/spring-boot-artemis/src/main/java/org/springframework/boot/artemis/autoconfigure/ArtemisConnectionFactoryConfiguration.java | {
"start": 3950,
"end": 4551
} | class ____ {
@Bean(destroyMethod = "stop")
JmsPoolConnectionFactory jmsConnectionFactory(ListableBeanFactory beanFactory, ArtemisProperties properties,
ArtemisConnectionDetails connectionDetails) {
ActiveMQConnectionFactory connectionFactory = new ArtemisConnectionFactoryFactory(beanFactory, properties,
connectionDetails)
.createConnectionFactory(ActiveMQConnectionFactory::new, ActiveMQConnectionFactory::new);
return new JmsPoolConnectionFactoryFactory(properties.getPool())
.createPooledConnectionFactory(connectionFactory);
}
}
}
| PooledConnectionFactoryConfiguration |
java | grpc__grpc-java | core/src/test/java/io/grpc/internal/JndiResourceResolverTest.java | {
"start": 1391,
"end": 3650
} | class ____ {
@Test
public void normalizeDataRemovesJndiFormattingForTxtRecords() {
assertEquals("blah", JndiResourceResolver.unquote("blah"));
assertEquals("", JndiResourceResolver.unquote("\"\""));
assertEquals("blahblah", JndiResourceResolver.unquote("blah blah"));
assertEquals("blahfoo blah", JndiResourceResolver.unquote("blah \"foo blah\""));
assertEquals("blah blah", JndiResourceResolver.unquote("\"blah blah\""));
assertEquals("blah\"blah", JndiResourceResolver.unquote("\"blah\\\"blah\""));
assertEquals("blah\\blah", JndiResourceResolver.unquote("\"blah\\\\blah\""));
}
@IgnoreJRERequirement
@Test
public void jndiResolverWorks() throws Exception {
Assume.assumeNoException(new JndiResourceResolverFactory().unavailabilityCause());
RecordFetcher recordFetcher = new JndiRecordFetcher();
try {
recordFetcher.getAllRecords("SRV", "dns:///localhost");
} catch (javax.naming.CommunicationException e) {
Assume.assumeNoException(e);
} catch (javax.naming.NameNotFoundException e) {
Assume.assumeNoException(e);
}
}
@Test
public void txtRecordLookup() throws Exception {
RecordFetcher recordFetcher = mock(RecordFetcher.class);
when(recordFetcher.getAllRecords("TXT", "dns:///service.example.com"))
.thenReturn(Arrays.asList("foo", "\"bar\""));
List<String> golden = Arrays.asList("foo", "bar");
JndiResourceResolver resolver = new JndiResourceResolver(recordFetcher);
assertThat(resolver.resolveTxt("service.example.com")).isEqualTo(golden);
}
@SuppressWarnings("deprecation")
@Test
public void srvRecordLookup() throws Exception {
RecordFetcher recordFetcher = mock(RecordFetcher.class);
when(recordFetcher.getAllRecords("SRV", "dns:///service.example.com"))
.thenReturn(Arrays.asList(
"0 0 314 foo.example.com.", "0 0 42 bar.example.com.", "0 0 1 discard.example.com"));
List<SrvRecord> golden = Arrays.asList(
new SrvRecord("foo.example.com.", 314),
new SrvRecord("bar.example.com.", 42));
JndiResourceResolver resolver = new JndiResourceResolver(recordFetcher);
assertThat(resolver.resolveSrv("service.example.com")).isEqualTo(golden);
}
}
| JndiResourceResolverTest |
java | spring-projects__spring-security | web/src/main/java/org/springframework/security/web/authentication/session/SessionFixationProtectionEvent.java | {
"start": 1090,
"end": 2240
} | class ____ extends AbstractAuthenticationEvent {
@Serial
private static final long serialVersionUID = -2554621992006921150L;
private final String oldSessionId;
private final String newSessionId;
/**
* Constructs a new session fixation protection event.
* @param authentication The authentication object
* @param oldSessionId The old session ID before it was changed
* @param newSessionId The new session ID after it was changed
*/
public SessionFixationProtectionEvent(Authentication authentication, String oldSessionId, String newSessionId) {
super(authentication);
Assert.hasLength(oldSessionId, "oldSessionId must have length");
Assert.hasLength(newSessionId, "newSessionId must have length");
this.oldSessionId = oldSessionId;
this.newSessionId = newSessionId;
}
/**
* Getter for the session ID before it was changed.
* @return the old session ID.
*/
public String getOldSessionId() {
return this.oldSessionId;
}
/**
* Getter for the session ID after it was changed.
* @return the new session ID.
*/
public String getNewSessionId() {
return this.newSessionId;
}
}
| SessionFixationProtectionEvent |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/rest/action/admin/cluster/RestNodesUsageAction.java | {
"start": 1455,
"end": 3792
} | class ____ extends BaseRestHandler {
@Override
public List<Route> routes() {
return List.of(
new Route(GET, "/_nodes/usage"),
new Route(GET, "/_nodes/{nodeId}/usage"),
new Route(GET, "/_nodes/usage/{metric}"),
new Route(GET, "/_nodes/{nodeId}/usage/{metric}")
);
}
@Override
protected RestChannelConsumer prepareRequest(RestRequest request, NodeClient client) throws IOException {
String[] nodesIds = Strings.splitStringByCommaToArray(request.param("nodeId"));
Set<String> metrics = Strings.tokenizeByCommaToSet(request.param("metric", "_all"));
NodesUsageRequest nodesUsageRequest = new NodesUsageRequest(nodesIds);
nodesUsageRequest.setTimeout(getTimeout(request));
if (metrics.size() == 1 && metrics.contains("_all")) {
nodesUsageRequest.all();
} else if (metrics.contains("_all")) {
throw new IllegalArgumentException(
String.format(
Locale.ROOT,
"request [%s] contains _all and individual metrics [%s]",
request.path(),
request.param("metric")
)
);
} else {
nodesUsageRequest.clear();
nodesUsageRequest.restActions(metrics.contains("rest_actions"));
nodesUsageRequest.aggregations(metrics.contains("aggregations"));
}
return channel -> client.admin().cluster().nodesUsage(nodesUsageRequest, new RestBuilderListener<NodesUsageResponse>(channel) {
@Override
public RestResponse buildResponse(NodesUsageResponse response, XContentBuilder builder) throws Exception {
builder.startObject();
RestActions.buildNodesHeader(builder, channel.request(), response);
builder.field("cluster_name", response.getClusterName().value());
response.toXContent(builder, channel.request());
builder.endObject();
return new RestResponse(RestStatus.OK, builder);
}
});
}
@Override
public String getName() {
return "nodes_usage_action";
}
@Override
public boolean canTripCircuitBreaker() {
return false;
}
}
| RestNodesUsageAction |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/RedisPublisher.java | {
"start": 28563,
"end": 29722
} | class ____<T> implements RedisSubscriber<T> {
private final CoreSubscriber<T> delegate;
private final Executor executor;
public PublishOnSubscriber(Subscriber<T> delegate, Executor executor) {
this.delegate = (CoreSubscriber) reactor.core.publisher.Operators.toCoreSubscriber(delegate);
this.executor = executor;
}
@Override
public Context currentContext() {
return delegate.currentContext();
}
@Override
public void onSubscribe(Subscription s) {
delegate.onSubscribe(s);
}
@Override
public void onNext(T t) {
executor.execute(OnNext.newInstance(t, delegate));
}
@Override
public void onError(Throwable t) {
executor.execute(OnComplete.newInstance(t, delegate));
}
@Override
public void onComplete() {
executor.execute(OnComplete.newInstance(delegate));
}
}
/**
* OnNext {@link Runnable}. This listener is pooled and must be {@link #recycle() recycled after usage}.
*/
static | PublishOnSubscriber |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/snapshot/AbstractINodeDiff.java | {
"start": 1917,
"end": 4889
} | class ____<N extends INode,
A extends INodeAttributes,
D extends AbstractINodeDiff<N, A, D>>
implements Comparable<Integer> {
/** The id of the corresponding snapshot. */
private int snapshotId;
/** The snapshot inode data. It is null when there is no change. */
A snapshotINode;
/**
* Posterior diff is the diff happened after this diff.
* The posterior diff should be first applied to obtain the posterior
* snapshot and then apply this diff in order to obtain this snapshot.
* If the posterior diff is null, the posterior state is the current state.
*/
private D posteriorDiff;
AbstractINodeDiff(int snapshotId, A snapshotINode, D posteriorDiff) {
this.snapshotId = snapshotId;
this.snapshotINode = snapshotINode;
this.posteriorDiff = posteriorDiff;
}
/** Compare diffs with snapshot ID. */
@Override
public final int compareTo(final Integer that) {
return Snapshot.ID_INTEGER_COMPARATOR.compare(this.snapshotId, that);
}
/** @return the snapshot object of this diff. */
public final int getSnapshotId() {
return snapshotId;
}
final void setSnapshotId(int snapshot) {
this.snapshotId = snapshot;
}
/** @return the posterior diff. */
final D getPosterior() {
return posteriorDiff;
}
final void setPosterior(D posterior) {
posteriorDiff = posterior;
}
/** Save the INode state to the snapshot if it is not done already. */
void saveSnapshotCopy(A snapshotCopy) {
Preconditions.checkState(snapshotINode == null, "Expected snapshotINode to be null");
snapshotINode = snapshotCopy;
}
/** @return the inode corresponding to the snapshot. */
A getSnapshotINode() {
// get from this diff, then the posterior diff
// and then null for the current inode
for(AbstractINodeDiff<N, A, D> d = this; ; d = d.posteriorDiff) {
if (d.snapshotINode != null) {
return d.snapshotINode;
} else if (d.posteriorDiff == null) {
return null;
}
}
}
/** Combine the posterior diff and collect blocks for deletion. */
abstract void combinePosteriorAndCollectBlocks(
INode.ReclaimContext reclaimContext, final N currentINode,
final D posterior);
/**
* Delete and clear self.
* @param reclaimContext blocks and inodes that need to be reclaimed
* @param currentINode The inode where the deletion happens.
*/
abstract void destroyDiffAndCollectBlocks(INode.ReclaimContext reclaimContext,
final N currentINode);
@Override
public String toString() {
return getClass().getSimpleName() + ": " + this.getSnapshotId() + " (post="
+ (posteriorDiff == null? null: posteriorDiff.getSnapshotId()) + ")";
}
void writeSnapshot(DataOutput out) throws IOException {
out.writeInt(snapshotId);
}
abstract void write(DataOutput out, ReferenceMap referenceMap
) throws IOException;
}
| AbstractINodeDiff |
java | quarkusio__quarkus | extensions/amazon-lambda/common-runtime/src/main/java/io/quarkus/amazon/lambda/runtime/DateModule.java | {
"start": 1748,
"end": 2552
} | class ____ extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser parser, DeserializationContext context) throws IOException {
double dateSeconds = parser.getValueAsDouble();
if (dateSeconds == 0.0) {
return null;
} else {
return new Date((long) secondsToMillis(dateSeconds));
}
}
}
private static double millisToSeconds(double millis) {
return millis / 1000.0;
}
private static double secondsToMillis(double seconds) {
return seconds * 1000.0;
}
public DateModule() {
super(PackageVersion.VERSION);
addSerializer(Date.class, new Serializer());
addDeserializer(Date.class, new Deserializer());
}
}
| Deserializer |
java | apache__logging-log4j2 | log4j-api/src/main/java/org/apache/logging/log4j/util/Activator.java | {
"start": 1733,
"end": 2010
} | class ____.</em>
* OSGi bundle activator. Used for locating an implementation of
* {@link org.apache.logging.log4j.spi.LoggerContextFactory} et al. that have corresponding
* {@code META-INF/log4j-provider.properties} files. As with all OSGi BundleActivator classes, this | private |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/checker/AbstractFuture.java | {
"start": 37800,
"end": 38796
} | class ____ {
/**
* Non volatile write of the thread to the {@link Waiter#thread} field.
*/
abstract void putThread(Waiter waiter, Thread newValue);
/**
* Non volatile write of the waiter to the {@link Waiter#next} field.
*/
abstract void putNext(Waiter waiter, Waiter newValue);
/**
* Performs a CAS operation on the {@link #waiters} field.
*/
abstract boolean casWaiters(
AbstractFuture<?> future, Waiter expect,
Waiter update);
/**
* Performs a CAS operation on the {@link #listeners} field.
*/
abstract boolean casListeners(
AbstractFuture<?> future, Listener expect,
Listener update);
/**
* Performs a CAS operation on the {@link #value} field.
*/
abstract boolean casValue(
AbstractFuture<?> future, Object expect, Object update);
}
/**
* {@link AtomicHelper} based on {@link sun.misc.Unsafe}.
* <p>
* <p>Static initialization of this | AtomicHelper |
java | spring-projects__spring-framework | spring-beans/src/test/java/org/springframework/beans/factory/annotation/AutowiredAnnotationBeanPostProcessorTests.java | {
"start": 157465,
"end": 157599
} | class ____ {
@Autowired
public RepositoryFactoryBean<?> repositoryFactoryBean;
}
public static | RepositoryFactoryBeanInjectionBean |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/dynamic/RedisCommandsAsyncIntegrationTests.java | {
"start": 1265,
"end": 1383
} | interface ____ extends Commands {
Future<String> set(String key, String value);
}
}
| MultipleExecutionModels |
java | apache__camel | components/camel-olingo2/camel-olingo2-component/src/test/java/org/apache/camel/component/olingo2/AbstractOlingo2AppAPITestSupport.java | {
"start": 7341,
"end": 9080
} | class ____<T> implements Olingo2ResponseHandler<T> {
private T response;
private Exception error;
private CountDownLatch latch = new CountDownLatch(1);
@Override
public void onResponse(T response, Map<String, String> responseHeaders) {
this.response = response;
if (LOG.isDebugEnabled()) {
if (response instanceof ODataFeed) {
LOG.debug("Received response: {}", prettyPrint((ODataFeed) response));
} else if (response instanceof ODataEntry) {
LOG.debug("Received response: {}", prettyPrint((ODataEntry) response));
} else {
LOG.debug("Received response: {}", response);
}
}
latch.countDown();
}
@Override
public void onException(Exception ex) {
error = ex;
latch.countDown();
}
@Override
public void onCanceled() {
error = new IllegalStateException("Request Canceled");
latch.countDown();
}
public T await() throws Exception {
return await(TIMEOUT, TimeUnit.SECONDS);
}
public T await(long timeout, TimeUnit unit) throws Exception {
assertTrue(latch.await(timeout, unit), "Timeout waiting for response");
if (error != null) {
throw error;
}
assertNotNull(response, "Response");
return response;
}
public void reset() {
latch.countDown();
latch = new CountDownLatch(1);
response = null;
error = null;
}
}
}
| TestOlingo2ResponseHandler |
java | qos-ch__slf4j | log4j-over-slf4j/src/main/java/org/apache/log4j/Level.java | {
"start": 6273,
"end": 7563
} | class ____ found.
*/
private void readObject(final ObjectInputStream s) throws IOException, ClassNotFoundException {
s.defaultReadObject();
level = s.readInt();
syslogEquivalent = s.readInt();
levelStr = s.readUTF();
if (levelStr == null) {
levelStr = "";
}
}
/**
* Serialize level.
*
* @param s serialization stream.
* @throws IOException if exception during serialization.
*/
private void writeObject(final ObjectOutputStream s) throws IOException {
s.defaultWriteObject();
s.writeInt(level);
s.writeInt(syslogEquivalent);
s.writeUTF(levelStr);
}
/**
* Resolved deserialized level to one of the stock instances. May be overridden
* in classes derived from Level.
*
* @return resolved object.
* @throws ObjectStreamException if exception during resolution.
*/
private Object readResolve() throws ObjectStreamException {
//
// if the deserialized object is exactly an instance of Level
//
if (getClass() == Level.class) {
return toLevel(level);
}
//
// extension of Level can't substitute stock item
//
return this;
}
} | not |
java | grpc__grpc-java | api/src/main/java/io/grpc/LongHistogramMetricInstrument.java | {
"start": 731,
"end": 1303
} | class ____ extends PartialMetricInstrument {
private final List<Long> bucketBoundaries;
public LongHistogramMetricInstrument(int index, String name, String description, String unit,
List<Long> bucketBoundaries, List<String> requiredLabelKeys, List<String> optionalLabelKeys,
boolean enableByDefault) {
super(index, name, description, unit, requiredLabelKeys, optionalLabelKeys, enableByDefault);
this.bucketBoundaries = bucketBoundaries;
}
public List<Long> getBucketBoundaries() {
return bucketBoundaries;
}
}
| LongHistogramMetricInstrument |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/extension/ExtensionLoader_Compatible_Test.java | {
"start": 1263,
"end": 1773
} | class ____ {
@Test
void test_getExtension() {
ModuleModel moduleModel = ApplicationModel.defaultModel().getDefaultModule();
assertTrue(
moduleModel.getExtensionLoader(CompatibleExt.class).getExtension("impl1")
instanceof CompatibleExtImpl1);
assertTrue(
moduleModel.getExtensionLoader(CompatibleExt.class).getExtension("impl2")
instanceof CompatibleExtImpl2);
}
}
| ExtensionLoader_Compatible_Test |
java | apache__camel | components/camel-mapstruct/src/test/java/org/apache/camel/component/mapstruct/mapper/VehicleMapper.java | {
"start": 1057,
"end": 1287
} | class ____ {
@Mapping(source = "brand", target = "company")
@Mapping(source = "model", target = "name")
@Mapping(source = "electric", target = "power")
public abstract VehicleDto toVehicle(CarDto car);
}
| VehicleMapper |
java | spring-projects__spring-security | core/src/test/java/org/springframework/security/aot/hint/AuthorizeReturnObjectCoreHintsRegistrarTests.java | {
"start": 1304,
"end": 2546
} | class ____ {
private final AuthorizationProxyFactory proxyFactory = spy(AuthorizationAdvisorProxyFactory.withDefaults());
private final AuthorizeReturnObjectCoreHintsRegistrar registrar = new AuthorizeReturnObjectCoreHintsRegistrar(
this.proxyFactory);
@Test
public void registerHintsWhenUsingAuthorizeReturnObjectThenRegisters() {
GenericApplicationContext context = new GenericApplicationContext();
context.registerBean(MyService.class, MyService::new);
context.registerBean(MyInterface.class, MyImplementation::new);
context.refresh();
RuntimeHints hints = new RuntimeHints();
this.registrar.registerHints(hints, context.getBeanFactory());
assertThat(hints.reflection().typeHints().map((hint) -> hint.getType().getName())).containsOnly(
cglibClassName(MyObject.class), cglibClassName(MySubObject.class), MyObject.class.getName(),
MySubObject.class.getName());
assertThat(hints.proxies()
.jdkProxyHints()
.flatMap((hint) -> hint.getProxiedInterfaces().stream())
.map(TypeReference::getName)).contains(MyInterface.class.getName());
}
private static String cglibClassName(Class<?> clazz) {
return clazz.getName() + "$$SpringCGLIB$$0";
}
public static | AuthorizeReturnObjectCoreHintsRegistrarTests |
java | quarkusio__quarkus | extensions/devui/deployment-spi/src/main/java/io/quarkus/devui/spi/JsonRPCProvidersBuildItem.java | {
"start": 527,
"end": 1569
} | class ____ extends AbstractDevUIBuildItem {
private final Class jsonRPCMethodProviderClass;
private final DotName defaultBeanScope;
public JsonRPCProvidersBuildItem(Class jsonRPCMethodProviderClass) {
super();
this.jsonRPCMethodProviderClass = jsonRPCMethodProviderClass;
this.defaultBeanScope = null;
}
public JsonRPCProvidersBuildItem(Class jsonRPCMethodProviderClass, DotName defaultBeanScope) {
super();
this.jsonRPCMethodProviderClass = jsonRPCMethodProviderClass;
this.defaultBeanScope = defaultBeanScope;
}
public JsonRPCProvidersBuildItem(String customIdentifier, Class jsonRPCMethodProviderClass) {
super(customIdentifier);
this.jsonRPCMethodProviderClass = jsonRPCMethodProviderClass;
this.defaultBeanScope = null;
}
public Class getJsonRPCMethodProviderClass() {
return jsonRPCMethodProviderClass;
}
public DotName getDefaultBeanScope() {
return defaultBeanScope;
}
}
| JsonRPCProvidersBuildItem |
java | google__error-prone | core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessPropagationTest.java | {
"start": 51662,
"end": 52676
} | class ____ {
static String staticStringField;
}
}\
""")
.doTest();
}
@Test
public void transferFunctions7() {
compilationHelper
.addSourceLines(
"NullnessPropagationTransferCases7.java",
"""
package com.google.errorprone.dataflow.nullnesspropagation.testdata;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessChecker;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessCheckerOnBoxed;
import static com.google.errorprone.dataflow.nullnesspropagation.NullnessPropagationTest.triggerNullnessCheckerOnPrimitive;
import static com.google.errorprone.dataflow.nullnesspropagation.testdata.NullnessPropagationTransferCases7.HasStaticFields.staticIntField;
import static com.google.errorprone.dataflow.nullnesspropagation.testdata.NullnessPropagationTransferCases7.HasStaticFields.staticStringField;
/** Tests for field accesses and assignments. */
public | HasStaticFields |
java | google__auto | value/src/it/functional/src/test/java/com/google/auto/value/gwt/GwtCompilationTest.java | {
"start": 1225,
"end": 1473
} | class ____ {
private static final JavaFileObject GWT_COMPATIBLE =
JavaFileObjects.forSourceLines(
"com.google.annotations.GwtCompatible",
"package com.google.annotations;",
"",
"public @ | GwtCompilationTest |
java | apache__kafka | clients/src/test/java/org/apache/kafka/test/TestSslUtils.java | {
"start": 4241,
"end": 20087
} | class ____ {
public static final String TRUST_STORE_PASSWORD = "TrustStorePassword";
public static final String DEFAULT_TLS_PROTOCOL_FOR_TESTS = SslConfigs.DEFAULT_SSL_PROTOCOL;
/**
* Create a self-signed X.509 Certificate.
* From http://bfo.com/blog/2011/03/08/odds_and_ends_creating_a_new_x_509_certificate.html.
*
* @param dn the X.509 Distinguished Name, eg "CN=Test, L=London, C=GB"
* @param pair the KeyPair
* @param days how many days from now the Certificate is valid for, or - for negative values - how many days before now
* @param algorithm the signing algorithm, eg "SHA256withRSA"
* @return the self-signed certificate
* @throws CertificateException thrown if a security error or an IO error occurred.
*/
public static X509Certificate generateCertificate(String dn, KeyPair pair,
int days, String algorithm)
throws CertificateException {
return new CertificateBuilder(days, algorithm).generate(dn, pair);
}
/**
* Generate a signed certificate. Self-signed, if no issuer and parentKeyPair are supplied
*
* @param dn The distinguished name of this certificate
* @param keyPair A key pair
* @param daysBeforeNow how many days before now the Certificate is valid for
* @param daysAfterNow how many days from now the Certificate is valid for
* @param issuer The issuer who signs the certificate. Leave null if you want to generate a root
* CA.
* @param parentKeyPair The key pair of the issuer. Leave null if you want to generate a root
* CA.
* @param algorithm the signing algorithm, eg "SHA256withRSA"
* @return the signed certificate
* @throws CertificateException
*/
public static X509Certificate generateSignedCertificate(String dn, KeyPair keyPair,
int daysBeforeNow, int daysAfterNow, String issuer, KeyPair parentKeyPair,
String algorithm, boolean isCA, boolean isServerCert, boolean isClientCert) throws CertificateException {
return new CertificateBuilder(0, algorithm).generateSignedCertificate(dn, keyPair,
daysBeforeNow, daysAfterNow, issuer, parentKeyPair, isCA, isServerCert, isClientCert);
}
public static X509Certificate generateSignedCertificate(String dn, KeyPair keyPair,
int daysBeforeNow, int daysAfterNow, String issuer, KeyPair parentKeyPair,
String algorithm, boolean isCA, boolean isServerCert, boolean isClientCert,
String[] hostNames) throws CertificateException, IOException {
return new CertificateBuilder(0, algorithm).sanDnsNames(hostNames).generateSignedCertificate(dn, keyPair,
daysBeforeNow, daysAfterNow, issuer, parentKeyPair, isCA, isServerCert, isClientCert);
}
public static KeyPair generateKeyPair(String algorithm) throws NoSuchAlgorithmException {
KeyPairGenerator keyGen = KeyPairGenerator.getInstance(algorithm);
keyGen.initialize(algorithm.equals("EC") ? 256 : 2048);
return keyGen.genKeyPair();
}
private static KeyStore createEmptyKeyStore() throws GeneralSecurityException, IOException {
KeyStore ks = KeyStore.getInstance("JKS");
ks.load(null, null); // initialize
return ks;
}
private static void saveKeyStore(KeyStore ks, String filename,
Password password) throws GeneralSecurityException, IOException {
try (OutputStream out = Files.newOutputStream(Paths.get(filename))) {
ks.store(out, password.value().toCharArray());
}
}
/**
* Creates a keystore with a single key and saves it to a file.
*
* @param filename String file to save
* @param password String store password to set on keystore
* @param keyPassword String key password to set on key
* @param alias String alias to use for the key
* @param privateKey Key to save in keystore
* @param cert Certificate to use as certificate chain associated to key
* @throws GeneralSecurityException for any error with the security APIs
* @throws IOException if there is an I/O error saving the file
*/
public static void createKeyStore(String filename,
Password password, Password keyPassword, String alias,
Key privateKey, Certificate cert) throws GeneralSecurityException, IOException {
KeyStore ks = createEmptyKeyStore();
ks.setKeyEntry(alias, privateKey, keyPassword.value().toCharArray(),
new Certificate[]{cert});
saveKeyStore(ks, filename, password);
}
public static <T extends Certificate> void createTrustStore(
String filename, Password password, Map<String, T> certs) throws GeneralSecurityException, IOException {
KeyStore ks = KeyStore.getInstance("JKS");
try (InputStream in = Files.newInputStream(Paths.get(filename))) {
ks.load(in, password.value().toCharArray());
} catch (EOFException e) {
ks = createEmptyKeyStore();
}
for (Map.Entry<String, T> cert : certs.entrySet()) {
ks.setCertificateEntry(cert.getKey(), cert.getValue());
}
saveKeyStore(ks, filename, password);
}
public static Map<String, Object> createSslConfig(String keyManagerAlgorithm, String trustManagerAlgorithm, String tlsProtocol) {
Map<String, Object> sslConfigs = new HashMap<>();
sslConfigs.put(SslConfigs.SSL_PROTOCOL_CONFIG, tlsProtocol); // protocol to create SSLContext
sslConfigs.put(SslConfigs.SSL_KEYMANAGER_ALGORITHM_CONFIG, keyManagerAlgorithm);
sslConfigs.put(SslConfigs.SSL_TRUSTMANAGER_ALGORITHM_CONFIG, trustManagerAlgorithm);
sslConfigs.put(SslConfigs.SSL_CIPHER_SUITES_CONFIG, List.of());
List<String> enabledProtocols = new ArrayList<>();
enabledProtocols.add(tlsProtocol);
sslConfigs.put(SslConfigs.SSL_ENABLED_PROTOCOLS_CONFIG, enabledProtocols);
return sslConfigs;
}
public static Map<String, Object> createSslConfig(boolean useClientCert, boolean trustStore, ConnectionMode connectionMode, File trustStoreFile, String certAlias)
throws IOException, GeneralSecurityException {
return createSslConfig(useClientCert, trustStore, connectionMode, trustStoreFile, certAlias, "localhost");
}
public static Map<String, Object> createSslConfig(boolean useClientCert, boolean trustStore,
ConnectionMode connectionMode, File trustStoreFile, String certAlias, String cn)
throws IOException, GeneralSecurityException {
return createSslConfig(useClientCert, trustStore, connectionMode, trustStoreFile, certAlias, cn, new CertificateBuilder());
}
public static Map<String, Object> createSslConfig(boolean useClientCert, boolean createTrustStore,
ConnectionMode connectionMode, File trustStoreFile, String certAlias, String cn, CertificateBuilder certBuilder)
throws IOException, GeneralSecurityException {
SslConfigsBuilder builder = new SslConfigsBuilder(connectionMode)
.useClientCert(useClientCert)
.certAlias(certAlias)
.cn(cn)
.certBuilder(certBuilder);
if (createTrustStore)
builder = builder.createNewTrustStore(trustStoreFile);
else
builder = builder.useExistingTrustStore(trustStoreFile);
return builder.build();
}
public static void convertToPem(Map<String, Object> sslProps, boolean writeToFile, boolean encryptPrivateKey) throws Exception {
String tsPath = (String) sslProps.get(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG);
String tsType = (String) sslProps.get(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG);
Password tsPassword = (Password) sslProps.remove(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG);
Password trustCerts = (Password) sslProps.remove(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG);
if (trustCerts == null && tsPath != null) {
trustCerts = exportCertificates(tsPath, tsPassword, tsType);
}
if (trustCerts != null) {
if (tsPath == null) {
tsPath = TestUtils.tempFile("truststore", ".pem").getPath();
sslProps.put(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG, tsPath);
}
sslProps.put(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, PEM_TYPE);
if (writeToFile)
writeToFile(tsPath, trustCerts);
else {
sslProps.put(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG, trustCerts);
sslProps.remove(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG);
}
}
String ksPath = (String) sslProps.get(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG);
Password certChain = (Password) sslProps.remove(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG);
Password key = (Password) sslProps.remove(SslConfigs.SSL_KEYSTORE_KEY_CONFIG);
if (certChain == null && ksPath != null) {
String ksType = (String) sslProps.get(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG);
Password ksPassword = (Password) sslProps.remove(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG);
Password keyPassword = (Password) sslProps.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG);
certChain = exportCertificates(ksPath, ksPassword, ksType);
Password pemKeyPassword = encryptPrivateKey ? keyPassword : null;
key = exportPrivateKey(ksPath, ksPassword, keyPassword, ksType, pemKeyPassword);
if (!encryptPrivateKey)
sslProps.remove(SslConfigs.SSL_KEY_PASSWORD_CONFIG);
}
if (certChain != null) {
if (ksPath == null) {
ksPath = TestUtils.tempFile("keystore", ".pem").getPath();
sslProps.put(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG, ksPath);
}
sslProps.put(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, PEM_TYPE);
if (writeToFile)
writeToFile(ksPath, key, certChain);
else {
sslProps.put(SslConfigs.SSL_KEYSTORE_KEY_CONFIG, key);
sslProps.put(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG, certChain);
sslProps.remove(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG);
}
}
}
private static void writeToFile(String path, Password... entries) throws IOException {
try (FileOutputStream out = new FileOutputStream(path)) {
for (Password entry: entries) {
out.write(entry.value().getBytes(StandardCharsets.UTF_8));
}
}
}
public static void convertToPemWithoutFiles(Properties sslProps) throws Exception {
String tsPath = sslProps.getProperty(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG);
if (tsPath != null) {
Password trustCerts = exportCertificates(tsPath,
(Password) sslProps.get(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG),
sslProps.getProperty(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG));
sslProps.remove(SslConfigs.SSL_TRUSTSTORE_LOCATION_CONFIG);
sslProps.remove(SslConfigs.SSL_TRUSTSTORE_PASSWORD_CONFIG);
sslProps.setProperty(SslConfigs.SSL_TRUSTSTORE_TYPE_CONFIG, PEM_TYPE);
sslProps.put(SslConfigs.SSL_TRUSTSTORE_CERTIFICATES_CONFIG, trustCerts);
}
String ksPath = sslProps.getProperty(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG);
if (ksPath != null) {
String ksType = sslProps.getProperty(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG);
Password ksPassword = (Password) sslProps.get(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG);
Password keyPassword = (Password) sslProps.get(SslConfigs.SSL_KEY_PASSWORD_CONFIG);
Password certChain = exportCertificates(ksPath, ksPassword, ksType);
Password key = exportPrivateKey(ksPath, ksPassword, keyPassword, ksType, keyPassword);
sslProps.remove(SslConfigs.SSL_KEYSTORE_LOCATION_CONFIG);
sslProps.remove(SslConfigs.SSL_KEYSTORE_PASSWORD_CONFIG);
sslProps.setProperty(SslConfigs.SSL_KEYSTORE_TYPE_CONFIG, PEM_TYPE);
sslProps.put(SslConfigs.SSL_KEYSTORE_CERTIFICATE_CHAIN_CONFIG, certChain);
sslProps.put(SslConfigs.SSL_KEYSTORE_KEY_CONFIG, key);
}
}
public static Password exportCertificates(String storePath, Password storePassword, String storeType) throws Exception {
StringBuilder builder = new StringBuilder();
try (FileInputStream in = new FileInputStream(storePath)) {
KeyStore ks = KeyStore.getInstance(storeType);
ks.load(in, storePassword.value().toCharArray());
Enumeration<String> aliases = ks.aliases();
if (!aliases.hasMoreElements())
throw new IllegalArgumentException("No certificates found in file " + storePath);
while (aliases.hasMoreElements()) {
String alias = aliases.nextElement();
Certificate[] certs = ks.getCertificateChain(alias);
if (certs != null) {
for (Certificate cert : certs) {
builder.append(pem(cert));
}
} else {
builder.append(pem(ks.getCertificate(alias)));
}
}
}
return new Password(builder.toString());
}
public static Password exportPrivateKey(String storePath,
Password storePassword,
Password keyPassword,
String storeType,
Password pemKeyPassword) throws Exception {
try (FileInputStream in = new FileInputStream(storePath)) {
KeyStore ks = KeyStore.getInstance(storeType);
ks.load(in, storePassword.value().toCharArray());
String alias = ks.aliases().nextElement();
return new Password(pem((PrivateKey) ks.getKey(alias, keyPassword.value().toCharArray()), pemKeyPassword));
}
}
static String pem(Certificate cert) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) {
pemWriter.writeObject(new JcaMiscPEMGenerator(cert));
}
return out.toString(StandardCharsets.UTF_8);
}
static String pem(PrivateKey privateKey, Password password) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (PemWriter pemWriter = new PemWriter(new OutputStreamWriter(out, StandardCharsets.UTF_8))) {
if (password == null) {
pemWriter.writeObject(new JcaPKCS8Generator(privateKey, null));
} else {
JceOpenSSLPKCS8EncryptorBuilder encryptorBuilder = new JceOpenSSLPKCS8EncryptorBuilder(PKCS8Generator.PBE_SHA1_3DES);
encryptorBuilder.setPassword(password.value().toCharArray());
try {
pemWriter.writeObject(new JcaPKCS8Generator(privateKey, encryptorBuilder.build()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return out.toString(StandardCharsets.UTF_8);
}
public static | TestSslUtils |
java | apache__flink | flink-queryable-state/flink-queryable-state-runtime/src/main/java/org/apache/flink/queryablestate/client/proxy/KvStateClientProxyImpl.java | {
"start": 1876,
"end": 5712
} | class ____ extends AbstractServerBase<KvStateRequest, KvStateResponse>
implements KvStateClientProxy {
/** Number of threads used to process incoming requests. */
private final int queryExecutorThreads;
/** Statistics collector. */
private final KvStateRequestStats stats;
private final ConcurrentHashMap<JobID, KvStateLocationOracle> kvStateLocationOracles;
/**
* Creates the Queryable State Client Proxy.
*
* <p>The server is instantiated using reflection by the {@link
* org.apache.flink.runtime.query.QueryableStateUtils#createKvStateClientProxy(String, Iterator,
* int, int, KvStateRequestStats) QueryableStateUtils.createKvStateClientProxy(InetAddress,
* Iterator, int, int, KvStateRequestStats)}.
*
* <p>The server needs to be started via {@link #start()} in order to bind to the configured
* bind address.
*
* @param bindAddress the address to listen to.
* @param bindPortIterator the port range to try to bind to.
* @param numEventLoopThreads number of event loop threads.
* @param numQueryThreads number of query threads.
* @param stats the statistics collector.
*/
public KvStateClientProxyImpl(
final String bindAddress,
final Iterator<Integer> bindPortIterator,
final Integer numEventLoopThreads,
final Integer numQueryThreads,
final KvStateRequestStats stats) {
super(
"Queryable State Proxy Server",
bindAddress,
bindPortIterator,
numEventLoopThreads,
numQueryThreads);
Preconditions.checkArgument(numQueryThreads >= 1, "Non-positive number of query threads.");
this.queryExecutorThreads = numQueryThreads;
this.stats = Preconditions.checkNotNull(stats);
this.kvStateLocationOracles = new ConcurrentHashMap<>(4);
}
@Override
public InetSocketAddress getServerAddress() {
return super.getServerAddress();
}
@Override
public void start() throws Throwable {
super.start();
}
@Override
public void shutdown() {
try {
shutdownServer().get(10L, TimeUnit.SECONDS);
log.info("{} was shutdown successfully.", getServerName());
} catch (Exception e) {
log.warn("{} shutdown failed: {}", getServerName(), e);
}
}
@Override
public void updateKvStateLocationOracle(
JobID jobId, @Nullable KvStateLocationOracle kvStateLocationOracle) {
if (kvStateLocationOracle == null) {
kvStateLocationOracles.remove(jobId);
} else {
kvStateLocationOracles.put(jobId, kvStateLocationOracle);
}
}
@Nullable
@Override
public KvStateLocationOracle getKvStateLocationOracle(JobID jobId) {
final KvStateLocationOracle legacyKvStateLocationOracle =
kvStateLocationOracles.get(HighAvailabilityServices.DEFAULT_JOB_ID);
// we give preference to the oracle registered under the default job id
// to make it work with the legacy code paths
if (legacyKvStateLocationOracle != null) {
return legacyKvStateLocationOracle;
} else {
return kvStateLocationOracles.get(jobId);
}
}
@Override
public AbstractServerHandler<KvStateRequest, KvStateResponse> initializeHandler() {
MessageSerializer<KvStateRequest, KvStateResponse> serializer =
new MessageSerializer<>(
new KvStateRequest.KvStateRequestDeserializer(),
new KvStateResponse.KvStateResponseDeserializer());
return new KvStateClientProxyHandler(this, queryExecutorThreads, serializer, stats);
}
}
| KvStateClientProxyImpl |
java | mybatis__mybatis-3 | src/test/java/org/apache/ibatis/reflection/wrapper/MapWrapperTest.java | {
"start": 5503,
"end": 7919
} | class ____ {
private String propA;
private String propB;
public String getPropA() {
return propA;
}
public void setPropA(String propA) {
this.propA = propA;
}
public String getPropB() {
return propB;
}
public void setPropB(String propB) {
this.propB = propB;
}
}
@Test
void accessIndexedList() {
Map<String, Object> map = new HashMap<>();
List<String> list = Arrays.asList("a", "b", "c");
map.put("list", list);
MetaObject metaObj = MetaObject.forObject(map, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(),
new DefaultReflectorFactory());
assertEquals("b", metaObj.getValue("list[1]"));
metaObj.setValue("list[2]", "x");
assertEquals("x", list.get(2));
try {
metaObj.setValue("list[3]", "y");
fail();
} catch (IndexOutOfBoundsException e) {
// pass
}
assertTrue(metaObj.hasGetter("list[1]"));
assertTrue(metaObj.hasSetter("list[1]"));
// this one looks wrong
// assertFalse(metaObj.hasSetter("list[3]"));
}
@Test
void accessIndexedMap() {
Map<String, Object> map = new HashMap<>();
Map<String, String> submap = new HashMap<>();
submap.put("a", "100");
submap.put("b", "200");
submap.put("c", "300");
map.put("submap", submap);
MetaObject metaObj = MetaObject.forObject(map, new DefaultObjectFactory(), new DefaultObjectWrapperFactory(),
new DefaultReflectorFactory());
assertEquals("200", metaObj.getValue("submap[b]"));
metaObj.setValue("submap[c]", "999");
assertEquals("999", submap.get("c"));
metaObj.setValue("submap[d]", "400");
assertEquals(4, submap.size());
assertEquals("400", submap.get("d"));
assertTrue(metaObj.hasGetter("submap[b]"));
assertTrue(metaObj.hasGetter("submap[anykey]"));
assertTrue(metaObj.hasSetter("submap[d]"));
assertTrue(metaObj.hasSetter("submap[anykey]"));
}
@ParameterizedTest
@CsvSource({ "abc[def]", "abc.def", "abc.def.ghi", "abc[d.ef].ghi" })
void customMapWrapper(String key) {
Map<String, Object> map = new HashMap<>();
MetaObject metaObj = MetaObject.forObject(map, new DefaultObjectFactory(), new FlatMapWrapperFactory(),
new DefaultReflectorFactory());
metaObj.setValue(key, "1");
assertEquals("1", map.get(key));
assertEquals("1", metaObj.getValue(key));
}
static | TestBean |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/connector/source/DynamicFilteringValuesSource.java | {
"start": 2266,
"end": 5888
} | class ____
implements Source<RowData, ValuesSourcePartitionSplit, NoOpEnumState> {
private final TypeSerializer<RowData> serializer;
private final TerminatingLogic terminatingLogic;
private final Boundedness boundedness;
private Map<Map<String, String>, byte[]> serializedElements;
private Map<Map<String, String>, Integer> counts;
private final List<String> dynamicFilteringFields;
public DynamicFilteringValuesSource(
TerminatingLogic terminatingLogic,
Boundedness boundedness,
Map<Map<String, String>, Collection<RowData>> elements,
TypeSerializer<RowData> serializer,
List<String> dynamicFilteringFields) {
this.serializer = serializer;
this.dynamicFilteringFields = dynamicFilteringFields;
this.terminatingLogic = terminatingLogic;
this.boundedness = boundedness;
serializeElements(serializer, elements);
}
private void serializeElements(
TypeSerializer<RowData> serializer,
Map<Map<String, String>, Collection<RowData>> elements) {
Preconditions.checkState(serializer != null, "serializer not set");
serializedElements = new HashMap<>();
counts = new HashMap<>();
for (Map<String, String> partition : elements.keySet()) {
Collection<RowData> collection = elements.get(partition);
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputViewStreamWrapper wrapper = new DataOutputViewStreamWrapper(baos)) {
for (RowData e : collection) {
serializer.serialize(e, wrapper);
}
byte[] value = baos.toByteArray();
serializedElements.put(partition, value);
} catch (Exception e) {
throw new TableException(
"Serializing the source elements failed: " + e.getMessage(), e);
}
counts.put(partition, collection.size());
}
}
@Override
public Boundedness getBoundedness() {
return boundedness;
}
@Override
public SourceReader<RowData, ValuesSourcePartitionSplit> createReader(
SourceReaderContext readerContext) throws Exception {
return new DynamicFilteringValuesSourceReader(
serializedElements, counts, serializer, readerContext);
}
@Override
public SplitEnumerator<ValuesSourcePartitionSplit, NoOpEnumState> createEnumerator(
SplitEnumeratorContext<ValuesSourcePartitionSplit> context) throws Exception {
List<ValuesSourcePartitionSplit> splits =
serializedElements.keySet().stream()
.map(ValuesSourcePartitionSplit::new)
.collect(Collectors.toList());
return new DynamicFilteringValuesSourceEnumerator(
context, terminatingLogic, splits, dynamicFilteringFields);
}
@Override
public SplitEnumerator<ValuesSourcePartitionSplit, NoOpEnumState> restoreEnumerator(
SplitEnumeratorContext<ValuesSourcePartitionSplit> context, NoOpEnumState checkpoint)
throws Exception {
return createEnumerator(context);
}
@Override
public SimpleVersionedSerializer<ValuesSourcePartitionSplit> getSplitSerializer() {
return new ValuesSourcePartitionSplitSerializer();
}
@Override
public SimpleVersionedSerializer<NoOpEnumState> getEnumeratorCheckpointSerializer() {
return new NoOpEnumStateSerializer();
}
}
| DynamicFilteringValuesSource |
java | apache__camel | components/camel-elasticsearch-rest-client/src/generated/java/org/apache/camel/component/elasticsearch/rest/client/ElasticsearchRestClientEndpointConfigurer.java | {
"start": 752,
"end": 6022
} | class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
ElasticsearchRestClientEndpoint target = (ElasticsearchRestClientEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "certificatepath":
case "certificatePath": target.setCertificatePath(property(camelContext, java.lang.String.class, value)); return true;
case "connectiontimeout":
case "connectionTimeout": target.setConnectionTimeout(property(camelContext, int.class, value)); return true;
case "enablesniffer":
case "enableSniffer": target.setEnableSniffer(property(camelContext, boolean.class, value)); return true;
case "hostaddresseslist":
case "hostAddressesList": target.setHostAddressesList(property(camelContext, java.lang.String.class, value)); return true;
case "indexname":
case "indexName": target.setIndexName(property(camelContext, java.lang.String.class, value)); return true;
case "lazystartproducer":
case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
case "operation": target.setOperation(property(camelContext, org.apache.camel.component.elasticsearch.rest.client.ElasticsearchRestClientOperation.class, value)); return true;
case "password": target.setPassword(property(camelContext, java.lang.String.class, value)); return true;
case "restclient":
case "restClient": target.setRestClient(property(camelContext, org.elasticsearch.client.RestClient.class, value)); return true;
case "sniffafterfailuredelay":
case "sniffAfterFailureDelay": target.setSniffAfterFailureDelay(property(camelContext, int.class, value)); return true;
case "snifferinterval":
case "snifferInterval": target.setSnifferInterval(property(camelContext, int.class, value)); return true;
case "sockettimeout":
case "socketTimeout": target.setSocketTimeout(property(camelContext, int.class, value)); return true;
case "user": target.setUser(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public String[] getAutowiredNames() {
return new String[]{"restClient"};
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "certificatepath":
case "certificatePath": return java.lang.String.class;
case "connectiontimeout":
case "connectionTimeout": return int.class;
case "enablesniffer":
case "enableSniffer": return boolean.class;
case "hostaddresseslist":
case "hostAddressesList": return java.lang.String.class;
case "indexname":
case "indexName": return java.lang.String.class;
case "lazystartproducer":
case "lazyStartProducer": return boolean.class;
case "operation": return org.apache.camel.component.elasticsearch.rest.client.ElasticsearchRestClientOperation.class;
case "password": return java.lang.String.class;
case "restclient":
case "restClient": return org.elasticsearch.client.RestClient.class;
case "sniffafterfailuredelay":
case "sniffAfterFailureDelay": return int.class;
case "snifferinterval":
case "snifferInterval": return int.class;
case "sockettimeout":
case "socketTimeout": return int.class;
case "user": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
ElasticsearchRestClientEndpoint target = (ElasticsearchRestClientEndpoint) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "certificatepath":
case "certificatePath": return target.getCertificatePath();
case "connectiontimeout":
case "connectionTimeout": return target.getConnectionTimeout();
case "enablesniffer":
case "enableSniffer": return target.isEnableSniffer();
case "hostaddresseslist":
case "hostAddressesList": return target.getHostAddressesList();
case "indexname":
case "indexName": return target.getIndexName();
case "lazystartproducer":
case "lazyStartProducer": return target.isLazyStartProducer();
case "operation": return target.getOperation();
case "password": return target.getPassword();
case "restclient":
case "restClient": return target.getRestClient();
case "sniffafterfailuredelay":
case "sniffAfterFailureDelay": return target.getSniffAfterFailureDelay();
case "snifferinterval":
case "snifferInterval": return target.getSnifferInterval();
case "sockettimeout":
case "socketTimeout": return target.getSocketTimeout();
case "user": return target.getUser();
default: return null;
}
}
}
| ElasticsearchRestClientEndpointConfigurer |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/aggfunctions/SingleValueAggFunction.java | {
"start": 8394,
"end": 8921
} | class ____ extends SingleValueAggFunction {
private static final long serialVersionUID = 320495723666949978L;
private final DecimalType type;
public DecimalSingleValueAggFunction(DecimalType type) {
this.type = type;
}
@Override
public DataType getResultType() {
return DataTypes.DECIMAL(type.getPrecision(), type.getScale());
}
}
/** Built-in char single value aggregate function. */
public static final | DecimalSingleValueAggFunction |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/event/spi/DirtyCheckEvent.java | {
"start": 272,
"end": 532
} | class ____ extends AbstractSessionEvent {
private boolean dirty;
public DirtyCheckEvent(EventSource source) {
super(source);
}
public boolean isDirty() {
return dirty;
}
public void setDirty(boolean dirty) {
this.dirty = dirty;
}
}
| DirtyCheckEvent |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/fields/RecursiveComparisonAssert_isEqualTo_withComparatorsForFieldMatchingRegexes_Test.java | {
"start": 10839,
"end": 11188
} | class ____ {
final String firstname;
final String lastname;
public Name(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
@Override
public String toString() {
return "Name[firstname=%s, lastname=%s]".formatted(this.firstname, this.lastname);
}
}
static | Name |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.