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 | spring-cloud__spring-cloud-gateway | spring-cloud-gateway-server-webflux/src/test/java/org/springframework/cloud/gateway/test/ssl/ClientCertAuthSSLTests.java | {
"start": 1701,
"end": 3386
} | class ____ extends SingleCertSSLTests {
@Value("${spring.cloud.gateway.server.webflux.httpclient.ssl.key-store}")
private String keyStore;
@Value("${spring.cloud.gateway.server.webflux.httpclient.ssl.key-store-password}")
private String keyStorePassword;
@Value("${spring.cloud.gateway.server.webflux.httpclient.ssl.key-password}")
private String keyPassword;
@BeforeEach
public void setup() throws Exception {
KeyStore store = KeyStore.getInstance("JKS");
try {
URL url = ResourceUtils.getURL(keyStore);
store.load(url.openStream(), keyStorePassword != null ? keyStorePassword.toCharArray() : null);
}
catch (Exception e) {
throw new WebServerException("Could not load key store ' " + keyStore + "'", e);
}
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
char[] keyPasswordCharArray = keyPassword != null ? keyPassword.toCharArray() : null;
if (keyPasswordCharArray == null && keyStorePassword != null) {
keyPasswordCharArray = keyStorePassword.toCharArray();
}
keyManagerFactory.init(store, keyPasswordCharArray);
try {
SslContext sslContext = SslContextBuilder.forClient()
.trustManager(InsecureTrustManagerFactory.INSTANCE)
.keyManager(keyManagerFactory)
.build();
HttpClient httpClient = HttpClient.create().secure(ssl -> ssl.sslContext(sslContext));
setup(new ReactorClientHttpConnector(httpClient), "https://localhost:" + port);
}
catch (SSLException e) {
throw new RuntimeException(e);
}
}
@Test
public void testSslTrust() {
testClient.get().uri("/ssltrust").exchange().expectStatus().is2xxSuccessful();
}
}
| ClientCertAuthSSLTests |
java | google__error-prone | check_api/src/test/java/com/google/errorprone/util/FindIdentifiersTest.java | {
"start": 39156,
"end": 39272
} | class ____. */
@BugPattern(severity = SeverityLevel.ERROR, summary = "A is visible on ClassTree")
public static | tree |
java | spring-projects__spring-boot | smoke-test/spring-boot-smoke-test-data-elasticsearch/src/main/java/smoketest/data/elasticsearch/SampleDocument.java | {
"start": 925,
"end": 1405
} | class ____ {
@Id
private @Nullable String id;
private @Nullable String text;
public @Nullable String getId() {
return this.id;
}
public void setId(@Nullable String id) {
this.id = id;
}
public @Nullable String getText() {
return this.text;
}
public void setText(@Nullable String text) {
this.text = text;
}
@Override
public String toString() {
return "SampleDocument{" + "id='" + this.id + '\'' + ", text='" + this.text + '\'' + '}';
}
}
| SampleDocument |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/resultmapping/InheritanceTests.java | {
"start": 3870,
"end": 4062
} | class ____ extends Parent {
@Column(name = "test")
int test;
public Child() {
}
public Child(Long id, String name, int test) {
super( id, name );
this.test = test;
}
}
}
| Child |
java | apache__flink | flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/operators/aggregate/window/SlicingWindowAggOperatorTest.java | {
"start": 2201,
"end": 37769
} | class ____ extends WindowAggOperatorTestBase {
public SlicingWindowAggOperatorTest(ZoneId shiftTimeZone, boolean enableAsyncState) {
super(shiftTimeZone, enableAsyncState);
}
@Parameters(name = "TimeZone = {0}, EnableAsyncState = {1}")
private static Collection<Object[]> runMode() {
return Arrays.asList(
new Object[] {UTC_ZONE_ID, false},
new Object[] {UTC_ZONE_ID, true},
new Object[] {SHANGHAI_ZONE_ID, false},
new Object[] {SHANGHAI_ZONE_ID, true});
}
@TestTemplate
void testEventTimeHoppingWindows() throws Exception {
final SliceAssigner assigner =
SliceAssigners.hopping(
2, shiftTimeZone, Duration.ofSeconds(3), Duration.ofSeconds(1));
final SlicingSumAndCountAggsFunction aggsFunction =
new SlicingSumAndCountAggsFunction(assigner);
OneInputStreamOperator<RowData, RowData> operator =
buildWindowOperator(assigner, aggsFunction, 1);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(operator);
testHarness.setup(OUT_SERIALIZER);
testHarness.open();
// process elements
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
// add elements out-of-order
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(3999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(3000L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(20L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(0L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1998L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1000L)));
testHarness.processWatermark(new Watermark(999));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(-2000L), localMills(1000L)));
expectedOutput.add(new Watermark(999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processWatermark(new Watermark(1999));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(-1000L), localMills(2000L)));
expectedOutput.add(insertRecord("key2", 3L, 3L, localMills(-1000L), localMills(2000L)));
expectedOutput.add(new Watermark(1999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processWatermark(new Watermark(2999));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(0L), localMills(3000L)));
expectedOutput.add(insertRecord("key2", 3L, 3L, localMills(0L), localMills(3000L)));
expectedOutput.add(new Watermark(2999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// do a snapshot, close and restore again
testHarness.prepareSnapshotPreBarrier(0L);
OperatorSubtaskState snapshot = testHarness.snapshot(0L, 0);
testHarness.close();
assertThat(aggsFunction.closeCalled.get()).as("Close was not called.").isGreaterThan(0);
expectedOutput.clear();
testHarness = createTestHarness(operator);
testHarness.setup(OUT_SERIALIZER);
testHarness.initializeState(snapshot);
testHarness.open();
testHarness.processWatermark(new Watermark(3999));
expectedOutput.add(insertRecord("key2", 5L, 5L, localMills(1000L), localMills(4000L)));
expectedOutput.add(new Watermark(3999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// late element for [1K, 4K), but should be accumulated into [2K, 5K), [3K, 6K)
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(3500L)));
testHarness.processWatermark(new Watermark(4999));
expectedOutput.add(insertRecord("key2", 3L, 3L, localMills(2000L), localMills(5000L)));
expectedOutput.add(new Watermark(4999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// late for all assigned windows, should be dropped
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(2999L)));
testHarness.processWatermark(new Watermark(5999));
expectedOutput.add(insertRecord("key2", 3L, 3L, localMills(3000L), localMills(6000L)));
expectedOutput.add(new Watermark(5999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// those don't have any effect...
testHarness.processWatermark(new Watermark(6999));
testHarness.processWatermark(new Watermark(7999));
expectedOutput.add(new Watermark(6999));
expectedOutput.add(new Watermark(7999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
assertThat(getNumLateRecordsDroppedCount(operator)).isEqualTo(1);
testHarness.close();
}
@TestTemplate
public void testEventTimeHoppingWindowWithExpiredSliceAndRestore() throws Exception {
final SliceAssigner assigner =
SliceAssigners.hopping(
2, shiftTimeZone, Duration.ofSeconds(3), Duration.ofSeconds(1));
final SlicingSumAndCountAggsFunction aggsFunction =
new SlicingSumAndCountAggsFunction(assigner);
OneInputStreamOperator<RowData, RowData> operator =
buildWindowOperator(assigner, aggsFunction, 1);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(operator);
testHarness.setup(OUT_SERIALIZER);
testHarness.open();
// 1. process elements
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(1020L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(1001L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(1999L)));
testHarness.processWatermark(new Watermark(2001));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(-1000L), localMills(2000L)));
expectedOutput.add(new Watermark(2001));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// 2. do a snapshot, close and restore again
testHarness.prepareSnapshotPreBarrier(0L);
OperatorSubtaskState snapshot = testHarness.snapshot(0L, 0);
testHarness.close();
assertThat(aggsFunction.closeCalled.get()).as("Close was not called.").isGreaterThan(0);
expectedOutput.clear();
testHarness = createTestHarness(operator);
testHarness.setup(OUT_SERIALIZER);
testHarness.initializeState(snapshot);
testHarness.open();
// 3. process elements
// Expired slice but belong to other window.
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1500L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(2998L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(2999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(2000L)));
testHarness.processWatermark(new Watermark(2999));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(0L), localMills(3000L)));
expectedOutput.add(insertRecord("key2", 4L, 4L, localMills(0L), localMills(3000L)));
expectedOutput.add(new Watermark(2999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
}
@TestTemplate
public void testEventTimeHoppingWindowWithExpiredSliceAndNoRestore() throws Exception {
final SliceAssigner assigner =
SliceAssigners.hopping(
2, shiftTimeZone, Duration.ofSeconds(3), Duration.ofSeconds(1));
final SlicingSumAndCountAggsFunction aggsFunction =
new SlicingSumAndCountAggsFunction(assigner);
OneInputStreamOperator<RowData, RowData> operator =
buildWindowOperator(assigner, aggsFunction, 1);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(operator);
testHarness.setup(OUT_SERIALIZER);
testHarness.open();
// 1. process elements
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(1020L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(1001L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(1999L)));
testHarness.processWatermark(new Watermark(2001));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(-1000L), localMills(2000L)));
expectedOutput.add(new Watermark(2001));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// 2. process elements
// Expired slice but belong to other window.
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1500L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(2998L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(2999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(2000L)));
testHarness.processWatermark(new Watermark(2999));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(0L), localMills(3000L)));
expectedOutput.add(insertRecord("key2", 4L, 4L, localMills(0L), localMills(3000L)));
expectedOutput.add(new Watermark(2999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
}
@TestTemplate
void testProcessingTimeHoppingWindows() throws Exception {
final SliceAssigner assigner =
SliceAssigners.hopping(-1, shiftTimeZone, Duration.ofHours(3), Duration.ofHours(1));
final SlicingSumAndCountAggsFunction aggsFunction =
new SlicingSumAndCountAggsFunction(assigner);
OneInputStreamOperator<RowData, RowData> operator =
buildWindowOperator(assigner, aggsFunction, 1);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(operator);
testHarness.setup(OUT_SERIALIZER);
testHarness.open();
// process elements
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
// timestamp is ignored in processing time
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T00:00:00.003"));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T01:00:00"));
expectedOutput.add(
insertRecord(
"key2",
1L,
1L,
epochMills(UTC_ZONE_ID, "1969-12-31T22:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T01:00:00")));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T02:00:00"));
expectedOutput.add(
insertRecord(
"key2",
3L,
3L,
epochMills(UTC_ZONE_ID, "1969-12-31T23:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T02:00:00")));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T03:00:00"));
expectedOutput.add(
insertRecord(
"key2",
3L,
3L,
epochMills(UTC_ZONE_ID, "1970-01-01T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T03:00:00")));
expectedOutput.add(
insertRecord(
"key1",
2L,
2L,
epochMills(UTC_ZONE_ID, "1970-01-01T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T03:00:00")));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T07:00:00"));
expectedOutput.add(
insertRecord(
"key2",
2L,
2L,
epochMills(UTC_ZONE_ID, "1970-01-01T01:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T04:00:00")));
expectedOutput.add(
insertRecord(
"key1",
5L,
5L,
epochMills(UTC_ZONE_ID, "1970-01-01T01:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T04:00:00")));
expectedOutput.add(
insertRecord(
"key1",
5L,
5L,
epochMills(UTC_ZONE_ID, "1970-01-01T02:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T05:00:00")));
expectedOutput.add(
insertRecord(
"key1",
3L,
3L,
epochMills(UTC_ZONE_ID, "1970-01-01T03:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T06:00:00")));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
assertThat(aggsFunction.closeCalled.get()).as("Close was not called.").isGreaterThan(0);
}
@TestTemplate
void testEventTimeCumulativeWindows() throws Exception {
final SliceAssigner assigner =
SliceAssigners.cumulative(
2, shiftTimeZone, Duration.ofSeconds(3), Duration.ofSeconds(1));
final SlicingSumAndCountAggsFunction aggsFunction =
new SlicingSumAndCountAggsFunction(assigner);
OneInputStreamOperator<RowData, RowData> operator =
buildWindowOperator(assigner, aggsFunction, null);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(operator);
testHarness.setup(OUT_SERIALIZER);
testHarness.open();
// process elements
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
// add elements out-of-order
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(2999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(3000L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(20L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(0L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1998L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1000L)));
testHarness.processWatermark(new Watermark(999));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(0L), localMills(1000L)));
expectedOutput.add(new Watermark(999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processWatermark(new Watermark(1999));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(0L), localMills(2000L)));
expectedOutput.add(insertRecord("key2", 3L, 3L, localMills(0L), localMills(2000L)));
expectedOutput.add(new Watermark(1999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// do a snapshot, close and restore again
testHarness.prepareSnapshotPreBarrier(0L);
OperatorSubtaskState snapshot = testHarness.snapshot(0L, 0);
testHarness.close();
assertThat(aggsFunction.closeCalled.get()).as("Close was not called.").isGreaterThan(0);
expectedOutput.clear();
testHarness = createTestHarness(operator);
testHarness.setup();
testHarness.initializeState(snapshot);
testHarness.open();
// the late event would not trigger window [0, 2000L) again even if the job restore from
// savepoint
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1000L)));
testHarness.processWatermark(new Watermark(1999));
expectedOutput.add(new Watermark(1999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processWatermark(new Watermark(2999));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(0L), localMills(3000L)));
expectedOutput.add(insertRecord("key2", 5L, 5L, localMills(0L), localMills(3000L)));
expectedOutput.add(new Watermark(2999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processWatermark(new Watermark(3999));
expectedOutput.add(insertRecord("key2", 1L, 1L, localMills(3000L), localMills(4000L)));
expectedOutput.add(new Watermark(3999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// late element for [3K, 4K), but should be accumulated into [3K, 5K) [3K, 6K)
testHarness.processElement(insertRecord("key1", 2, fromEpochMillis(3500L)));
testHarness.processWatermark(new Watermark(4999));
expectedOutput.add(insertRecord("key2", 1L, 1L, localMills(3000L), localMills(5000L)));
expectedOutput.add(insertRecord("key1", 2L, 1L, localMills(3000L), localMills(5000L)));
expectedOutput.add(new Watermark(4999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// late for all assigned windows, should be dropped
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(2999L)));
testHarness.processWatermark(new Watermark(5999));
expectedOutput.add(insertRecord("key2", 1L, 1L, localMills(3000L), localMills(6000L)));
expectedOutput.add(insertRecord("key1", 2L, 1L, localMills(3000L), localMills(6000L)));
expectedOutput.add(new Watermark(5999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// those don't have any effect...
testHarness.processWatermark(new Watermark(6999));
testHarness.processWatermark(new Watermark(7999));
expectedOutput.add(new Watermark(6999));
expectedOutput.add(new Watermark(7999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
assertThat(getNumLateRecordsDroppedCount(operator)).isEqualTo(1);
testHarness.close();
}
@TestTemplate
void testProcessingTimeCumulativeWindows() throws Exception {
final SliceAssigner assigner =
SliceAssigners.cumulative(
-1, shiftTimeZone, Duration.ofDays(1), Duration.ofHours(8));
final SlicingSumAndCountAggsFunction aggsFunction =
new SlicingSumAndCountAggsFunction(assigner);
OneInputStreamOperator<RowData, RowData> operator =
buildWindowOperator(assigner, aggsFunction, null);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(operator);
testHarness.setup(OUT_SERIALIZER);
testHarness.open();
// process elements
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
// timestamp is ignored in processing time
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T00:00:00.003"));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T08:00:00"));
expectedOutput.add(
insertRecord(
"key2",
1L,
1L,
epochMills(UTC_ZONE_ID, "1970-01-01T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T08:00:00")));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T16:00:00"));
expectedOutput.add(
insertRecord(
"key2",
3L,
3L,
epochMills(UTC_ZONE_ID, "1970-01-01T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T16:00:00")));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-02T00:00:00"));
expectedOutput.add(
insertRecord(
"key2",
3L,
3L,
epochMills(UTC_ZONE_ID, "1970-01-01T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-02T00:00:00")));
expectedOutput.add(
insertRecord(
"key1",
2L,
2L,
epochMills(UTC_ZONE_ID, "1970-01-01T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-02T00:00:00")));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-03T08:00:00"));
expectedOutput.add(
insertRecord(
"key1",
2L,
2L,
epochMills(UTC_ZONE_ID, "1970-01-02T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-02T08:00:00")));
expectedOutput.add(
insertRecord(
"key2",
1L,
1L,
epochMills(UTC_ZONE_ID, "1970-01-02T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-02T08:00:00")));
expectedOutput.add(
insertRecord(
"key1",
2L,
2L,
epochMills(UTC_ZONE_ID, "1970-01-02T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-02T16:00:00")));
expectedOutput.add(
insertRecord(
"key2",
1L,
1L,
epochMills(UTC_ZONE_ID, "1970-01-02T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-02T16:00:00")));
expectedOutput.add(
insertRecord(
"key1",
2L,
2L,
epochMills(UTC_ZONE_ID, "1970-01-02T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-03T00:00:00")));
expectedOutput.add(
insertRecord(
"key2",
1L,
1L,
epochMills(UTC_ZONE_ID, "1970-01-02T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-03T00:00:00")));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
assertThat(aggsFunction.closeCalled.get()).as("Close was not called.").isGreaterThan(0);
}
@TestTemplate
void testEventTimeTumblingWindows() throws Exception {
final SliceAssigner assigner =
SliceAssigners.tumbling(2, shiftTimeZone, Duration.ofSeconds(3));
final SlicingSumAndCountAggsFunction aggsFunction =
new SlicingSumAndCountAggsFunction(assigner);
OneInputStreamOperator<RowData, RowData> operator =
buildWindowOperator(assigner, aggsFunction, null);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(operator);
testHarness.setup(OUT_SERIALIZER);
testHarness.open();
// process elements
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
// add elements out-of-order
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(3999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(3000L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(20L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(0L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1998L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1999L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(1000L)));
testHarness.processWatermark(new Watermark(999));
expectedOutput.add(new Watermark(999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processWatermark(new Watermark(1999));
expectedOutput.add(new Watermark(1999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// do a snapshot, close and restore again
testHarness.prepareSnapshotPreBarrier(0L);
OperatorSubtaskState snapshot = testHarness.snapshot(0L, 0);
testHarness.close();
assertThat(aggsFunction.closeCalled.get()).as("Close was not called.").isGreaterThan(0);
expectedOutput.clear();
testHarness = createTestHarness(operator);
testHarness.setup();
testHarness.initializeState(snapshot);
testHarness.open();
testHarness.processWatermark(new Watermark(2999));
expectedOutput.add(insertRecord("key1", 3L, 3L, localMills(0L), localMills(3000L)));
expectedOutput.add(insertRecord("key2", 3L, 3L, localMills(0L), localMills(3000L)));
expectedOutput.add(new Watermark(2999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processWatermark(new Watermark(3999));
expectedOutput.add(new Watermark(3999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// late element, should be dropped
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(2500L)));
testHarness.processWatermark(new Watermark(4999));
expectedOutput.add(new Watermark(4999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// late element, should be dropped
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(2999L)));
testHarness.processWatermark(new Watermark(5999));
expectedOutput.add(insertRecord("key2", 2L, 2L, localMills(3000L), localMills(6000L)));
expectedOutput.add(new Watermark(5999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
// those don't have any effect...
testHarness.processWatermark(new Watermark(6999));
testHarness.processWatermark(new Watermark(7999));
expectedOutput.add(new Watermark(6999));
expectedOutput.add(new Watermark(7999));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
assertThat(getNumLateRecordsDroppedCount(operator)).isEqualTo(2);
testHarness.close();
}
@TestTemplate
void testProcessingTimeTumblingWindows() throws Exception {
final SliceAssigner assigner =
SliceAssigners.tumbling(-1, shiftTimeZone, Duration.ofHours(5));
// the assigned windows should like as following, e.g. the given timeZone is GMT+08:00:
// local windows(timestamp in GMT+08:00) <=> epoch windows(timestamp in UTC)
// [1970-01-01 00:00, 1970-01-01 05:00] <=> [1969-12-31 16:00, 1969-12-31 21:00]
// [1970-01-01 05:00, 1970-01-01 10:00] <=> [1969-12-31 21:00, 1970-01-01 02:00]
final SlicingSumAndCountAggsFunction aggsFunction =
new SlicingSumAndCountAggsFunction(assigner);
OneInputStreamOperator<RowData, RowData> operator =
buildWindowOperator(assigner, aggsFunction, null);
OneInputStreamOperatorTestHarness<RowData, RowData> testHarness =
createTestHarness(operator);
testHarness.setup(OUT_SERIALIZER);
testHarness.open();
// process elements
ConcurrentLinkedQueue<Object> expectedOutput = new ConcurrentLinkedQueue<>();
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T00:00:00.003"));
// timestamp is ignored in processing time
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(Long.MAX_VALUE)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(7000L)));
testHarness.processElement(insertRecord("key2", 1, fromEpochMillis(7000L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(7000L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(7000L)));
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T05:00:00"));
expectedOutput.add(
insertRecord(
"key2",
3L,
3L,
epochMills(UTC_ZONE_ID, "1970-01-01T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T05:00:00")));
expectedOutput.add(
insertRecord(
"key1",
2L,
2L,
epochMills(UTC_ZONE_ID, "1970-01-01T00:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T05:00:00")));
testHarness.endInput();
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(7000L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(7000L)));
testHarness.processElement(insertRecord("key1", 1, fromEpochMillis(7000L)));
testHarness.setProcessingTime(epochMills(shiftTimeZone, "1970-01-01T10:00:01"));
expectedOutput.add(
insertRecord(
"key1",
3L,
3L,
epochMills(UTC_ZONE_ID, "1970-01-01T05:00:00"),
epochMills(UTC_ZONE_ID, "1970-01-01T10:00:00")));
assertThat(getWatermarkLatency(operator)).isEqualTo(Long.valueOf(0L));
ASSERTER.assertOutputEqualsSorted(
"Output was not correct.", expectedOutput, testHarness.getOutput());
testHarness.close();
}
@TestTemplate
void testInvalidWindows() {
final SliceAssigner assigner =
SliceAssigners.hopping(
2, shiftTimeZone, Duration.ofSeconds(3), Duration.ofSeconds(1));
final SlicingSumAndCountAggsFunction aggsFunction =
new SlicingSumAndCountAggsFunction(assigner);
// hopping window without specifying count star index
assertThatThrownBy(() -> buildWindowOperator(assigner, aggsFunction, null))
.hasMessageContaining(
"Hopping window requires a COUNT(*) in the aggregate functions.");
}
/** A test agg function for {@link SlicingWindowAggOperatorTest}. */
protected static | SlicingWindowAggOperatorTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/MultipleParallelOrSequentialCallsTest.java | {
"start": 16926,
"end": 17095
} | class ____ {
public TestClass(String con) {}
private boolean testClass() {
return true;
}
}
}\
""")
.doTest(TestMode.AST_MATCH);
}
}
| TestClass |
java | apache__flink | flink-table/flink-sql-client/src/main/java/org/apache/flink/table/client/cli/CliResultView.java | {
"start": 8172,
"end": 10485
} | class ____ extends Thread {
public volatile boolean isRunning = true;
public volatile boolean cleanUpQuery = true;
public long lastUpdatedResults = System.currentTimeMillis();
@Override
public void run() {
while (isRunning) {
final long interval = REFRESH_INTERVALS.get(refreshInterval).f1;
if (interval >= 0) {
// refresh according to specified interval
if (interval > 0) {
synchronized (RefreshThread.this) {
if (isRunning) {
try {
RefreshThread.this.wait(interval);
} catch (InterruptedException e) {
continue;
}
}
}
}
synchronized (CliResultView.this) {
refresh();
// do the display only every 100 ms (even in fastest mode)
if (System.currentTimeMillis() - lastUpdatedResults > 100) {
if (CliResultView.this.isRunning()) {
display();
}
lastUpdatedResults = System.currentTimeMillis();
}
}
} else {
// keep the thread running but without refreshing
synchronized (RefreshThread.this) {
if (isRunning) {
try {
RefreshThread.this.wait(100);
} catch (InterruptedException e) {
// continue
}
}
}
}
}
// final display
synchronized (CliResultView.this) {
if (CliResultView.this.isRunning()) {
display();
}
}
if (cleanUpQuery) {
// cancel table program
cleanUpQuery();
}
}
}
}
| RefreshThread |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/state/v2/ReducingStateDescriptor.java | {
"start": 1378,
"end": 3638
} | class ____<T> extends StateDescriptor<T> {
private final ReduceFunction<T> reduceFunction;
/**
* Creates a new {@code ReducingStateDescriptor} with the given name and default value.
*
* @param name The (unique) name for the state.
* @param reduceFunction The {@code ReduceFunction} used to aggregate the state.
* @param typeInfo The type of the values in the state.
*/
public ReducingStateDescriptor(
@Nonnull String name,
@Nonnull ReduceFunction<T> reduceFunction,
@Nonnull TypeInformation<T> typeInfo) {
super(name, typeInfo);
this.reduceFunction = checkNotNull(reduceFunction);
}
/**
* Create a new {@code ReducingStateDescriptor} with the given stateId and the given type
* serializer.
*
* @param stateId The (unique) stateId for the state.
* @param serializer The type serializer for the values in the state.
*/
public ReducingStateDescriptor(
@Nonnull String stateId,
@Nonnull ReduceFunction<T> reduceFunction,
@Nonnull TypeSerializer<T> serializer) {
super(stateId, serializer);
this.reduceFunction = checkNotNull(reduceFunction);
}
/**
* Creates a new {@code ReducingStateDescriptor} with the given name, type, and default value.
*
* <p>If this constructor fails (because it is not possible to describe the type via a class),
* consider using the {@link #ReducingStateDescriptor(String, ReduceFunction, TypeInformation)}
* constructor.
*
* @param name The (unique) name for the state.
* @param reduceFunction The {@code ReduceFunction} used to aggregate the state.
* @param typeClass The type of the values in the state.
*/
public ReducingStateDescriptor(
String name, ReduceFunction<T> reduceFunction, Class<T> typeClass) {
super(name, typeClass);
this.reduceFunction = checkNotNull(reduceFunction);
}
/** Returns the reduce function to be used for the reducing state. */
public ReduceFunction<T> getReduceFunction() {
return reduceFunction;
}
@Override
public Type getType() {
return Type.REDUCING;
}
}
| ReducingStateDescriptor |
java | spring-projects__spring-security | test/src/main/java/org/springframework/security/test/web/reactive/server/SecurityMockServerConfigurers.java | {
"start": 26692,
"end": 32425
} | class ____ implements WebTestClientConfigurer, MockServerConfigurer {
private final String nameAttributeKey = "sub";
private ClientRegistration clientRegistration;
private OAuth2AccessToken accessToken;
private Supplier<Collection<GrantedAuthority>> authorities = this::defaultAuthorities;
private Supplier<Map<String, Object>> attributes = this::defaultAttributes;
private Supplier<OAuth2User> oauth2User = this::defaultPrincipal;
private OAuth2LoginMutator(OAuth2AccessToken accessToken) {
this.accessToken = accessToken;
this.clientRegistration = clientRegistrationBuilder().build();
}
/**
* Use the provided authorities in the {@link Authentication}
* @param authorities the authorities to use
* @return the {@link OAuth2LoginMutator} for further configuration
*/
public OAuth2LoginMutator authorities(Collection<GrantedAuthority> authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = () -> authorities;
this.oauth2User = this::defaultPrincipal;
return this;
}
/**
* Use the provided authorities in the {@link Authentication}
* @param authorities the authorities to use
* @return the {@link OAuth2LoginMutator} for further configuration
*/
public OAuth2LoginMutator authorities(GrantedAuthority... authorities) {
Assert.notNull(authorities, "authorities cannot be null");
this.authorities = () -> Arrays.asList(authorities);
this.oauth2User = this::defaultPrincipal;
return this;
}
/**
* Mutate the attributes using the given {@link Consumer}
* @param attributesConsumer The {@link Consumer} for mutating the {@code Map} of
* attributes
* @return the {@link OAuth2LoginMutator} for further configuration
*/
public OAuth2LoginMutator attributes(Consumer<Map<String, Object>> attributesConsumer) {
Assert.notNull(attributesConsumer, "attributesConsumer cannot be null");
this.attributes = () -> {
Map<String, Object> attributes = defaultAttributes();
attributesConsumer.accept(attributes);
return attributes;
};
this.oauth2User = this::defaultPrincipal;
return this;
}
/**
* Use the provided {@link OAuth2User} as the authenticated user.
* @param oauth2User the {@link OAuth2User} to use
* @return the {@link OAuth2LoginMutator} for further configuration
*/
public OAuth2LoginMutator oauth2User(OAuth2User oauth2User) {
this.oauth2User = () -> oauth2User;
return this;
}
/**
* Use the provided {@link ClientRegistration} as the client to authorize.
* <p>
* The supplied {@link ClientRegistration} will be registered into a
* {@link ServerOAuth2AuthorizedClientRepository}.
* @param clientRegistration the {@link ClientRegistration} to use
* @return the {@link OAuth2LoginMutator} for further configuration
*/
public OAuth2LoginMutator clientRegistration(ClientRegistration clientRegistration) {
this.clientRegistration = clientRegistration;
return this;
}
@Override
public void beforeServerCreated(WebHttpHandlerBuilder builder) {
OAuth2AuthenticationToken token = getToken();
mockOAuth2Client().accessToken(this.accessToken)
.clientRegistration(this.clientRegistration)
.principalName(token.getPrincipal().getName())
.beforeServerCreated(builder);
mockAuthentication(token).beforeServerCreated(builder);
}
@Override
public void afterConfigureAdded(WebTestClient.MockServerSpec<?> serverSpec) {
OAuth2AuthenticationToken token = getToken();
mockOAuth2Client().accessToken(this.accessToken)
.clientRegistration(this.clientRegistration)
.principalName(token.getPrincipal().getName())
.afterConfigureAdded(serverSpec);
mockAuthentication(token).afterConfigureAdded(serverSpec);
}
@Override
public void afterConfigurerAdded(WebTestClient.Builder builder,
@Nullable WebHttpHandlerBuilder httpHandlerBuilder, @Nullable ClientHttpConnector connector) {
OAuth2AuthenticationToken token = getToken();
mockOAuth2Client().accessToken(this.accessToken)
.clientRegistration(this.clientRegistration)
.principalName(token.getPrincipal().getName())
.afterConfigurerAdded(builder, httpHandlerBuilder, connector);
mockAuthentication(token).afterConfigurerAdded(builder, httpHandlerBuilder, connector);
}
private OAuth2AuthenticationToken getToken() {
OAuth2User oauth2User = this.oauth2User.get();
return new OAuth2AuthenticationToken(oauth2User, oauth2User.getAuthorities(),
this.clientRegistration.getRegistrationId());
}
private ClientRegistration.Builder clientRegistrationBuilder() {
return ClientRegistration.withRegistrationId("test")
.authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
.redirectUri("https://client.example.com")
.clientId("test-client")
.authorizationUri("https://authorize-uri.example.org")
.tokenUri("https://token-uri.example.org");
}
private Collection<GrantedAuthority> defaultAuthorities() {
Set<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.add(new OAuth2UserAuthority(this.attributes.get(), this.nameAttributeKey));
for (String authority : this.accessToken.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
}
return authorities;
}
private Map<String, Object> defaultAttributes() {
Map<String, Object> attributes = new HashMap<>();
attributes.put(this.nameAttributeKey, "user");
return attributes;
}
private OAuth2User defaultPrincipal() {
return new DefaultOAuth2User(this.authorities.get(), this.attributes.get(), this.nameAttributeKey);
}
}
/**
* @author Josh Cummings
* @since 5.3
*/
public static final | OAuth2LoginMutator |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/mysql/select/MySqlSelectTest_18.java | {
"start": 979,
"end": 2879
} | class ____ extends MysqlTest {
public void test_0() throws Exception {
String sql = "SELECT host.id as id"
+ ", host.item_id as itemId"
+ ", host.node_id as nodeId"
+ ", host.node_type as nodeType"
+ ", host.begin_time as beginTime"
+ ", host.end_time as endTime"
+ ", host.gmt_create as gmtCreate"
+ ", host.gmt_modify as gmtModify"
+ ", host.reason as reason"
+ ", host.creator_id as creatorId"
+ ", host.modifier_id as modifierId"
+ ", user.name as creator"
+ ", user.name as modifier"
+ ", user.nick_name as nickName "
+ " FROM notice_close_node host left join sys_user user on user.id = host.modifier_id";
MySqlStatementParser parser = new MySqlStatementParser(sql);
List<SQLStatement> statementList = parser.parseStatementList();
SQLStatement statemen = statementList.get(0);
// print(statementList);
assertEquals(1, statementList.size());
MySqlSchemaStatVisitor visitor = new MySqlSchemaStatVisitor();
statemen.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(2, visitor.getTables().size());
assertEquals(14, visitor.getColumns().size());
assertEquals(2, visitor.getConditions().size());
assertTrue(visitor.getColumns().contains(new Column("sys_user", "id")));
assertTrue(visitor.getColumns().contains(new Column("notice_close_node", "modifier_id")));
}
}
| MySqlSelectTest_18 |
java | elastic__elasticsearch | libs/x-content/src/test/java/org/elasticsearch/xcontent/ConstructingObjectParserTests.java | {
"start": 11138,
"end": 13119
} | class ____ {
CalledOneTime(String yeah) {
Matcher<String> yeahMatcher = equalTo("!");
if (ctorArgOptional) {
// either(yeahMatcher).or(nullValue) is broken by https://github.com/hamcrest/JavaHamcrest/issues/49
yeahMatcher = anyOf(yeahMatcher, nullValue());
}
assertThat(yeah, yeahMatcher);
}
boolean fooSet = false;
void setFoo(String foo) {
assertFalse(fooSet);
fooSet = true;
}
}
ConstructingObjectParser<CalledOneTime, Void> parser = new ConstructingObjectParser<>(
"one_time_test",
(a) -> new CalledOneTime((String) a[0])
);
parser.declareString(CalledOneTime::setFoo, new ParseField("foo"));
parser.declareString(ctorArgOptional ? optionalConstructorArg() : constructorArg(), new ParseField("yeah"));
// ctor arg first so we can test for the bug we found one time
XContentParser xcontent = createParser(JsonXContent.jsonXContent, "{ \"yeah\": \"!\", \"foo\": \"foo\" }");
CalledOneTime result = parser.apply(xcontent, null);
assertTrue(result.fooSet);
// and ctor arg second just in case
xcontent = createParser(JsonXContent.jsonXContent, "{ \"foo\": \"foo\", \"yeah\": \"!\" }");
result = parser.apply(xcontent, null);
assertTrue(result.fooSet);
if (ctorArgOptional) {
// and without the constructor arg if we've made it optional
xcontent = createParser(JsonXContent.jsonXContent, "{ \"foo\": \"foo\" }");
result = parser.apply(xcontent, null);
}
assertTrue(result.fooSet);
}
public void testIgnoreUnknownFields() throws IOException {
XContentParser parser = createParser(JsonXContent.jsonXContent, """
{ "test" : "foo", "junk" : 2 }""");
| CalledOneTime |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/disposables/DisposableContainer.java | {
"start": 745,
"end": 1559
} | interface ____ {
/**
* Adds a disposable to this container or disposes it if the
* container has been disposed.
* @param d the disposable to add, not null
* @return true if successful, false if this container has been disposed
*/
boolean add(Disposable d);
/**
* Removes and disposes the given disposable if it is part of this
* container.
* @param d the disposable to remove and dispose, not null
* @return true if the operation was successful
*/
boolean remove(Disposable d);
/**
* Removes but does not dispose the given disposable if it is part of this
* container.
* @param d the disposable to remove, not null
* @return true if the operation was successful
*/
boolean delete(Disposable d);
}
| DisposableContainer |
java | quarkusio__quarkus | extensions/spring-data-jpa/deployment/src/test/java/io/quarkus/spring/data/deployment/ModifyingQueryWithFlushAndClearUsingDataSqlTest.java | {
"start": 513,
"end": 3822
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.addAsResource("import_users.sql", "data.sql")
.addClasses(User.class, LoginEvent.class, UserRepository.class))
.withConfigurationResource("application.properties");
@Inject
UserRepository repo;
@BeforeEach
@Transactional
public void setUp() {
final User user = getUser("JOHN");
user.setLoginCounter(0);
repo.save(user);
}
@Test
@Transactional
public void testNoAutoClear() {
getUser("JOHN"); // read user to attach it to entity manager
repo.incrementLoginCounterPlain("JOHN");
final User userAfterIncrement = getUser("JOHN"); // we get the cached entity
// the read doesn't re-read the incremented counter and is therefore equal to the old value
assertThat(userAfterIncrement.getLoginCounter()).isEqualTo(0);
}
@Test
@Transactional
public void testAutoClear() {
getUser("JOHN"); // read user to attach it to entity manager
repo.incrementLoginCounterAutoClear("JOHN");
final User userAfterIncrement = getUser("JOHN");
assertThat(userAfterIncrement.getLoginCounter()).isEqualTo(1);
}
@Test
@Transactional
public void testNoAutoFlush() {
final User user = getUser("JOHN");
createLoginEvent(user);
repo.processLoginEventsPlain();
final User verifyUser = getUser("JOHN");
// processLoginEvents did not see the new login event
final boolean allProcessed = verifyUser.getLoginEvents().stream()
.allMatch(loginEvent -> loginEvent.isProcessed());
assertThat(allProcessed).describedAs("all LoginEvents are marked as processed").isFalse();
}
@Test
@Transactional
public void testAutoFlush() {
final User user = getUser("JOHN");
createLoginEvent(user);
repo.processLoginEventsPlainAutoClearAndFlush();
final User verifyUser = getUser("JOHN");
final boolean allProcessed = verifyUser.getLoginEvents().stream()
.allMatch(loginEvent -> loginEvent.isProcessed());
assertThat(allProcessed).describedAs("all LoginEvents are marked as processed").isTrue();
}
@Test
@Transactional
public void testNamedQueryOnEntities() {
User user = repo.getUserByFullNameUsingNamedQuery("John Doe");
assertThat(user).isNotNull();
}
@Test
@Transactional
public void testNamedQueriesOnEntities() {
User user = repo.getUserByFullNameUsingNamedQueries("John Doe");
assertThat(user).isNotNull();
}
private LoginEvent createLoginEvent(User user) {
final LoginEvent loginEvent = new LoginEvent();
loginEvent.setUser(user);
loginEvent.setZonedDateTime(ZonedDateTime.now());
user.addEvent(loginEvent);
return loginEvent;
}
private User getUser(String userId) {
final Optional<User> user = repo.findById(userId);
assertThat(user).describedAs("user <%s>", userId).isPresent();
return user.get();
}
}
| ModifyingQueryWithFlushAndClearUsingDataSqlTest |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/JavaInstantGetSecondsGetNanoTest.java | {
"start": 1910,
"end": 2412
} | class ____ {
public static int foo(Instant instant) {
// BUG: Diagnostic contains: JavaInstantGetSecondsGetNano
return instant.getNano();
}
}
""")
.doTest();
}
@Test
public void getSecondsWithGetNanosInReturnType2() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"""
package test;
import com.google.common.collect.ImmutableMap;
import java.time.Instant;
public | TestCase |
java | apache__spark | sql/catalyst/src/main/java/org/apache/spark/sql/connector/read/streaming/SupportsRealTimeRead.java | {
"start": 1218,
"end": 1657
} | class ____ represent the status of a record to be read as the return type of nextWithTimeout.
* It contains whether the next record is available and the ingestion time of the record
* if the source connector provided relevant info. A list of source connector that has ingestion
* time is listed below:
* - Kafka when the record timestamp type is LogAppendTime
* - Kinesis has ApproximateArrivalTimestamp
*/
| to |
java | elastic__elasticsearch | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/action/TransportMlInfoActionTests.java | {
"start": 684,
"end": 1501
} | class ____ extends ESTestCase {
public void testAreMlNodesBiggestSize() {
boolean expectedResult = randomBoolean();
long mlNodeSize = randomLongBetween(10000000L, 10000000000L);
long biggestSize = expectedResult ? mlNodeSize : mlNodeSize * randomLongBetween(2, 5);
int numMlNodes = randomIntBetween(2, 4);
var nodes = Stream.generate(
() -> DiscoveryNodeUtils.builder("node")
.roles(Set.of(DiscoveryNodeRole.ML_ROLE))
.attributes(Map.of(MachineLearning.MACHINE_MEMORY_NODE_ATTR, Long.toString(mlNodeSize)))
.build()
).limit(numMlNodes).toList();
assertThat(TransportMlInfoAction.areMlNodesBiggestSize(ByteSizeValue.ofBytes(biggestSize), nodes), is(expectedResult));
}
}
| TransportMlInfoActionTests |
java | mockito__mockito | mockito-core/src/test/java/org/mockitousage/annotation/CaptorAnnotationTest.java | {
"start": 1948,
"end": 2240
} | class ____ {
@Captor List<?> wrongType;
}
@Test
public void shouldScreamWhenWrongTypeForCaptor() {
try {
MockitoAnnotations.openMocks(new WrongType());
fail();
} catch (MockitoException e) {
}
}
public static | WrongType |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/joincolumn/CharArrayToStringJoinColumnTest.java | {
"start": 3160,
"end": 3858
} | class ____ implements Serializable {
@Id
private Long id;
@Column(name = "string_col", nullable = false)
private String stringProp;
@OneToMany(mappedBy = "vehicle")
private List<VehicleInvoice> invoices;
public Vehicle() {
this.invoices = new ArrayList<>();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getStringProp() {
return stringProp;
}
public void setStringProp(String stringProp) {
this.stringProp = stringProp;
}
public List<VehicleInvoice> getInvoices() {
return invoices;
}
public void setInvoices(List<VehicleInvoice> invoices) {
this.invoices = invoices;
}
}
}
| Vehicle |
java | spring-projects__spring-boot | module/spring-boot-data-redis/src/test/java/org/springframework/boot/data/redis/autoconfigure/DataRedisAutoConfigurationTests.java | {
"start": 38939,
"end": 39526
} | class ____ {
@Bean
DataRedisConnectionDetails redisConnectionDetails() {
return new DataRedisConnectionDetails() {
@Override
public String getUsername() {
return "user-1";
}
@Override
public String getPassword() {
return "password-1";
}
@Override
public MasterReplica getMasterReplica() {
return new MasterReplica() {
@Override
public List<Node> getNodes() {
return List.of(new Node("node-1", 12345), new Node("node-2", 23456));
}
};
}
};
}
}
}
| ConnectionDetailsMasterReplicaConfiguration |
java | micronaut-projects__micronaut-core | http/src/main/java/io/micronaut/http/bind/binders/PathVariableAnnotationBinder.java | {
"start": 1452,
"end": 3982
} | class ____<T> extends AbstractArgumentBinder<T> implements AnnotatedRequestArgumentBinder<PathVariable, T> {
/**
* @param conversionService The conversion service
*/
public PathVariableAnnotationBinder(ConversionService conversionService) {
super(conversionService);
}
/**
* @param conversionService The conversion service
* @param argument The argument
*/
public PathVariableAnnotationBinder(ConversionService conversionService, Argument<T> argument) {
super(conversionService, argument);
}
@Override
public Class<PathVariable> getAnnotationType() {
return PathVariable.class;
}
@Override
public BindingResult<T> bind(ArgumentConversionContext<T> context, HttpRequest<?> source) {
ConvertibleMultiValues<String> parameters = source.getParameters();
Argument<T> argument = context.getArgument();
// If we need to bind all request params to command object
// checks if the variable is defined with modifier char *
// e.g. ?pojo*
final UriMatchInfo matchInfo = BasicHttpAttributes.getRouteMatchInfo(source).orElseThrow();
boolean bindAll = getBindAll(matchInfo, resolvedParameterName(argument));
final ConvertibleValues<Object> variableValues = ConvertibleValues.of(matchInfo.getVariableValues(), conversionService);
if (bindAll) {
Object value;
// Only maps and POJOs will "bindAll", lists work like normal
if (Iterable.class.isAssignableFrom(argument.getType())) {
value = doResolve(context, variableValues);
if (value == null) {
value = Collections.emptyList();
}
} else {
value = parameters.asMap();
}
return doConvert(value, context);
}
return doBind(context, variableValues, BindingResult.unsatisfied());
}
@Override
protected String getParameterName(Argument<T> argument) {
AnnotationMetadata annotationMetadata = argument.getAnnotationMetadata();
return annotationMetadata.stringValue(PathVariable.class).orElse(argument.getName());
}
private Boolean getBindAll(UriMatchInfo matchInfo, String parameterName) {
for (UriMatchVariable v : matchInfo.getVariables()) {
if (v.getName().equals(parameterName)) {
return v.isExploded();
}
}
return false;
}
}
| PathVariableAnnotationBinder |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/util/Transform.java | {
"start": 959,
"end": 6807
} | class ____ {
private static final String CDATA_START = "<![CDATA[";
private static final String CDATA_END = "]]>";
private static final String CDATA_PSEUDO_END = "]]>";
private static final String CDATA_EMBEDED_END = CDATA_END + CDATA_PSEUDO_END + CDATA_START;
private static final int CDATA_END_LEN = CDATA_END.length();
private Transform() {}
/**
* This method takes a string which may contain HTML tags (ie,
* <b>, <table>, etc) and replaces any
* '<', '>' , '&' or '"'
* characters with respective predefined entity references.
*
* @param input The text to be converted.
* @return The input string with the special characters replaced.
*/
public static String escapeHtmlTags(final String input) {
// Check if the string is null, zero length or devoid of special characters
// if so, return what was sent in.
if (Strings.isEmpty(input)
|| (input.indexOf('"') == -1
&& input.indexOf('&') == -1
&& input.indexOf('<') == -1
&& input.indexOf('>') == -1)) {
return input;
}
// Use a StringBuilder in lieu of String concatenation -- it is
// much more efficient this way.
final StringBuilder buf = new StringBuilder(input.length() + 6);
final int len = input.length();
for (int i = 0; i < len; i++) {
final char ch = input.charAt(i);
if (ch > '>') {
buf.append(ch);
} else
switch (ch) {
case '<':
buf.append("<");
break;
case '>':
buf.append(">");
break;
case '&':
buf.append("&");
break;
case '"':
buf.append(""");
break;
default:
buf.append(ch);
break;
}
}
return buf.toString();
}
/**
* Ensures that embedded CDEnd strings (]]>) are handled properly
* within message, NDC and throwable tag text.
*
* @param buf StringBuilder holding the XML data to this point. The
* initial CDStart (<![CDATA[) and final CDEnd (]]>) of the CDATA
* section are the responsibility of the calling method.
* @param str The String that is inserted into an existing CDATA Section within buf.
*/
public static void appendEscapingCData(final StringBuilder buf, final String str) {
if (str != null) {
int end = str.indexOf(CDATA_END);
if (end < 0) {
buf.append(str);
} else {
int start = 0;
while (end > -1) {
buf.append(str.substring(start, end));
buf.append(CDATA_EMBEDED_END);
start = end + CDATA_END_LEN;
if (start < str.length()) {
end = str.indexOf(CDATA_END, start);
} else {
return;
}
}
buf.append(str.substring(start));
}
}
}
/**
* This method takes a string which may contain JSON reserved chars and
* escapes them.
*
* @param input The text to be converted.
* @return The input string with the special characters replaced.
*/
public static String escapeJsonControlCharacters(final String input) {
// Check if the string is null, zero length or devoid of special characters
// if so, return what was sent in.
// TODO: escaped Unicode chars.
if (Strings.isEmpty(input)
|| (input.indexOf('"') == -1
&& input.indexOf('\\') == -1
&& input.indexOf('/') == -1
&& input.indexOf('\b') == -1
&& input.indexOf('\f') == -1
&& input.indexOf('\n') == -1
&& input.indexOf('\r') == -1
&& input.indexOf('\t') == -1)) {
return input;
}
final StringBuilder buf = new StringBuilder(input.length() + 6);
final int len = input.length();
for (int i = 0; i < len; i++) {
final char ch = input.charAt(i);
final String escBs = "\\";
switch (ch) {
case '"':
buf.append(escBs);
buf.append(ch);
break;
case '\\':
buf.append(escBs);
buf.append(ch);
break;
case '/':
buf.append(escBs);
buf.append(ch);
break;
case '\b':
buf.append(escBs);
buf.append('b');
break;
case '\f':
buf.append(escBs);
buf.append('f');
break;
case '\n':
buf.append(escBs);
buf.append('n');
break;
case '\r':
buf.append(escBs);
buf.append('r');
break;
case '\t':
buf.append(escBs);
buf.append('t');
break;
default:
buf.append(ch);
}
}
return buf.toString();
}
}
| Transform |
java | apache__flink | flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/AsyncCorrelateCodeGenerator.java | {
"start": 1597,
"end": 3529
} | class ____ {
public static GeneratedFunction<AsyncFunction<RowData, Object>> generateFunction(
String name,
RowType inputType,
RowType returnType,
RexCall invocation,
ReadableConfig tableConfig,
ClassLoader classLoader) {
CodeGeneratorContext ctx = new CodeGeneratorContext(tableConfig, classLoader);
String processCode =
generateProcessCode(ctx, inputType, invocation, CodeGenUtils.DEFAULT_INPUT1_TERM());
return FunctionCodeGenerator.generateFunction(
ctx,
name,
getFunctionClass(),
processCode,
returnType,
inputType,
CodeGenUtils.DEFAULT_INPUT1_TERM(),
JavaScalaConversionUtil.toScala(Optional.empty()),
JavaScalaConversionUtil.toScala(Optional.empty()),
CodeGenUtils.DEFAULT_COLLECTOR_TERM(),
CodeGenUtils.DEFAULT_CONTEXT_TERM());
}
@SuppressWarnings("unchecked")
private static Class<AsyncFunction<RowData, Object>> getFunctionClass() {
return (Class<AsyncFunction<RowData, Object>>) (Object) AsyncFunction.class;
}
private static String generateProcessCode(
CodeGeneratorContext ctx, RowType inputType, RexCall invocation, String inputTerm) {
invocation.accept(new AsyncCorrelateFunctionsValidator());
ExprCodeGenerator exprGenerator =
new ExprCodeGenerator(ctx, false)
.bindInput(
inputType,
inputTerm,
JavaScalaConversionUtil.toScala(Optional.empty()));
GeneratedExpression invocationExprs = exprGenerator.generateExpression(invocation);
return invocationExprs.code();
}
private static | AsyncCorrelateCodeGenerator |
java | spring-projects__spring-security | oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/authentication/BearerTokenAuthenticationFilterTests.java | {
"start": 4265,
"end": 21343
} | class ____ {
@Mock
AuthenticationEntryPoint authenticationEntryPoint;
@Mock
AuthenticationFailureHandler authenticationFailureHandler;
@Mock
AuthenticationManager authenticationManager;
@Mock
AuthenticationManagerResolver<HttpServletRequest> authenticationManagerResolver;
@Mock
BearerTokenResolver bearerTokenResolver;
@Mock
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource;
MockHttpServletRequest request;
MockHttpServletResponse response;
MockFilterChain filterChain;
@BeforeEach
public void httpMocks() {
this.request = new MockHttpServletRequest();
this.response = new MockHttpServletResponse();
this.filterChain = new MockFilterChain();
}
@Test
public void doFilterWhenBearerTokenPresentThenAuthenticates() throws ServletException, IOException {
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
ArgumentCaptor<BearerTokenAuthenticationToken> captor = ArgumentCaptor
.forClass(BearerTokenAuthenticationToken.class);
verify(this.authenticationManager).authenticate(captor.capture());
assertThat(captor.getValue().getPrincipal()).isEqualTo("token");
assertThat(this.request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
}
@Test
public void doFilterWhenSecurityContextRepositoryThenSaves() throws ServletException, IOException {
SecurityContextRepository securityContextRepository = mock(SecurityContextRepository.class);
String token = "token";
given(this.bearerTokenResolver.resolve(this.request)).willReturn(token);
TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("test", "password");
given(this.authenticationManager.authenticate(any())).willReturn(expectedAuthentication);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.setSecurityContextRepository(securityContextRepository);
filter.doFilter(this.request, this.response, this.filterChain);
ArgumentCaptor<BearerTokenAuthenticationToken> captor = ArgumentCaptor
.forClass(BearerTokenAuthenticationToken.class);
verify(this.authenticationManager).authenticate(captor.capture());
assertThat(captor.getValue().getPrincipal()).isEqualTo(token);
ArgumentCaptor<SecurityContext> contextArg = ArgumentCaptor.forClass(SecurityContext.class);
verify(securityContextRepository).saveContext(contextArg.capture(), eq(this.request), eq(this.response));
assertThat(contextArg.getValue().getAuthentication().getName()).isEqualTo(expectedAuthentication.getName());
}
@Test
public void doFilterWhenUsingAuthenticationManagerResolverThenAuthenticates() throws Exception {
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManagerResolver));
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManagerResolver.resolve(any())).willReturn(this.authenticationManager);
TestingAuthenticationToken expectedAuthentication = new TestingAuthenticationToken("test", "password");
given(this.authenticationManager.authenticate(any())).willReturn(expectedAuthentication);
filter.doFilter(this.request, this.response, this.filterChain);
ArgumentCaptor<BearerTokenAuthenticationToken> captor = ArgumentCaptor
.forClass(BearerTokenAuthenticationToken.class);
verify(this.authenticationManager).authenticate(captor.capture());
assertThat(captor.getValue().getPrincipal()).isEqualTo("token");
assertThat(this.request.getAttribute(RequestAttributeSecurityContextRepository.DEFAULT_REQUEST_ATTR_NAME))
.isNotNull();
}
@Test
public void doFilterWhenNoBearerTokenPresentThenDoesNotAuthenticate() throws ServletException, IOException {
given(this.bearerTokenResolver.resolve(this.request)).willReturn(null);
dontAuthenticate();
}
@Test
public void doFilterWhenMalformedBearerTokenThenPropagatesError() throws ServletException, IOException {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_REQUEST, HttpStatus.BAD_REQUEST,
"description", "uri");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
given(this.bearerTokenResolver.resolve(this.request)).willThrow(exception);
dontAuthenticate();
verify(this.authenticationEntryPoint).commence(this.request, this.response, exception);
}
@Test
public void doFilterWhenAuthenticationFailsWithDefaultHandlerThenPropagatesError()
throws ServletException, IOException {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED,
"description", "uri");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).willThrow(exception);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
verify(this.authenticationEntryPoint).commence(this.request, this.response, exception);
}
@Test
public void doFilterWhenAuthenticationFailsWithCustomHandlerThenPropagatesError()
throws ServletException, IOException {
BearerTokenError error = new BearerTokenError(BearerTokenErrorCodes.INVALID_TOKEN, HttpStatus.UNAUTHORIZED,
"description", "uri");
OAuth2AuthenticationException exception = new OAuth2AuthenticationException(error);
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class))).willThrow(exception);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.setAuthenticationFailureHandler(this.authenticationFailureHandler);
filter.doFilter(this.request, this.response, this.filterChain);
verify(this.authenticationFailureHandler).onAuthenticationFailure(this.request, this.response, exception);
}
@Test
public void doFilterWhenAuthenticationServiceExceptionThenRethrows() {
AuthenticationServiceException exception = new AuthenticationServiceException("message");
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any())).willThrow(exception);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
assertThatExceptionOfType(AuthenticationServiceException.class)
.isThrownBy(() -> filter.doFilter(this.request, this.response, this.filterChain));
}
@Test
public void doFilterWhenCustomEntryPointAndAuthenticationErrorThenUses() throws ServletException, IOException {
AuthenticationException exception = new InvalidBearerTokenException("message");
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any())).willThrow(exception);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
AuthenticationEntryPoint entrypoint = mock(AuthenticationEntryPoint.class);
filter.setAuthenticationEntryPoint(entrypoint);
filter.doFilter(this.request, this.response, this.filterChain);
verify(entrypoint).commence(any(), any(), any(InvalidBearerTokenException.class));
}
@Test
public void doFilterWhenCustomAuthenticationDetailsSourceThenUses() throws ServletException, IOException {
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
verify(this.authenticationDetailsSource).buildDetails(this.request);
}
@Test
public void doFilterWhenCustomSecurityContextHolderStrategyThenUses() throws ServletException, IOException {
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
SecurityContextHolderStrategy strategy = mock(SecurityContextHolderStrategy.class);
given(strategy.createEmptyContext()).willReturn(new SecurityContextImpl());
given(strategy.getContext()).willReturn(new SecurityContextImpl());
filter.setSecurityContextHolderStrategy(strategy);
filter.doFilter(this.request, this.response, this.filterChain);
verify(strategy).setContext(any());
}
@Test
public void doFilterWhenDPoPBoundTokenDowngradedThenPropagatesError() throws ServletException, IOException {
Jwt jwt = TestJwts.jwt().claim("cnf", Collections.singletonMap("jkt", "jwk-thumbprint")).build();
JwtAuthenticationToken authenticationResult = new JwtAuthenticationToken(jwt);
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any(BearerTokenAuthenticationToken.class)))
.willReturn(authenticationResult);
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.setAuthenticationFailureHandler(this.authenticationFailureHandler);
filter.doFilter(this.request, this.response, this.filterChain);
ArgumentCaptor<OAuth2AuthenticationException> exceptionCaptor = ArgumentCaptor
.forClass(OAuth2AuthenticationException.class);
verify(this.authenticationFailureHandler).onAuthenticationFailure(any(), any(), exceptionCaptor.capture());
OAuth2Error error = exceptionCaptor.getValue().getError();
assertThat(error.getErrorCode()).isEqualTo(BearerTokenErrorCodes.INVALID_TOKEN);
assertThat(error.getDescription()).isEqualTo("Invalid bearer token");
}
@Test
public void doFilterWhenSetAuthenticationConverterAndAuthenticationDetailsSourceThenIllegalArgument(
@Mock AuthenticationConverter authenticationConverter) {
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(this.authenticationManager,
authenticationConverter);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> filter.setAuthenticationDetailsSource(this.authenticationDetailsSource));
}
@Test
public void doFilterWhenSetBearerTokenResolverAndAuthenticationConverterThenIllegalArgument(
@Mock AuthenticationConverter authenticationConverter) {
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(this.authenticationManager,
authenticationConverter);
assertThatExceptionOfType(IllegalArgumentException.class)
.isThrownBy(() -> filter.setBearerTokenResolver(this.bearerTokenResolver));
}
/**
* This is critical to avoid adding duplicate GrantedAuthority instances with the same
* authority when the issuedAt is too old and a new instance is requested.
* @throws Exception
*/
@Test
void doFilterWhenDefaultEqualsGrantedAuthorityThenNoDuplicates() throws Exception {
TestingAuthenticationToken existingAuthn = new TestingAuthenticationToken("username", "password",
new DefaultEqualsGrantedAuthority());
SecurityContextHolder.setContext(new SecurityContextImpl(existingAuthn));
given(this.authenticationManager.authenticate(any()))
.willReturn(new TestingAuthenticationToken("username", "password", new DefaultEqualsGrantedAuthority()));
given(this.bearerTokenResolver.resolve(any())).willReturn("token");
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// @formatter:off
SecurityAssertions.assertThat(authentication).authorities()
.extracting(GrantedAuthority::getAuthority)
.containsExactly(DefaultEqualsGrantedAuthority.AUTHORITY);
// @formatter:on
}
@Test
void doFilterWhenNonBuildableAuthenticationSubclassThenSkipsToBuilder() throws Exception {
TestingAuthenticationToken existingAuthn = new TestingAuthenticationToken("username", "password", "FACTORONE");
SecurityContextHolder.setContext(new SecurityContextImpl(existingAuthn));
given(this.authenticationManager.authenticate(any()))
.willReturn(new NonBuildableAuthenticationToken("username", "password", "FACTORTWO"));
given(this.bearerTokenResolver.resolve(any())).willReturn("token");
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
// @formatter:off
SecurityAssertions.assertThat(authentication).authorities()
.extracting(GrantedAuthority::getAuthority)
.containsExactly("FACTORTWO");
// @formatter:on
}
@Test
public void setAuthenticationEntryPointWhenNullThenThrowsException() {
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(this.authenticationManager);
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> filter.setAuthenticationEntryPoint(null))
.withMessageContaining("authenticationEntryPoint cannot be null");
// @formatter:on
}
@Test
public void setBearerTokenResolverWhenNullThenThrowsException() {
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(this.authenticationManager);
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> filter.setBearerTokenResolver(null))
.withMessageContaining("bearerTokenResolver cannot be null");
// @formatter:on
}
@Test
public void setAuthenticationConverterWhenNullThenThrowsException() {
// @formatter:off
BearerTokenAuthenticationFilter filter = new BearerTokenAuthenticationFilter(this.authenticationManager);
assertThatIllegalArgumentException()
.isThrownBy(() -> filter.setAuthenticationDetailsSource(null))
.withMessageContaining("authenticationDetailsSource cannot be null");
// @formatter:on
}
@Test
public void setConverterWhenNullThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenAuthenticationFilter(this.authenticationManager, null))
.withMessageContaining("authenticationConverter cannot be null");
// @formatter:on
}
@Test
public void constructorWhenNullAuthenticationManagerThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenAuthenticationFilter((AuthenticationManager) null))
.withMessageContaining("authenticationManager cannot be null");
// @formatter:on
}
@Test
public void constructorWhenNullAuthenticationManagerResolverThenThrowsException() {
// @formatter:off
assertThatIllegalArgumentException()
.isThrownBy(() -> new BearerTokenAuthenticationFilter((AuthenticationManagerResolver<HttpServletRequest>) null))
.withMessageContaining("authenticationManagerResolver cannot be null");
// @formatter:on
}
@Test
void authenticateWhenPreviousAuthenticationThenApplies() throws Exception {
Authentication first = new TestingAuthenticationToken("user", "pass", "FACTOR_ONE");
Authentication second = new TestingAuthenticationToken("user", "pass", "FACTOR_TWO");
Filter filter = addMocks(new BearerTokenAuthenticationFilter(this.authenticationManager));
given(this.bearerTokenResolver.resolve(this.request)).willReturn("token");
given(this.authenticationManager.authenticate(any())).willReturn(second);
SecurityContextHolder.getContext().setAuthentication(first);
filter.doFilter(this.request, this.response, this.filterChain);
Authentication result = SecurityContextHolder.getContext().getAuthentication();
SecurityContextHolder.clearContext();
Set<String> authorities = AuthorityUtils.authorityListToSet(result.getAuthorities());
assertThat(authorities).containsExactlyInAnyOrder("FACTOR_ONE", "FACTOR_TWO");
}
private BearerTokenAuthenticationFilter addMocks(BearerTokenAuthenticationFilter filter) {
filter.setAuthenticationEntryPoint(this.authenticationEntryPoint);
filter.setBearerTokenResolver(this.bearerTokenResolver);
filter.setAuthenticationDetailsSource(this.authenticationDetailsSource);
return filter;
}
private void dontAuthenticate() throws ServletException, IOException {
BearerTokenAuthenticationFilter filter = addMocks(
new BearerTokenAuthenticationFilter(this.authenticationManager));
filter.doFilter(this.request, this.response, this.filterChain);
verifyNoMoreInteractions(this.authenticationManager);
}
static final | BearerTokenAuthenticationFilterTests |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DJLEndpointBuilderFactory.java | {
"start": 4205,
"end": 6676
} | interface ____
extends
EndpointProducerBuilder {
default DJLEndpointBuilder basic() {
return (DJLEndpointBuilder) this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedDJLEndpointBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedDJLEndpointBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
}
public | AdvancedDJLEndpointBuilder |
java | apache__flink | flink-metrics/flink-metrics-core/src/main/java/org/apache/flink/metrics/LogicalScopeProvider.java | {
"start": 970,
"end": 1222
} | interface ____ *not* meant for the long-term; it merely removes the need for
* reporters to depend on flink-runtime in order to access the logical scope. Once the logical scope
* is properly exposed this interface *will* be removed.
*/
@Public
public | is |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-client-jackson/deployment/src/test/java/io/quarkus/rest/client/reactive/jackson/test/BadRequestNotPropagatedTestCase.java | {
"start": 2805,
"end": 2895
} | class ____ {
String name;
}
@Path("/bad-server")
public static | JsonObject |
java | assertj__assertj-core | assertj-core/src/test/java/org/assertj/core/error/ShouldEndWithPath_create_Test.java | {
"start": 1028,
"end": 1489
} | class ____ {
@Test
void should_create_error_message() {
// GIVEN
final Path actual = mock(Path.class);
final Path other = mock(Path.class);
// WHEN
String actualMessage = shouldEndWith(actual, other).create(new TestDescription("Test"), STANDARD_REPRESENTATION);
// THEN
then(actualMessage).isEqualTo("[Test] %nExpected path:%n %s%nto end with:%n %s%nbut it did not.".formatted(actual, other));
}
}
| ShouldEndWithPath_create_Test |
java | spring-projects__spring-framework | spring-core/src/main/java24/org/springframework/core/type/classreading/ClassFileClassMetadata.java | {
"start": 6392,
"end": 6462
} | class ____
}
}
});
return builder.build();
}
static | element |
java | redisson__redisson | redisson/src/main/java/org/redisson/rx/RedissonBlockingQueueRx.java | {
"start": 839,
"end": 1215
} | class ____<V> extends RedissonListRx<V> {
private final RBlockingQueueAsync<V> queue;
public RedissonBlockingQueueRx(RBlockingQueueAsync<V> queue) {
super((BaseRedissonList<V>) queue);
this.queue = queue;
}
public Flowable<V> takeElements() {
return ElementsStream.takeElements(queue::takeAsync);
}
}
| RedissonBlockingQueueRx |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-common/src/main/java/org/apache/hadoop/yarn/server/api/protocolrecords/LogAggregationReport.java | {
"start": 1518,
"end": 2868
} | class ____ {
@Public
@Unstable
public static LogAggregationReport newInstance(ApplicationId appId,
LogAggregationStatus status, String diagnosticMessage) {
LogAggregationReport report = Records.newRecord(LogAggregationReport.class);
report.setApplicationId(appId);
report.setLogAggregationStatus(status);
report.setDiagnosticMessage(diagnosticMessage);
return report;
}
/**
* Get the <code>ApplicationId</code> of the application.
* @return <code>ApplicationId</code> of the application
*/
@Public
@Unstable
public abstract ApplicationId getApplicationId();
@Public
@Unstable
public abstract void setApplicationId(ApplicationId appId);
/**
* Get the <code>LogAggregationStatus</code>.
* @return <code>LogAggregationStatus</code>
*/
@Public
@Unstable
public abstract LogAggregationStatus getLogAggregationStatus();
@Public
@Unstable
public abstract void setLogAggregationStatus(
LogAggregationStatus logAggregationStatus);
/**
* Get the <em>diagnositic information</em> of this log aggregation
* @return <em>diagnositic information</em> of this log aggregation
*/
@Public
@Unstable
public abstract String getDiagnosticMessage();
@Public
@Unstable
public abstract void setDiagnosticMessage(String diagnosticMessage);
}
| LogAggregationReport |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/script/field/SortedSetDocValuesStringFieldScriptTests.java | {
"start": 1198,
"end": 2460
} | class ____ extends ESTestCase {
public void testValuesLimitIsNotEnforced() throws IOException {
try (Directory directory = newDirectory(); RandomIndexWriter iw = new RandomIndexWriter(random(), directory)) {
FieldType fieldType = new FieldType();
fieldType.setDocValuesType(DocValuesType.BINARY);
List<IndexableField> fields = new ArrayList<>();
int numValues = AbstractFieldScript.MAX_VALUES + randomIntBetween(1, 100);
for (int i = 0; i < numValues; i++) {
fields.add(new SortedSetDocValuesField("test", new BytesRef("term" + i)));
}
iw.addDocument(fields);
try (DirectoryReader reader = iw.getReader()) {
SortedSetDocValuesStringFieldScript docValues = new SortedSetDocValuesStringFieldScript(
"test",
new SearchLookup(field -> null, (ft, lookup, ftd) -> null, (ctx, doc) -> null),
reader.leaves().get(0)
);
List<String> values = new ArrayList<>();
docValues.runForDoc(0, values::add);
assertEquals(numValues, values.size());
}
}
}
}
| SortedSetDocValuesStringFieldScriptTests |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/flogger/FloggerRequiredModifiersTest.java | {
"start": 2997,
"end": 3292
} | class ____ {
void doIt() {
FluentLogger.forEnclosingClass().atInfo().log();
}
}
""")
.addOutputLines(
"out/Test.java",
"""
import com.google.common.flogger.FluentLogger;
| Test |
java | elastic__elasticsearch | x-pack/plugin/inference/qa/mixed-cluster/src/javaRestTest/java/org/elasticsearch/xpack/inference/qa/mixed/CohereServiceMixedIT.java | {
"start": 1075,
"end": 10996
} | class ____ extends BaseMixedTestCase {
private static final String COHERE_EMBEDDINGS_ADDED = "8.13.0";
private static final String COHERE_RERANK_ADDED = "8.14.0";
private static final String COHERE_EMBEDDINGS_CHUNKING_SETTINGS_ADDED = "8.16.0";
private static final String BYTE_ALIAS_FOR_INT8_ADDED = "8.14.0";
private static final String MINIMUM_SUPPORTED_VERSION = "8.15.0";
private static MockWebServer cohereEmbeddingsServer;
private static MockWebServer cohereRerankServer;
@BeforeClass
public static void startWebServer() throws IOException {
cohereEmbeddingsServer = new MockWebServer();
cohereEmbeddingsServer.start();
cohereRerankServer = new MockWebServer();
cohereRerankServer.start();
}
@AfterClass
public static void shutdown() {
cohereEmbeddingsServer.close();
cohereRerankServer.close();
}
@SuppressWarnings("unchecked")
public void testCohereEmbeddings() throws IOException {
var embeddingsSupported = bwcVersion.onOrAfter(Version.fromString(COHERE_EMBEDDINGS_ADDED));
assumeTrue("Cohere embedding service added in " + COHERE_EMBEDDINGS_ADDED, embeddingsSupported);
assumeTrue(
"Cohere service requires at least " + MINIMUM_SUPPORTED_VERSION,
bwcVersion.onOrAfter(Version.fromString(MINIMUM_SUPPORTED_VERSION))
);
final String inferenceIdInt8 = "mixed-cluster-cohere-embeddings-int8";
final String inferenceIdFloat = "mixed-cluster-cohere-embeddings-float";
try {
// queue a response as PUT will call the service
cohereEmbeddingsServer.enqueue(new MockResponse().setResponseCode(200).setBody(embeddingResponseByte()));
put(inferenceIdInt8, embeddingConfigInt8(getUrl(cohereEmbeddingsServer)), TaskType.TEXT_EMBEDDING);
// float model
cohereEmbeddingsServer.enqueue(new MockResponse().setResponseCode(200).setBody(embeddingResponseFloat()));
put(inferenceIdFloat, embeddingConfigFloat(getUrl(cohereEmbeddingsServer)), TaskType.TEXT_EMBEDDING);
} catch (Exception e) {
if (bwcVersion.before(Version.fromString(COHERE_EMBEDDINGS_CHUNKING_SETTINGS_ADDED))) {
// Chunking settings were added in 8.16.0. if the version is before that, an exception will be thrown if the index mapping
// was created based on a mapping from an old node
assertThat(
e.getMessage(),
containsString(
"One or more nodes in your cluster does not support chunking_settings. "
+ "Please update all nodes in your cluster to the latest version to use chunking_settings."
)
);
return;
}
}
var configs = (List<Map<String, Object>>) get(TaskType.TEXT_EMBEDDING, inferenceIdInt8).get("endpoints");
assertEquals("cohere", configs.get(0).get("service"));
var serviceSettings = (Map<String, Object>) configs.get(0).get("service_settings");
assertThat(serviceSettings, hasEntry("model_id", "embed-english-light-v3.0"));
var embeddingType = serviceSettings.get("embedding_type");
// An upgraded node will report the embedding type as byte, an old node int8
assertThat(embeddingType, Matchers.is(oneOf("int8", "byte")));
configs = (List<Map<String, Object>>) get(TaskType.TEXT_EMBEDDING, inferenceIdFloat).get("endpoints");
serviceSettings = (Map<String, Object>) configs.get(0).get("service_settings");
assertThat(serviceSettings, hasEntry("embedding_type", "float"));
assertEmbeddingInference(inferenceIdInt8, CohereEmbeddingType.BYTE);
assertEmbeddingInference(inferenceIdFloat, CohereEmbeddingType.FLOAT);
delete(inferenceIdFloat);
delete(inferenceIdInt8);
}
void assertEmbeddingInference(String inferenceId, CohereEmbeddingType type) throws IOException {
switch (type) {
case INT8:
case BYTE:
cohereEmbeddingsServer.enqueue(new MockResponse().setResponseCode(200).setBody(embeddingResponseByte()));
break;
case FLOAT:
cohereEmbeddingsServer.enqueue(new MockResponse().setResponseCode(200).setBody(embeddingResponseFloat()));
}
var inferenceMap = inference(inferenceId, TaskType.TEXT_EMBEDDING, "some text");
assertThat(inferenceMap.entrySet(), not(empty()));
}
@SuppressWarnings("unchecked")
public void testRerank() throws IOException {
var rerankSupported = bwcVersion.onOrAfter(Version.fromString(COHERE_RERANK_ADDED));
assumeTrue("Cohere rerank service added in " + COHERE_RERANK_ADDED, rerankSupported);
assumeTrue(
"Cohere service requires at least " + MINIMUM_SUPPORTED_VERSION,
bwcVersion.onOrAfter(Version.fromString(MINIMUM_SUPPORTED_VERSION))
);
final String inferenceId = "mixed-cluster-rerank";
cohereRerankServer.enqueue(new MockResponse().setResponseCode(200).setBody(rerankResponse()));
put(inferenceId, rerankConfig(getUrl(cohereRerankServer)), TaskType.RERANK);
assertRerank(inferenceId);
var configs = (List<Map<String, Object>>) get(TaskType.RERANK, inferenceId).get("endpoints");
assertThat(configs, hasSize(1));
assertEquals("cohere", configs.get(0).get("service"));
var serviceSettings = (Map<String, Object>) configs.get(0).get("service_settings");
assertThat(serviceSettings, hasEntry("model_id", "rerank-english-v3.0"));
var taskSettings = (Map<String, Object>) configs.get(0).get("task_settings");
assertThat(taskSettings, hasEntry("top_n", 3));
assertRerank(inferenceId);
}
private void assertRerank(String inferenceId) throws IOException {
cohereRerankServer.enqueue(new MockResponse().setResponseCode(200).setBody(rerankResponse()));
var inferenceMap = rerank(
inferenceId,
List.of("luke", "like", "leia", "chewy", "r2d2", "star", "wars"),
"star wars main character"
);
assertThat(inferenceMap.entrySet(), not(empty()));
}
private String embeddingConfigByte(String url) {
return embeddingConfigTemplate(url, "byte");
}
private String embeddingConfigInt8(String url) {
return embeddingConfigTemplate(url, "int8");
}
private String embeddingConfigFloat(String url) {
return embeddingConfigTemplate(url, "float");
}
private String embeddingConfigTemplate(String url, String embeddingType) {
return Strings.format("""
{
"service": "cohere",
"service_settings": {
"url": "%s",
"api_key": "XXXX",
"model_id": "embed-english-light-v3.0",
"embedding_type": "%s"
}
}
""", url, embeddingType);
}
private String embeddingResponseByte() {
return """
{
"id": "3198467e-399f-4d4a-aa2c-58af93bd6dc4",
"texts": [
"hello"
],
"embeddings": [
[
12,
56
]
],
"meta": {
"api_version": {
"version": "1"
},
"billed_units": {
"input_tokens": 1
}
},
"response_type": "embeddings_bytes"
}
""";
}
private String embeddingResponseFloat() {
return """
{
"id": "3198467e-399f-4d4a-aa2c-58af93bd6dc4",
"texts": [
"hello"
],
"embeddings": [
[
-0.0018434525,
0.01777649
]
],
"meta": {
"api_version": {
"version": "1"
},
"billed_units": {
"input_tokens": 1
}
},
"response_type": "embeddings_floats"
}
""";
}
private String rerankConfig(String url) {
return Strings.format("""
{
"service": "cohere",
"service_settings": {
"api_key": "XXXX",
"model_id": "rerank-english-v3.0",
"url": "%s"
},
"task_settings": {
"return_documents": false,
"top_n": 3
}
}
""", url);
}
private String rerankResponse() {
return """
{
"index": "d0760819-5a73-4d58-b163-3956d3648b62",
"results": [
{
"index": 2,
"relevance_score": 0.98005307
},
{
"index": 3,
"relevance_score": 0.27904198
},
{
"index": 0,
"relevance_score": 0.10194652
}
],
"meta": {
"api_version": {
"version": "1"
},
"billed_units": {
"search_units": 1
}
}
}
""";
}
}
| CohereServiceMixedIT |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/manytoone/jointable/ManyToOneJoinTableTest.java | {
"start": 6454,
"end": 7022
} | class ____ {
private Integer id;
private String name;
private OtherEntity other;
@Id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@OneToOne(mappedBy = "simpleEntity")
public OtherEntity getOther() {
return other;
}
public void setOther(OtherEntity other) {
this.other = other;
}
}
@Entity(name = "AnotherEntity")
@Table(name = "another_entity")
public static | SimpleEntity |
java | google__auto | value/src/main/java/com/google/auto/value/extension/AutoValueExtension.java | {
"start": 10949,
"end": 11019
} | class ____ this:
*
* <pre>{@code
* @AutoValue abstract | like |
java | apache__flink | flink-formats/flink-protobuf/src/main/java/org/apache/flink/formats/protobuf/deserialize/PbCodegenArrayDeserializer.java | {
"start": 1358,
"end": 3887
} | class ____ implements PbCodegenDeserializer {
private final Descriptors.FieldDescriptor fd;
private final LogicalType elementType;
private final PbFormatContext formatContext;
public PbCodegenArrayDeserializer(
Descriptors.FieldDescriptor fd,
LogicalType elementType,
PbFormatContext formatContext) {
this.fd = fd;
this.elementType = elementType;
this.formatContext = formatContext;
}
@Override
public String codegen(String resultVar, String pbObjectCode, int indent)
throws PbCodegenException {
// The type of pbObjectCode represents a general List object,
// it should be converted to ArrayData of flink internal type as resultVariable.
PbCodegenAppender appender = new PbCodegenAppender(indent);
PbCodegenVarId varUid = PbCodegenVarId.getInstance();
int uid = varUid.getAndIncrement();
String protoTypeStr = PbCodegenUtils.getTypeStrFromProto(fd, false);
String listPbVar = "list" + uid;
String flinkArrVar = "newArr" + uid;
String flinkArrEleVar = "subReturnVar" + uid;
String iVar = "i" + uid;
String subPbObjVar = "subObj" + uid;
appender.appendLine("List<" + protoTypeStr + "> " + listPbVar + "=" + pbObjectCode);
appender.appendLine(
"Object[] " + flinkArrVar + "= new " + "Object[" + listPbVar + ".size()]");
appender.begin(
"for(int " + iVar + "=0;" + iVar + " < " + listPbVar + ".size(); " + iVar + "++){");
appender.appendLine("Object " + flinkArrEleVar + " = null");
appender.appendLine(
protoTypeStr
+ " "
+ subPbObjVar
+ " = ("
+ protoTypeStr
+ ")"
+ listPbVar
+ ".get("
+ iVar
+ ")");
PbCodegenDeserializer codegenDes =
PbCodegenDeserializeFactory.getPbCodegenDes(fd, elementType, formatContext);
String code = codegenDes.codegen(flinkArrEleVar, subPbObjVar, appender.currentIndent());
appender.appendSegment(code);
appender.appendLine(flinkArrVar + "[" + iVar + "]=" + flinkArrEleVar + "");
appender.end("}");
appender.appendLine(resultVar + " = new GenericArrayData(" + flinkArrVar + ")");
return appender.code();
}
}
| PbCodegenArrayDeserializer |
java | mapstruct__mapstruct | integrationtest/src/test/resources/simpleTest/src/main/java/org/mapstruct/itest/simple/SomeOtherType.java | {
"start": 229,
"end": 1271
} | class ____ extends BaseType {
private String value;
public SomeOtherType(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ( ( value == null ) ? 0 : value.hashCode() );
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
SomeOtherType other = (SomeOtherType) obj;
if ( value == null ) {
if ( other.value != null ) {
return false;
}
}
else if ( !value.equals( other.value ) ) {
return false;
}
return true;
}
}
| SomeOtherType |
java | spring-projects__spring-security | oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/JdbcOAuth2AuthorizationService.java | {
"start": 38713,
"end": 39158
} | class ____ {
private static ObjectMapper createObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
ClassLoader classLoader = Jackson2.class.getClassLoader();
List<Module> securityModules = SecurityJackson2Modules.getModules(classLoader);
objectMapper.registerModules(securityModules);
objectMapper.registerModule(new OAuth2AuthorizationServerJackson2Module());
return objectMapper;
}
}
/**
* Nested | Jackson2 |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/common/extension/adaptive/impl/HasAdaptiveExt_ManualAdaptive.java | {
"start": 1089,
"end": 1387
} | class ____ implements HasAdaptiveExt {
public String echo(URL url, String s) {
HasAdaptiveExt addExt1 =
ExtensionLoader.getExtensionLoader(HasAdaptiveExt.class).getExtension(url.getParameter("key"));
return addExt1.echo(url, s);
}
}
| HasAdaptiveExt_ManualAdaptive |
java | google__dagger | javatests/dagger/functional/basic/OuterClassFoo.java | {
"start": 741,
"end": 794
} | interface ____ {
Thing thing();
}
}
| NestedComponent |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/RoutingSlipThrowExceptionFromExpressionTest.java | {
"start": 1097,
"end": 2140
} | class ____ extends ContextTestSupport {
@Test
public void testRoutingSlipAndVerifyException() throws Exception {
getMockEndpoint("mock:error").expectedMessageCount(1);
getMockEndpoint("mock:result").expectedMessageCount(0);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
onException(ExpressionEvaluationException.class).handled(true).to("mock://error");
from("direct://start").to("log:foo").routingSlip()
.method(RoutingSlipThrowExceptionFromExpressionTest.class, "slipTo").to("mock://result").end();
}
};
}
public List<String> slipTo(Exchange exchange) throws ExpressionEvaluationException {
throw new ExpressionEvaluationException(null, exchange, null);
}
}
| RoutingSlipThrowExceptionFromExpressionTest |
java | google__guava | android/guava/src/com/google/common/primitives/UnsignedLong.java | {
"start": 971,
"end": 1515
} | class ____ unsigned {@code long} values, supporting arithmetic operations.
*
* <p>In some cases, when speed is more important than code readability, it may be faster simply to
* treat primitive {@code long} values as unsigned, using the methods from {@link UnsignedLongs}.
*
* <p>See the Guava User Guide article on <a
* href="https://github.com/google/guava/wiki/PrimitivesExplained#unsigned-support">unsigned
* primitive utilities</a>.
*
* @author Louis Wasserman
* @author Colin Evans
* @since 11.0
*/
@GwtCompatible
public final | for |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/enums/EnumWithNullToString4355Test.java | {
"start": 377,
"end": 1119
} | enum ____ {
ALPHA("A"),
BETA("B"),
UNDEFINED(null);
private final String s;
Enum4355(String s) {
this.s = s;
}
@Override
public String toString() {
return s;
}
}
private final ObjectMapper MAPPER = jsonMapperBuilder()
.disable(EnumFeature.WRITE_ENUMS_USING_TO_STRING).build();
// [databind#4355]
@Test
public void testWithNullToString() throws Exception
{
assertEquals(q("ALPHA"), MAPPER.writeValueAsString(Enum4355.ALPHA));
assertEquals(q("BETA"), MAPPER.writeValueAsString(Enum4355.BETA));
assertEquals(q("UNDEFINED"), MAPPER.writeValueAsString(Enum4355.UNDEFINED));
}
}
| Enum4355 |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ConsulEndpointBuilderFactory.java | {
"start": 32781,
"end": 38909
} | interface ____ extends EndpointProducerBuilder {
default ConsulEndpointProducerBuilder basic() {
return (ConsulEndpointProducerBuilder) this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedConsulEndpointProducerBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedConsulEndpointProducerBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* The consistencyMode used for queries, default
* ConsistencyMode.DEFAULT.
*
* The option is a:
* <code>org.kiwiproject.consul.option.ConsistencyMode</code> type.
*
* Default: DEFAULT
* Group: advanced
*
* @param consistencyMode the value to set
* @return the dsl builder
*/
default AdvancedConsulEndpointProducerBuilder consistencyMode(org.kiwiproject.consul.option.ConsistencyMode consistencyMode) {
doSetProperty("consistencyMode", consistencyMode);
return this;
}
/**
* The consistencyMode used for queries, default
* ConsistencyMode.DEFAULT.
*
* The option will be converted to a
* <code>org.kiwiproject.consul.option.ConsistencyMode</code> type.
*
* Default: DEFAULT
* Group: advanced
*
* @param consistencyMode the value to set
* @return the dsl builder
*/
default AdvancedConsulEndpointProducerBuilder consistencyMode(String consistencyMode) {
doSetProperty("consistencyMode", consistencyMode);
return this;
}
/**
* The consul client to use.
*
* The option is a: <code>org.kiwiproject.consul.Consul</code> type.
*
* Group: advanced
*
* @param consulClient the value to set
* @return the dsl builder
*/
default AdvancedConsulEndpointProducerBuilder consulClient(org.kiwiproject.consul.Consul consulClient) {
doSetProperty("consulClient", consulClient);
return this;
}
/**
* The consul client to use.
*
* The option will be converted to a
* <code>org.kiwiproject.consul.Consul</code> type.
*
* Group: advanced
*
* @param consulClient the value to set
* @return the dsl builder
*/
default AdvancedConsulEndpointProducerBuilder consulClient(String consulClient) {
doSetProperty("consulClient", consulClient);
return this;
}
/**
* The data center.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param datacenter the value to set
* @return the dsl builder
*/
default AdvancedConsulEndpointProducerBuilder datacenter(String datacenter) {
doSetProperty("datacenter", datacenter);
return this;
}
/**
* The near node to use for queries.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param nearNode the value to set
* @return the dsl builder
*/
default AdvancedConsulEndpointProducerBuilder nearNode(String nearNode) {
doSetProperty("nearNode", nearNode);
return this;
}
/**
* The comma separated node meta-data to use for queries.
*
* The option is a: <code>java.lang.String</code> type.
*
* Group: advanced
*
* @param nodeMeta the value to set
* @return the dsl builder
*/
default AdvancedConsulEndpointProducerBuilder nodeMeta(String nodeMeta) {
doSetProperty("nodeMeta", nodeMeta);
return this;
}
}
/**
* Builder for endpoint for the Consul component.
*/
public | AdvancedConsulEndpointProducerBuilder |
java | google__guice | core/test/com/google/inject/errors/DuplicateElementErrorTest.java | {
"start": 2850,
"end": 4014
} | class ____ extends AbstractModule {
@ProvidesIntoSet
@Foo
IntWrapper provideFirstIntWrapper0() {
return new IntWrapper(0);
}
@ProvidesIntoSet
@Foo
IntWrapper provideSecondIntWrapper0() {
return new IntWrapper(0);
}
@ProvidesIntoSet
@Foo
IntWrapper provideFirstIntWrapper1() {
return new IntWrapper(1);
}
@ProvidesIntoSet
@Foo
IntWrapper provideSecondIntWrapper1() {
return new IntWrapper(1);
}
@Override
protected void configure() {
Multibinder.newSetBinder(binder(), Key.get(IntWrapper.class, Foo.class))
.addBinding()
.toProvider(() -> new IntWrapper(1));
}
}
@Test
public void multipleDuplicatesElementError() {
Injector injector = Guice.createInjector(new MultipleDuplicateElementsModule());
ProvisionException exception =
assertThrows(
ProvisionException.class,
() -> injector.getInstance(new Key<Set<IntWrapper>>(Foo.class) {}));
assertGuiceErrorEqualsIgnoreLineNumber(
exception.getMessage(), "multiple_duplicate_elements_error.txt");
}
}
| MultipleDuplicateElementsModule |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/cluster/metadata/DataStreamGlobalRetentionSettings.java | {
"start": 924,
"end": 1577
} | class ____ the data stream global retention settings. It defines, validates and monitors the settings.
* <p>
* The global retention settings apply to non-system data streams that are managed by the data stream lifecycle. They consist of:
* - The default retention which applies to the backing indices of data streams that do not have a retention defined.
* - The max retention which applies to backing and failure indices of data streams that do not have retention or their
* retention has exceeded this value.
* - The failures default retention which applied to the failure indices of data streams that do not have retention defined.
*/
public | holds |
java | spring-projects__spring-security | docs/src/test/java/org/springframework/security/docs/features/integrations/rest/configurationwebclient/ServerRestClientHttpInterfaceIntegrationConfigurationTests.java | {
"start": 2151,
"end": 3275
} | class ____ {
@Test
void getAuthenticatedUser(@Autowired MockWebServer webServer, @Autowired ReactiveOAuth2AuthorizedClientManager authorizedClients, @Autowired UserService users)
throws InterruptedException {
ClientRegistration registration = CommonOAuth2Provider.GITHUB.getBuilder("github").clientId("github").build();
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt.plus(Duration.ofMinutes(5));
OAuth2AccessToken token = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "1234",
issuedAt, expiresAt);
OAuth2AuthorizedClient result = new OAuth2AuthorizedClient(registration, "rob", token);
given(authorizedClients.authorize(any())).willReturn(Mono.just(result));
webServer.enqueue(new MockResponse().addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE).setBody(
"""
{"login": "rob_winch", "id": 1234, "name": "Rob Winch" }
"""));
users.getAuthenticatedUser();
assertThat(webServer.takeRequest().getHeader(HttpHeaders.AUTHORIZATION)).isEqualTo("Bearer " + token.getTokenValue());
}
}
| ServerRestClientHttpInterfaceIntegrationConfigurationTests |
java | elastic__elasticsearch | x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/SenderService.java | {
"start": 1918,
"end": 8450
} | class ____ implements InferenceService {
protected static final Set<TaskType> COMPLETION_ONLY = EnumSet.of(TaskType.COMPLETION);
private final Sender sender;
private final ServiceComponents serviceComponents;
private final ClusterService clusterService;
public SenderService(HttpRequestSender.Factory factory, ServiceComponents serviceComponents, ClusterService clusterService) {
Objects.requireNonNull(factory);
sender = factory.createSender();
this.serviceComponents = Objects.requireNonNull(serviceComponents);
this.clusterService = Objects.requireNonNull(clusterService);
}
public Sender getSender() {
return sender;
}
protected ServiceComponents getServiceComponents() {
return serviceComponents;
}
@Override
public void infer(
Model model,
@Nullable String query,
@Nullable Boolean returnDocuments,
@Nullable Integer topN,
List<String> input,
boolean stream,
Map<String, Object> taskSettings,
InputType inputType,
@Nullable TimeValue timeout,
ActionListener<InferenceServiceResults> listener
) {
SubscribableListener.newForked(this::init).<InferenceServiceResults>andThen((inferListener) -> {
var resolvedInferenceTimeout = ServiceUtils.resolveInferenceTimeout(timeout, inputType, clusterService);
var inferenceInput = createInput(this, model, input, inputType, query, returnDocuments, topN, stream);
doInfer(model, inferenceInput, taskSettings, resolvedInferenceTimeout, inferListener);
}).addListener(listener);
}
private static InferenceInputs createInput(
SenderService service,
Model model,
List<String> input,
InputType inputType,
@Nullable String query,
@Nullable Boolean returnDocuments,
@Nullable Integer topN,
boolean stream
) {
return switch (model.getTaskType()) {
case COMPLETION, CHAT_COMPLETION -> new ChatCompletionInput(input, stream);
case RERANK -> {
ValidationException validationException = new ValidationException();
service.validateRerankParameters(returnDocuments, topN, validationException);
if (query == null) {
validationException.addValidationError("Rerank task type requires a non-null query field");
}
if (validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
yield new QueryAndDocsInputs(query, input, returnDocuments, topN, stream);
}
case TEXT_EMBEDDING, SPARSE_EMBEDDING -> {
ValidationException validationException = new ValidationException();
service.validateInputType(inputType, model, validationException);
if (validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
yield new EmbeddingsInput(input, inputType, stream);
}
default -> throw new ElasticsearchStatusException(
Strings.format("Invalid task type received when determining input type: [%s]", model.getTaskType().toString()),
RestStatus.BAD_REQUEST
);
};
}
@Override
public void unifiedCompletionInfer(
Model model,
UnifiedCompletionRequest request,
TimeValue timeout,
ActionListener<InferenceServiceResults> listener
) {
SubscribableListener.newForked(this::init).<InferenceServiceResults>andThen((completionInferListener) -> {
doUnifiedCompletionInfer(model, new UnifiedChatInput(request, true), timeout, completionInferListener);
}).addListener(listener);
}
@Override
public void chunkedInfer(
Model model,
@Nullable String query,
List<ChunkInferenceInput> input,
Map<String, Object> taskSettings,
InputType inputType,
TimeValue timeout,
ActionListener<List<ChunkedInference>> listener
) {
SubscribableListener.newForked(this::init).<List<ChunkedInference>>andThen((chunkedInferListener) -> {
ValidationException validationException = new ValidationException();
validateInputType(inputType, model, validationException);
if (validationException.validationErrors().isEmpty() == false) {
throw validationException;
}
// a non-null query is not supported and is dropped by all providers
doChunkedInfer(model, input, taskSettings, inputType, timeout, chunkedInferListener);
}).addListener(listener);
}
protected abstract void doInfer(
Model model,
InferenceInputs inputs,
Map<String, Object> taskSettings,
TimeValue timeout,
ActionListener<InferenceServiceResults> listener
);
protected abstract void validateInputType(InputType inputType, Model model, ValidationException validationException);
protected void validateRerankParameters(Boolean returnDocuments, Integer topN, ValidationException validationException) {}
protected abstract void doUnifiedCompletionInfer(
Model model,
UnifiedChatInput inputs,
TimeValue timeout,
ActionListener<InferenceServiceResults> listener
);
protected abstract void doChunkedInfer(
Model model,
List<ChunkInferenceInput> inputs,
Map<String, Object> taskSettings,
InputType inputType,
TimeValue timeout,
ActionListener<List<ChunkedInference>> listener
);
public void start(Model model, ActionListener<Boolean> listener) {
SubscribableListener.newForked(this::init)
.<Boolean>andThen((doStartListener) -> doStart(model, doStartListener))
.addListener(listener);
}
@Override
public void start(Model model, @Nullable TimeValue unused, ActionListener<Boolean> listener) {
start(model, listener);
}
protected void doStart(Model model, ActionListener<Boolean> listener) {
listener.onResponse(true);
}
private void init(ActionListener<Void> listener) {
sender.startAsynchronously(listener);
}
@Override
public void close() throws IOException {
IOUtils.closeWhileHandlingException(sender);
}
}
| SenderService |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/DeadLetterChannelUseOriginalInBodyTest.java | {
"start": 2746,
"end": 3064
} | class ____ implements Processor {
public MyThrowProcessor() {
}
@Override
public void process(Exchange exchange) {
assertEquals("Hello World", exchange.getIn().getBody(String.class));
throw new IllegalArgumentException("Forced");
}
}
}
| MyThrowProcessor |
java | quarkusio__quarkus | extensions/panache/hibernate-reactive-panache/runtime/src/main/java/io/quarkus/hibernate/reactive/panache/runtime/CustomCountPanacheQuery.java | {
"start": 421,
"end": 839
} | class ____<Entity> extends PanacheQueryImpl<Entity> {
public CustomCountPanacheQuery(Uni<Mutiny.Session> em, String query, String customCountQuery,
Object paramsArrayOrMap) {
super(new CommonPanacheQueryImpl<Entity>(em, query, null, null, paramsArrayOrMap) {
{
this.customCountQueryForSpring = customCountQuery;
}
});
}
}
| CustomCountPanacheQuery |
java | apache__camel | components/camel-aws/camel-aws2-sts/src/test/java/org/apache/camel/component/aws2/sts/integration/StsAssumeRoleIT.java | {
"start": 1492,
"end": 2950
} | class ____ extends Aws2StsBase {
@EndpointInject
private ProducerTemplate template;
@EndpointInject("mock:result")
private MockEndpoint result;
@Test
public void sendIn() throws Exception {
result.expectedMessageCount(1);
template.send("direct:assumeRole", new Processor() {
@Override
public void process(Exchange exchange) {
exchange.getIn().setHeader(STS2Constants.OPERATION, "assumeRole");
exchange.getIn().setHeader(STS2Constants.ROLE_SESSION_NAME, "user_test");
exchange.getIn().setHeader(STS2Constants.ROLE_ARN, "user_test");
}
});
MockEndpoint.assertIsSatisfied(context);
assertEquals(1, result.getExchanges().size());
assertNotNull(
result.getExchanges().get(0).getIn().getBody(AssumeRoleResponse.class).credentials().accessKeyId());
assertNotNull(
result.getExchanges().get(0).getIn().getBody(AssumeRoleResponse.class).assumedRoleUser().assumedRoleId());
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
String awsEndpoint
= "aws2-sts://default?operation=assumeRole";
from("direct:assumeRole").to(awsEndpoint).to("mock:result");
}
};
}
}
| StsAssumeRoleIT |
java | apache__hadoop | hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/DeleteOperation.java | {
"start": 15184,
"end": 15746
} | class ____ {
private final ObjectIdentifier objectIdentifier;
private final boolean isDirMarker;
private DeleteEntry(final String key, final boolean isDirMarker) {
this.objectIdentifier = ObjectIdentifier.builder().key(key).build();
this.isDirMarker = isDirMarker;
}
public String getKey() {
return objectIdentifier.key();
}
@Override
public String toString() {
return "DeleteEntry{" +
"key='" + getKey() + '\'' +
", isDirMarker=" + isDirMarker +
'}';
}
}
}
| DeleteEntry |
java | spring-projects__spring-security | webauthn/src/main/java/org/springframework/security/web/webauthn/authentication/WebAuthnAuthenticationFilter.java | {
"start": 8063,
"end": 9436
} | class ____<T> extends AbstractSmartHttpMessageConverter<T> {
private final GenericHttpMessageConverter<T> delegate;
private GenericHttpMessageConverterAdapter(GenericHttpMessageConverter<T> delegate) {
Assert.notNull(delegate, "delegate cannot be null");
this.delegate = delegate;
}
@Override
public boolean canRead(Class<?> clazz, @Nullable MediaType mediaType) {
return this.delegate.canRead(clazz, mediaType);
}
@Override
public boolean canWrite(Class<?> clazz, @Nullable MediaType mediaType) {
return this.delegate.canWrite(clazz, mediaType);
}
@Override
public List<MediaType> getSupportedMediaTypes() {
return this.delegate.getSupportedMediaTypes();
}
@Override
public List<MediaType> getSupportedMediaTypes(Class<?> clazz) {
return this.delegate.getSupportedMediaTypes(clazz);
}
@Override
protected void writeInternal(T t, ResolvableType type, HttpOutputMessage outputMessage,
@Nullable Map<String, Object> hints) throws IOException, HttpMessageNotWritableException {
this.delegate.write(t, null, outputMessage);
}
@Override
public T read(ResolvableType type, HttpInputMessage inputMessage, @Nullable Map<String, Object> hints)
throws IOException, HttpMessageNotReadableException {
return this.delegate.read(type.getType(), null, inputMessage);
}
}
}
| GenericHttpMessageConverterAdapter |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestMetaSave.java | {
"start": 2400,
"end": 8168
} | class ____ {
static final int NUM_DATA_NODES = 2;
static final long seed = 0xDEADBEEFL;
static final int blockSize = 8192;
private static MiniDFSCluster cluster = null;
private static FileSystem fileSys = null;
private static NamenodeProtocols nnRpc = null;
@BeforeEach
public void setUp() throws IOException {
// start a cluster
Configuration conf = new HdfsConfiguration();
// High value of replication interval
// so that blocks remain less redundant
conf.setInt(DFSConfigKeys.DFS_NAMENODE_REDUNDANCY_INTERVAL_SECONDS_KEY,
1000);
conf.setLong(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1L);
conf.setLong(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 1L);
conf.setLong(DFSConfigKeys.DFS_NAMENODE_STALE_DATANODE_INTERVAL_KEY, 5L);
cluster = new MiniDFSCluster.Builder(conf).numDataNodes(NUM_DATA_NODES).build();
cluster.waitActive();
fileSys = cluster.getFileSystem();
nnRpc = cluster.getNameNodeRpc();
}
/**
* Tests metasave
*/
@Order(1)
@Test
public void testMetaSave()
throws IOException, InterruptedException, TimeoutException {
for (int i = 0; i < 2; i++) {
Path file = new Path("/filestatus" + i);
DFSTestUtil.createFile(fileSys, file, 1024, 1024, blockSize, (short) 2,
seed);
}
// stop datanode and wait for namenode to discover that a datanode is dead
stopDatanodeAndWait(1);
nnRpc.setReplication("/filestatus0", (short) 4);
nnRpc.metaSave("metasave.out.txt");
// Verification
FileInputStream fstream = new FileInputStream(getLogFile(
"metasave.out.txt"));
DataInputStream in = new DataInputStream(fstream);
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = reader.readLine();
assertEquals("3 files and directories, 2 blocks = 5 total filesystem objects",
line);
line = reader.readLine();
assertTrue(line.equals("Live Datanodes: 1"));
line = reader.readLine();
assertTrue(line.equals("Dead Datanodes: 1"));
reader.readLine();
line = reader.readLine();
assertTrue(line.matches("^/filestatus[01]:.*"));
} finally {
if (reader != null)
reader.close();
}
}
/**
* Tests metasave after delete, to make sure there are no orphaned blocks
*/
@Test
public void testMetasaveAfterDelete()
throws IOException, InterruptedException, TimeoutException {
for (int i = 0; i < 2; i++) {
Path file = new Path("/filestatus" + i);
DFSTestUtil.createFile(fileSys, file, 1024, 1024, blockSize, (short) 2,
seed);
}
// stop datanode and wait for namenode to discover that a datanode is dead
stopDatanodeAndWait(1);
nnRpc.setReplication("/filestatus0", (short) 4);
nnRpc.delete("/filestatus0", true);
nnRpc.delete("/filestatus1", true);
BlockManagerTestUtil.waitForMarkedDeleteQueueIsEmpty(
cluster.getNamesystem().getBlockManager());
nnRpc.metaSave("metasaveAfterDelete.out.txt");
// Verification
BufferedReader reader = null;
try {
FileInputStream fstream = new FileInputStream(getLogFile(
"metasaveAfterDelete.out.txt"));
DataInputStream in = new DataInputStream(fstream);
reader = new BufferedReader(new InputStreamReader(in));
reader.readLine();
String line = reader.readLine();
assertTrue(line.equals("Live Datanodes: 1"));
line = reader.readLine();
assertTrue(line.equals("Dead Datanodes: 1"));
line = reader.readLine();
assertTrue(line.equals("Metasave: Blocks waiting for reconstruction: 0"));
line = reader.readLine();
assertTrue(line.equals("Metasave: Blocks currently missing: 0"));
line = reader.readLine();
assertTrue(line.equals("Mis-replicated blocks that have been postponed:"));
line = reader.readLine();
assertTrue(line.equals("Metasave: Blocks being reconstructed: 0"));
line = reader.readLine();
assertTrue(line.equals("Metasave: Blocks 2 waiting deletion from 1 datanodes."));
//skip 2 lines to reach HDFS-9033 scenario.
line = reader.readLine();
line = reader.readLine();
assertTrue(line.contains("blk"));
// skip 1 line for Corrupt Blocks section.
line = reader.readLine();
line = reader.readLine();
assertTrue(line.equals("Metasave: Number of datanodes: 2"));
line = reader.readLine();
assertFalse(line.contains("NaN"));
} finally {
if (reader != null)
reader.close();
}
}
/**
* Tests that metasave overwrites the output file (not append).
*/
@Test
public void testMetaSaveOverwrite() throws Exception {
// metaSave twice.
nnRpc.metaSave("metaSaveOverwrite.out.txt");
nnRpc.metaSave("metaSaveOverwrite.out.txt");
// Read output file.
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader rdr = null;
try {
fis = new FileInputStream(getLogFile("metaSaveOverwrite.out.txt"));
isr = new InputStreamReader(fis);
rdr = new BufferedReader(isr);
// Validate that file was overwritten (not appended) by checking for
// presence of only one "Live Datanodes" line.
boolean foundLiveDatanodesLine = false;
String line = rdr.readLine();
while (line != null) {
if (line.startsWith("Live Datanodes")) {
if (foundLiveDatanodesLine) {
fail("multiple Live Datanodes lines, output file not overwritten");
}
foundLiveDatanodesLine = true;
}
line = rdr.readLine();
}
} finally {
IOUtils.cleanupWithLogger(null, rdr, isr, fis);
}
}
| TestMetaSave |
java | spring-projects__spring-boot | module/spring-boot-opentelemetry/src/test/java/org/springframework/boot/opentelemetry/autoconfigure/OpenTelemetrySdkAutoConfigurationTests.java | {
"start": 7117,
"end": 7316
} | class ____ {
@Bean
OpenTelemetry customOpenTelemetry() {
return mock(OpenTelemetry.class);
}
@Bean
Resource customResource() {
return Resource.getDefault();
}
}
}
| UserConfiguration |
java | alibaba__nacos | config/src/main/java/com/alibaba/nacos/config/server/utils/SimpleReadWriteLock.java | {
"start": 800,
"end": 1982
} | class ____ {
/**
* Zero means no lock; Negative Numbers mean write locks; Positive Numbers mean read locks, and the numeric value
* represents the number of read locks.
*/
private int status = 0;
/**
* Try read lock.
*/
public synchronized boolean tryReadLock() {
if (isWriteLocked()) {
return false;
} else {
status++;
return true;
}
}
/**
* Release the read lock.
*/
public synchronized void releaseReadLock() {
// when status equals 0, it should not decrement to negative numbers
if (status == 0) {
return;
}
status--;
}
/**
* Try write lock.
*/
public synchronized boolean tryWriteLock() {
if (!isFree()) {
return false;
} else {
status = -1;
return true;
}
}
public synchronized void releaseWriteLock() {
status = 0;
}
private boolean isWriteLocked() {
return status < 0;
}
private boolean isFree() {
return status == 0;
}
}
| SimpleReadWriteLock |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/util/TokenBuffer.java | {
"start": 800,
"end": 1198
} | class ____ for efficient storage of {@link JsonToken}
* sequences, needed for temporary buffering.
* Space efficient for different sequence lengths (especially so for smaller
* ones; but not significantly less efficient for larger), highly efficient
* for linear iteration and appending. Implemented as segmented/chunked
* linked list of tokens; only modifications are via appends.
*/
public | used |
java | lettuce-io__lettuce-core | src/test/java/io/lettuce/core/cluster/RedisClusterClientFactoryUnitTests.java | {
"start": 537,
"end": 4417
} | class ____ {
private static final String URI = "redis://" + TestSettings.host() + ":" + TestSettings.port();
private static final RedisURI REDIS_URI = RedisURI.create(URI);
private static final List<RedisURI> REDIS_URIS = LettuceLists.newList(REDIS_URI);
@Test
void withStringUri() {
FastShutdown.shutdown(RedisClusterClient.create(TestClientResources.get(), URI));
}
@Test
void withStringUriNull() {
assertThatThrownBy(() -> RedisClusterClient.create((String) null)).isInstanceOf(IllegalArgumentException.class);
}
@Test
void withUri() {
FastShutdown.shutdown(RedisClusterClient.create(REDIS_URI));
}
@Test
void withUriUri() {
assertThatThrownBy(() -> RedisClusterClient.create((RedisURI) null)).isInstanceOf(IllegalArgumentException.class);
}
@Test
void withUriIterable() {
FastShutdown.shutdown(RedisClusterClient.create(LettuceLists.newList(REDIS_URI)));
}
@Test
void withUriIterableNull() {
assertThatThrownBy(() -> RedisClusterClient.create((Iterable<RedisURI>) null))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void clientResourcesWithStringUri() {
FastShutdown.shutdown(RedisClusterClient.create(TestClientResources.get(), URI));
}
@Test
void clientResourcesWithStringUriNull() {
assertThatThrownBy(() -> RedisClusterClient.create(TestClientResources.get(), (String) null))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void clientResourcesNullWithStringUri() {
assertThatThrownBy(() -> RedisClusterClient.create(null, URI)).isInstanceOf(IllegalArgumentException.class);
}
@Test
void clientResourcesWithUri() {
FastShutdown.shutdown(RedisClusterClient.create(TestClientResources.get(), REDIS_URI));
}
@Test
void clientResourcesWithUriNull() {
assertThatThrownBy(() -> RedisClusterClient.create(TestClientResources.get(), (RedisURI) null))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void clientResourcesWithUriUri() {
assertThatThrownBy(() -> RedisClusterClient.create(null, REDIS_URI)).isInstanceOf(IllegalArgumentException.class);
}
@Test
void clientResourcesWithUriIterable() {
FastShutdown.shutdown(RedisClusterClient.create(TestClientResources.get(), LettuceLists.newList(REDIS_URI)));
}
@Test
void clientResourcesWithUriIterableNull() {
assertThatThrownBy(() -> RedisClusterClient.create(TestClientResources.get(), (Iterable<RedisURI>) null))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void clientResourcesNullWithUriIterable() {
assertThatThrownBy(() -> RedisClusterClient.create(null, REDIS_URIS)).isInstanceOf(IllegalArgumentException.class);
}
@Test
void clientWithDifferentSslSettings() {
assertThatThrownBy(() -> RedisClusterClient
.create(Arrays.asList(RedisURI.create("redis://host1"), RedisURI.create("redis+ssl://host1"))))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void clientWithDifferentTlsSettings() {
assertThatThrownBy(() -> RedisClusterClient
.create(Arrays.asList(RedisURI.create("rediss://host1"), RedisURI.create("redis+tls://host1"))))
.isInstanceOf(IllegalArgumentException.class);
}
@Test
void clientWithDifferentVerifyPeerSettings() {
RedisURI redisURI = RedisURI.create("rediss://host1");
redisURI.setVerifyPeer(false);
assertThatThrownBy(() -> RedisClusterClient.create(Arrays.asList(redisURI, RedisURI.create("rediss://host1"))))
.isInstanceOf(IllegalArgumentException.class);
}
}
| RedisClusterClientFactoryUnitTests |
java | alibaba__fastjson | src/test/java/com/alibaba/fastjson/deserializer/issues3796/bean/ObjectA1.java | {
"start": 92,
"end": 777
} | class ____ {
private List<CommonObject> a;
private CommonObject b;
private CommonObject c;
private List<CommonObject> d;
private boolean e = true;
public List<CommonObject> getA() {
return a;
}
public void setA(List<CommonObject> a) {
this.a = a;
}
public CommonObject getB() {
return b;
}
public void setB(CommonObject b) {
this.b = b;
}
public CommonObject getC() {
return c;
}
public void setC(CommonObject c) {
this.c = c;
}
public List<CommonObject> getD() {
return d;
}
public void setD(List<CommonObject> d) {
this.d = d;
}
public boolean isE() {
return e;
}
public void setE(boolean e) {
this.e = e;
}
}
| ObjectA1 |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/android/WakelockReleasedDangerouslyTest.java | {
"start": 18232,
"end": 18433
} | class ____ {
WakeLock wakelock;
OuterClass(WakeLock wl) {
wakelock = wl;
wakelock.acquire(100);
}
public | OuterClass |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/executiongraph/failover/FailureHandlingResult.java | {
"start": 1608,
"end": 11131
} | class ____ {
/**
* Task vertices to restart to recover from the failure or {@code null} if the failure is not
* recoverable.
*/
private final Set<ExecutionVertexID> verticesToRestart;
/** Delay before the restarting can be conducted. */
private final long restartDelayMS;
/**
* The {@link Execution} that the failure is originating from or {@code null} if it's a global
* failure.
*/
@Nullable private final Execution failedExecution;
/** Failure reason. {@code @Nullable} because of FLINK-21376. */
@Nullable private final Throwable error;
/** Future Map of string labels characterizing the failure. */
private final CompletableFuture<Map<String, String>> failureLabels;
/** Failure timestamp. */
private final long timestamp;
/** True if the original failure was a global failure. */
private final boolean globalFailure;
/** True if current failure is the root cause instead of concurrent exceptions. */
private final boolean isRootCause;
/**
* Creates a result of a set of tasks to restart to recover from the failure.
*
* @param failedExecution the {@link Execution} that the failure is originating from. Passing
* {@code null} as a value indicates that the failure was issued by Flink itself.
* @param cause the exception that caused this failure.
* @param timestamp the time the failure was handled.
* @param failureLabels collection of string tags characterizing the failure.
* @param verticesToRestart containing task vertices to restart to recover from the failure.
* {@code null} indicates that the failure is not restartable.
* @param restartDelayMS indicate a delay before conducting the restart
* @param isRootCause indicate whether current failure is a new attempt.
*/
private FailureHandlingResult(
@Nullable Execution failedExecution,
@Nullable Throwable cause,
long timestamp,
CompletableFuture<Map<String, String>> failureLabels,
Set<ExecutionVertexID> verticesToRestart,
long restartDelayMS,
boolean globalFailure,
boolean isRootCause) {
checkState(restartDelayMS >= 0);
this.verticesToRestart = Collections.unmodifiableSet(checkNotNull(verticesToRestart));
this.restartDelayMS = restartDelayMS;
this.failedExecution = failedExecution;
this.error = cause;
this.failureLabels = failureLabels;
this.timestamp = timestamp;
this.globalFailure = globalFailure;
this.isRootCause = isRootCause;
}
/**
* Creates a result that the failure is not recoverable and no restarting should be conducted.
*
* @param failedExecution the {@link Execution} that the failure is originating from. Passing
* {@code null} as a value indicates that the failure was issued by Flink itself.
* @param error reason why the failure is not recoverable
* @param timestamp the time the failure was handled.
* @param failureLabels collection of tags characterizing the failure as produced by the
* FailureEnrichers
* @param isRootCause indicate whether current failure is a new attempt.
*/
private FailureHandlingResult(
@Nullable Execution failedExecution,
@Nonnull Throwable error,
long timestamp,
CompletableFuture<Map<String, String>> failureLabels,
boolean globalFailure,
boolean isRootCause) {
this.isRootCause = isRootCause;
this.verticesToRestart = null;
this.restartDelayMS = -1;
this.failedExecution = failedExecution;
this.error = checkNotNull(error);
this.failureLabels = failureLabels;
this.timestamp = timestamp;
this.globalFailure = globalFailure;
}
/**
* Returns the tasks to restart.
*
* @return the tasks to restart
*/
public Set<ExecutionVertexID> getVerticesToRestart() {
if (canRestart()) {
return verticesToRestart;
} else {
throw new IllegalStateException(
"Cannot get vertices to restart when the restarting is suppressed.");
}
}
/**
* Returns the delay before the restarting.
*
* @return the delay before the restarting
*/
public long getRestartDelayMS() {
if (canRestart()) {
return restartDelayMS;
} else {
throw new IllegalStateException(
"Cannot get restart delay when the restarting is suppressed.");
}
}
/**
* Returns an {@code Optional} with the {@link Execution} causing this failure or an empty
* {@code Optional} if it's a global failure.
*
* @return The {@code Optional} with the failed {@code Execution} or an empty {@code Optional}
* if it's a global failure.
*/
public Optional<Execution> getFailedExecution() {
return Optional.ofNullable(failedExecution);
}
/**
* Returns reason why the restarting cannot be conducted.
*
* @return reason why the restarting cannot be conducted
*/
@Nullable
public Throwable getError() {
return error;
}
/**
* Returns the labels future associated with the failure.
*
* @return the CompletableFuture Map of String labels
*/
public CompletableFuture<Map<String, String>> getFailureLabels() {
return failureLabels;
}
/**
* Returns the time of the failure.
*
* @return The timestamp.
*/
public long getTimestamp() {
return timestamp;
}
/**
* Returns whether the restarting can be conducted.
*
* @return whether the restarting can be conducted
*/
public boolean canRestart() {
return verticesToRestart != null;
}
/**
* Checks if this failure was a global failure, i.e., coming from a "safety net" failover that
* involved all tasks and should reset also components like the coordinators.
*/
public boolean isGlobalFailure() {
return globalFailure;
}
/**
* @return True means that the current failure is a new attempt, false means that there has been
* a failure before and has not been tried yet, and the current failure will be merged into
* the previous attempt, and these merged exceptions will be considered as the concurrent
* exceptions.
*/
public boolean isRootCause() {
return isRootCause;
}
/**
* Creates a result of a set of tasks to restart to recover from the failure.
*
* <p>The result can be flagged to be from a global failure triggered by the scheduler, rather
* than from the failure of an individual task.
*
* @param failedExecution the {@link Execution} that the failure is originating from. Passing
* {@code null} as a value indicates that the failure was issued by Flink itself.
* @param cause The reason of the failure.
* @param timestamp The time of the failure.
* @param failureLabels Map of labels characterizing the failure produced by the
* FailureEnrichers.
* @param verticesToRestart containing task vertices to restart to recover from the failure.
* {@code null} indicates that the failure is not restartable.
* @param restartDelayMS indicate a delay before conducting the restart
* @return result of a set of tasks to restart to recover from the failure
*/
public static FailureHandlingResult restartable(
@Nullable Execution failedExecution,
@Nullable Throwable cause,
long timestamp,
CompletableFuture<Map<String, String>> failureLabels,
Set<ExecutionVertexID> verticesToRestart,
long restartDelayMS,
boolean globalFailure,
boolean isRootCause) {
return new FailureHandlingResult(
failedExecution,
cause,
timestamp,
failureLabels,
verticesToRestart,
restartDelayMS,
globalFailure,
isRootCause);
}
/**
* Creates a result that the failure is not recoverable and no restarting should be conducted.
*
* <p>The result can be flagged to be from a global failure triggered by the scheduler, rather
* than from the failure of an individual task.
*
* @param failedExecution the {@link Execution} that the failure is originating from. Passing
* {@code null} as a value indicates that the failure was issued by Flink itself.
* @param error reason why the failure is not recoverable
* @param timestamp The time of the failure.
* @param failureLabels Map of labels characterizing the failure produced by the
* FailureEnrichers.
* @return result indicating the failure is not recoverable
*/
public static FailureHandlingResult unrecoverable(
@Nullable Execution failedExecution,
@Nonnull Throwable error,
long timestamp,
CompletableFuture<Map<String, String>> failureLabels,
boolean globalFailure,
boolean isRootCause) {
return new FailureHandlingResult(
failedExecution, error, timestamp, failureLabels, globalFailure, isRootCause);
}
}
| FailureHandlingResult |
java | spring-projects__spring-boot | module/spring-boot-web-server/src/main/java/org/springframework/boot/web/server/WebServerFactory.java | {
"start": 687,
"end": 970
} | interface ____ factories that create a {@link WebServer}.
*
* @author Phillip Webb
* @since 2.0.0
* @see WebServer
* @see org.springframework.boot.web.server.servlet.ServletWebServerFactory
* @see org.springframework.boot.web.server.reactive.ReactiveWebServerFactory
*/
public | for |
java | quarkusio__quarkus | extensions/panache/mongodb-panache-common/runtime/src/main/java/io/quarkus/mongodb/panache/common/runtime/MongoOperations.java | {
"start": 1532,
"end": 32333
} | class ____<QueryType, UpdateType> {
public static final String ID = "_id";
public static final Object SESSION_KEY = new Object();
private static final Logger LOGGER = Logger.getLogger(MongoOperations.class);
// update operators: https://docs.mongodb.com/manual/reference/operator/update/
private static final List<String> UPDATE_OPERATORS = Arrays.asList(
"$currentDate", "$inc", "$min", "$max", "$mul", "$rename", "$set", "$setOnInsert", "$unset",
"$addToSet", "$pop", "$pull", "$push", "$pullAll",
"$each", "$position", "$slice", "$sort",
"$bit");
private final Map<String, String> defaultDatabaseName = new ConcurrentHashMap<>();
protected abstract QueryType createQuery(MongoCollection<?> collection, ClientSession session, Bson query,
Bson sortDoc);
protected abstract UpdateType createUpdate(MongoCollection collection, Class<?> entityClass, Bson docUpdate);
protected abstract List<?> list(QueryType queryType);
protected abstract Stream<?> stream(QueryType queryType);
public void persist(Object entity) {
MongoCollection collection = mongoCollection(entity);
persist(collection, entity);
}
public void persist(Iterable<?> entities) {
// not all iterables are re-traversal, so we traverse it once for copying inside a list
List<Object> objects = new ArrayList<>();
for (Object entity : entities) {
objects.add(entity);
}
persist(objects);
}
public void persist(Object firstEntity, Object... entities) {
if (entities == null || entities.length == 0) {
MongoCollection collection = mongoCollection(firstEntity);
persist(collection, firstEntity);
} else {
List<Object> entityList = new ArrayList<>();
entityList.add(firstEntity);
entityList.addAll(Arrays.asList(entities));
persist(entityList);
}
}
public void persist(Stream<?> entities) {
List<Object> objects = entities.collect(Collectors.toList());
persist(objects);
}
public void update(Object entity) {
MongoCollection collection = mongoCollection(entity);
update(collection, entity);
}
public void update(Iterable<?> entities) {
// not all iterables are re-traversal, so we traverse it once for copying inside a list
List<Object> objects = new ArrayList<>();
for (Object entity : entities) {
objects.add(entity);
}
if (!objects.isEmpty()) {
// get the first entity to be able to retrieve the collection with it
Object firstEntity = objects.get(0);
MongoCollection collection = mongoCollection(firstEntity);
update(collection, objects);
}
}
public void update(Object firstEntity, Object... entities) {
MongoCollection collection = mongoCollection(firstEntity);
if (entities == null || entities.length == 0) {
update(collection, firstEntity);
} else {
List<Object> entityList = new ArrayList<>();
entityList.add(firstEntity);
entityList.addAll(Arrays.asList(entities));
update(collection, entityList);
}
}
public void update(Stream<?> entities) {
List<Object> objects = entities.collect(Collectors.toList());
if (!objects.isEmpty()) {
// get the first entity to be able to retrieve the collection with it
Object firstEntity = objects.get(0);
MongoCollection collection = mongoCollection(firstEntity);
update(collection, objects);
}
}
public void persistOrUpdate(Object entity) {
MongoCollection collection = mongoCollection(entity);
persistOrUpdate(collection, entity);
}
public void persistOrUpdate(Iterable<?> entities) {
// not all iterables are re-traversal, so we traverse it once for copying inside a list
List<Object> objects = new ArrayList<>();
for (Object entity : entities) {
objects.add(entity);
}
persistOrUpdate(objects);
}
public void persistOrUpdate(Object firstEntity, Object... entities) {
MongoCollection collection = mongoCollection(firstEntity);
if (entities == null || entities.length == 0) {
persistOrUpdate(collection, firstEntity);
} else {
List<Object> entityList = new ArrayList<>();
entityList.add(firstEntity);
entityList.addAll(Arrays.asList(entities));
persistOrUpdate(entityList);
}
}
public void persistOrUpdate(Stream<?> entities) {
List<Object> objects = entities.collect(Collectors.toList());
persistOrUpdate(objects);
}
public void delete(Object entity) {
MongoCollection collection = mongoCollection(entity);
BsonDocument document = getBsonDocument(collection, entity);
BsonValue id = document.get(ID);
BsonDocument query = new BsonDocument().append(ID, id);
ClientSession session = getSession(entity);
if (session == null) {
collection.deleteOne(query);
} else {
collection.deleteOne(session, query);
}
}
public MongoCollection mongoCollection(Class<?> entityClass) {
MongoEntity mongoEntity = entityClass.getAnnotation(MongoEntity.class);
MongoDatabase database = mongoDatabase(mongoEntity);
if (mongoEntity != null) {
MongoCollection collection = mongoEntity.collection().isEmpty()
? database.getCollection(entityClass.getSimpleName(), entityClass)
: database.getCollection(mongoEntity.collection(), entityClass);
if (!mongoEntity.readPreference().isEmpty()) {
try {
collection = collection.withReadPreference(ReadPreference.valueOf(mongoEntity.readPreference()));
} catch (IllegalArgumentException iae) {
throw new IllegalArgumentException("Illegal read preference " + mongoEntity.readPreference()
+ " configured in the @MongoEntity annotation of " + entityClass.getName() + "."
+ " Supported values are primary|primaryPreferred|secondary|secondaryPreferred|nearest");
}
}
return collection;
}
return database.getCollection(entityClass.getSimpleName(), entityClass);
}
public MongoDatabase mongoDatabase(Class<?> entityClass) {
MongoEntity mongoEntity = entityClass.getAnnotation(MongoEntity.class);
return mongoDatabase(mongoEntity);
}
//
// Private stuff
private void persist(MongoCollection collection, Object entity) {
ClientSession session = getSession(entity);
if (session == null) {
collection.insertOne(entity);
} else {
collection.insertOne(session, entity);
}
}
private void persist(List<Object> entities) {
if (!entities.isEmpty()) {
// get the first entity to be able to retrieve the collection with it
Object firstEntity = entities.get(0);
MongoCollection collection = mongoCollection(firstEntity);
ClientSession session = getSession(firstEntity);
if (session == null) {
collection.insertMany(entities);
} else {
collection.insertMany(session, entities);
}
}
}
private void update(MongoCollection collection, Object entity) {
//we transform the entity as a document first
BsonDocument document = getBsonDocument(collection, entity);
//then we get its id field and create a new Document with only this one that will be our replace query
BsonValue id = document.get(ID);
BsonDocument query = new BsonDocument().append(ID, id);
ClientSession session = getSession(entity);
if (session == null) {
collection.replaceOne(query, entity);
} else {
collection.replaceOne(session, query, entity);
}
}
private void update(MongoCollection collection, List<Object> entities) {
for (Object entity : entities) {
update(collection, entity);
}
}
private void persistOrUpdate(MongoCollection collection, Object entity) {
//we transform the entity as a document first
BsonDocument document = getBsonDocument(collection, entity);
ClientSession session = getSession(entity);
//then we get its id field and create a new Document with only this one that will be our replace query
BsonValue id = document.get(ID);
if (id == null) {
//insert with autogenerated ID
if (session == null) {
collection.insertOne(entity);
} else {
collection.insertOne(session, entity);
}
} else {
//insert with user provided ID or update
BsonDocument query = new BsonDocument().append(ID, id);
if (session == null) {
collection.replaceOne(query, entity, new ReplaceOptions().upsert(true));
} else {
collection.replaceOne(session, query, entity, new ReplaceOptions().upsert(true));
}
}
}
private void persistOrUpdate(List<Object> entities) {
if (entities.isEmpty()) {
return;
}
// get the first entity to be able to retrieve the collection with it
Object firstEntity = entities.get(0);
MongoCollection collection = mongoCollection(firstEntity);
ClientSession session = getSession(firstEntity);
//this will be an ordered bulk: it's less performant than an unordered one but will fail at the first failed write
List<WriteModel> bulk = new ArrayList<>();
for (Object entity : entities) {
//we transform the entity as a document first
BsonDocument document = getBsonDocument(collection, entity);
//then we get its id field and create a new Document with only this one that will be our replace query
BsonValue id = document.get(ID);
if (id == null) {
//insert with autogenerated ID
bulk.add(new InsertOneModel(entity));
} else {
//insert with user provided ID or update
BsonDocument query = new BsonDocument().append(ID, id);
bulk.add(new ReplaceOneModel(query, entity,
new ReplaceOptions().upsert(true)));
}
}
if (session == null) {
collection.bulkWrite(bulk);
} else {
collection.bulkWrite(session, bulk);
}
}
private BsonDocument getBsonDocument(MongoCollection collection, Object entity) {
BsonDocument document = new BsonDocument();
Codec codec = collection.getCodecRegistry().get(entity.getClass());
codec.encode(new BsonDocumentWriter(document), entity, EncoderContext.builder().build());
return document;
}
ClientSession getSession(Object entity) {
return getSession(entity.getClass());
}
public ClientSession getSession(Class<?> entityClass) {
ClientSession clientSession = null;
InstanceHandle<TransactionSynchronizationRegistry> instance = Arc.container()
.instance(TransactionSynchronizationRegistry.class);
if (instance.isAvailable()) {
TransactionSynchronizationRegistry registry = instance.get();
if (registry.getTransactionStatus() == Status.STATUS_ACTIVE) {
clientSession = (ClientSession) registry.getResource(SESSION_KEY);
if (clientSession == null) {
MongoEntity mongoEntity = entityClass == null ? null : entityClass.getAnnotation(MongoEntity.class);
return registerClientSession(mongoEntity, registry);
}
}
}
return clientSession;
}
public ClientSession getSession() {
return getSession(null);
}
private ClientSession registerClientSession(MongoEntity mongoEntity,
TransactionSynchronizationRegistry registry) {
TransactionManager transactionManager = Arc.container().instance(TransactionManager.class).get();
MongoClient client = BeanUtils.clientFromArc(mongoEntity, MongoClient.class, false);
ClientSession clientSession = client.startSession();
clientSession.startTransaction();//TODO add txoptions from annotation
registry.putResource(SESSION_KEY, clientSession);
registry.registerInterposedSynchronization(new Synchronization() {
@Override
public void beforeCompletion() {
}
@Override
public void afterCompletion(int i) {
try {
if (transactionManager.getStatus() == Status.STATUS_ROLLEDBACK) {
try {
clientSession.abortTransaction();
} finally {
clientSession.close();
}
} else {
try {
clientSession.commitTransaction();
} finally {
clientSession.close();
}
}
} catch (SystemException e) {
throw new MongoTransactionException(e);
}
}
});
return clientSession;
}
private MongoCollection mongoCollection(Object entity) {
Class<?> entityClass = entity.getClass();
return mongoCollection(entityClass);
}
private MongoDatabase mongoDatabase(MongoEntity mongoEntity) {
MongoClient mongoClient = BeanUtils.clientFromArc(mongoEntity, MongoClient.class, false);
if (mongoEntity != null && !mongoEntity.database().isEmpty()) {
return mongoClient.getDatabase(mongoEntity.database());
}
String databaseName = BeanUtils.getDatabaseNameFromResolver().orElseGet(() -> getDefaultDatabaseName(mongoEntity));
return mongoClient.getDatabase(databaseName);
}
private String getDefaultDatabaseName(MongoEntity mongoEntity) {
return defaultDatabaseName.computeIfAbsent(BeanUtils.beanName(mongoEntity),
new Function<String, String>() {
@Override
public String apply(String beanName) {
return BeanUtils.getDatabaseName(mongoEntity, beanName);
}
});
}
//
// Queries
public Object findById(Class<?> entityClass, Object id) {
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return session == null ? collection.find(new Document(ID, id)).first()
: collection.find(session, new Document(ID, id)).first();
}
public Optional findByIdOptional(Class<?> entityClass, Object id) {
return Optional.ofNullable(findById(entityClass, id));
}
public <Entity, ID> List<Entity> findByIds(Class<?> entityClass, List<ID> ids) {
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return session == null ? (List<Entity>) collection.find(in(ID, ids)).into(new ArrayList<>())
: (List<Entity>) collection.find(session, in(ID, ids)).into(new ArrayList<>());
}
public QueryType find(Class<?> entityClass, String query, Object... params) {
return find(entityClass, query, null, params);
}
public QueryType find(Class<?> entityClass, String query, Sort sort, Object... params) {
String bindQuery = bindFilter(entityClass, query, params);
Bson docQuery = Document.parse(bindQuery);
Bson docSort = sortToDocument(sort);
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return createQuery(collection, session, docQuery, docSort);
}
/**
* We should have a query like <code>{'firstname': ?1, 'lastname': ?2}</code> for native one
* and like <code>firstname = ?1</code> for PanacheQL one.
*/
public String bindFilter(Class<?> clazz, String query, Object[] params) {
String bindQuery = bindQuery(clazz, query, params);
LOGGER.debug(bindQuery);
return bindQuery;
}
/**
* We should have a query like <code>{'firstname': :firstname, 'lastname': :lastname}</code> for native one
* and like <code>firstname = :firstname and lastname = :lastname</code> for PanacheQL one.
*/
public String bindFilter(Class<?> clazz, String query, Map<String, Object> params) {
String bindQuery = bindQuery(clazz, query, params);
LOGGER.debug(bindQuery);
return bindQuery;
}
/**
* We should have a query like <code>{'firstname': ?1, 'lastname': ?2}</code> for native one
* and like <code>firstname = ?1 and lastname = ?2</code> for PanacheQL one.
* As update document needs an update operator, we add <code>$set</code> if none is provided.
*/
String bindUpdate(Class<?> clazz, String query, Object[] params) {
String bindUpdate = bindQuery(clazz, query, params);
if (!containsUpdateOperator(query)) {
bindUpdate = "{'$set':" + bindUpdate + "}";
}
LOGGER.debug(bindUpdate);
return bindUpdate;
}
/**
* We should have a query like <code>{'firstname': :firstname, 'lastname': :lastname}</code> for native one
* and like <code>firstname = :firstname and lastname = :lastname</code> for PanacheQL one.
* As update document needs an update operator, we add <code>$set</code> if none is provided.
*/
String bindUpdate(Class<?> clazz, String query, Map<String, Object> params) {
String bindUpdate = bindQuery(clazz, query, params);
if (!containsUpdateOperator(query)) {
bindUpdate = "{'$set':" + bindUpdate + "}";
}
LOGGER.debug(bindUpdate);
return bindUpdate;
}
private boolean containsUpdateOperator(String update) {
for (String operator : UPDATE_OPERATORS) {
if (update.contains(operator)) {
return true;
}
}
return false;
}
private String bindQuery(Class<?> clazz, String query, Object[] params) {
String bindQuery = null;
//determine the type of the query
if (query.charAt(0) == '{') {
//this is a native query
bindQuery = NativeQueryBinder.bindQuery(query, params);
} else {
//this is a PanacheQL query
bindQuery = PanacheQlQueryBinder.bindQuery(clazz, query, params);
}
return bindQuery;
}
private String bindQuery(Class<?> clazz, String query, Map<String, Object> params) {
String bindQuery = null;
//determine the type of the query
if (query.charAt(0) == '{') {
//this is a native query
bindQuery = NativeQueryBinder.bindQuery(query, params);
} else {
//this is a PanacheQL query
bindQuery = PanacheQlQueryBinder.bindQuery(clazz, query, params);
}
return bindQuery;
}
public QueryType find(Class<?> entityClass, String query, Map<String, Object> params) {
return find(entityClass, query, null, params);
}
public QueryType find(Class<?> entityClass, String query, Sort sort, Map<String, Object> params) {
String bindQuery = bindFilter(entityClass, query, params);
Bson docQuery = Document.parse(bindQuery);
Bson docSort = sortToDocument(sort);
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return createQuery(collection, session, docQuery, docSort);
}
public QueryType find(Class<?> entityClass, String query, Parameters params) {
return find(entityClass, query, null, params.map());
}
public QueryType find(Class<?> entityClass, String query, Sort sort, Parameters params) {
return find(entityClass, query, sort, params.map());
}
public QueryType find(Class<?> entityClass, Bson query, Sort sort) {
MongoCollection collection = mongoCollection(entityClass);
Bson sortDoc = sortToDocument(sort);
ClientSession session = getSession(entityClass);
return createQuery(collection, session, query, sortDoc);
}
public QueryType find(Class<?> entityClass, Bson query, Bson sort) {
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return createQuery(collection, session, query, sort);
}
public QueryType find(Class<?> entityClass, Bson query) {
return find(entityClass, query, (Document) null);
}
public List<?> list(Class<?> entityClass, String query, Object... params) {
return list(find(entityClass, query, params));
}
public List<?> list(Class<?> entityClass, String query, Sort sort, Object... params) {
return list(find(entityClass, query, sort, params));
}
public List<?> list(Class<?> entityClass, String query, Map<String, Object> params) {
return list(find(entityClass, query, params));
}
public List<?> list(Class<?> entityClass, String query, Sort sort, Map<String, Object> params) {
return list(find(entityClass, query, sort, params));
}
public List<?> list(Class<?> entityClass, String query, Parameters params) {
return list(find(entityClass, query, params));
}
public List<?> list(Class<?> entityClass, String query, Sort sort, Parameters params) {
return list(find(entityClass, query, sort, params));
}
//specific Mongo query
public List<?> list(Class<?> entityClass, Bson query) {
return list(find(entityClass, query));
}
//specific Mongo query
public List<?> list(Class<?> entityClass, Bson query, Bson sort) {
return list(find(entityClass, query, sort));
}
public Stream<?> stream(Class<?> entityClass, String query, Object... params) {
return stream(find(entityClass, query, params));
}
public Stream<?> stream(Class<?> entityClass, String query, Sort sort, Object... params) {
return stream(find(entityClass, query, sort, params));
}
public Stream<?> stream(Class<?> entityClass, String query, Map<String, Object> params) {
return stream(find(entityClass, query, params));
}
public Stream<?> stream(Class<?> entityClass, String query, Sort sort, Map<String, Object> params) {
return stream(find(entityClass, query, sort, params));
}
public Stream<?> stream(Class<?> entityClass, String query, Parameters params) {
return stream(find(entityClass, query, params));
}
public Stream<?> stream(Class<?> entityClass, String query, Sort sort, Parameters params) {
return stream(find(entityClass, query, sort, params));
}
//specific Mongo query
public Stream<?> stream(Class<?> entityClass, Bson query) {
return stream(find(entityClass, query));
}
//specific Mongo query
public Stream<?> stream(Class<?> entityClass, Bson query, Bson sort) {
return stream(find(entityClass, query, sort));
}
public QueryType findAll(Class<?> entityClass) {
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return createQuery(collection, session, null, null);
}
public QueryType findAll(Class<?> entityClass, Sort sort) {
MongoCollection collection = mongoCollection(entityClass);
Bson sortDoc = sortToDocument(sort);
ClientSession session = getSession(entityClass);
return createQuery(collection, session, null, sortDoc);
}
private Bson sortToDocument(Sort sort) {
if (sort == null) {
return null;
}
Document sortDoc = new Document();
for (Sort.Column col : sort.getColumns()) {
sortDoc.append(col.getName(), col.getDirection() == Sort.Direction.Ascending ? 1 : -1);
if (col.getNullPrecedence() != null) {
throw new UnsupportedOperationException("Cannot sort by nulls first or nulls last");
}
}
return sortDoc;
}
public List<?> listAll(Class<?> entityClass) {
return list(findAll(entityClass));
}
public List<?> listAll(Class<?> entityClass, Sort sort) {
return list(findAll(entityClass, sort));
}
public Stream<?> streamAll(Class<?> entityClass) {
return stream(findAll(entityClass));
}
public Stream<?> streamAll(Class<?> entityClass, Sort sort) {
return stream(findAll(entityClass, sort));
}
public long count(Class<?> entityClass) {
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return session == null ? collection.countDocuments() : collection.countDocuments(session);
}
public long count(Class<?> entityClass, String query, Object... params) {
String bindQuery = bindFilter(entityClass, query, params);
BsonDocument docQuery = BsonDocument.parse(bindQuery);
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return session == null ? collection.countDocuments(docQuery) : collection.countDocuments(session, docQuery);
}
public long count(Class<?> entityClass, String query, Map<String, Object> params) {
String bindQuery = bindFilter(entityClass, query, params);
BsonDocument docQuery = BsonDocument.parse(bindQuery);
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return session == null ? collection.countDocuments(docQuery) : collection.countDocuments(session, docQuery);
}
public long count(Class<?> entityClass, String query, Parameters params) {
return count(entityClass, query, params.map());
}
//specific Mongo query
public long count(Class<?> entityClass, Bson query) {
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return session == null ? collection.countDocuments(query) : collection.countDocuments(session, query);
}
public long deleteAll(Class<?> entityClass) {
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return session == null ? collection.deleteMany(new Document()).getDeletedCount()
: collection.deleteMany(session, new Document()).getDeletedCount();
}
public boolean deleteById(Class<?> entityClass, Object id) {
MongoCollection collection = mongoCollection(entityClass);
Bson query = new Document().append(ID, id);
ClientSession session = getSession(entityClass);
DeleteResult results = session == null ? collection.deleteOne(query) : collection.deleteOne(session, query);
return results.getDeletedCount() == 1;
}
public long delete(Class<?> entityClass, String query, Object... params) {
String bindQuery = bindFilter(entityClass, query, params);
BsonDocument docQuery = BsonDocument.parse(bindQuery);
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return session == null ? collection.deleteMany(docQuery).getDeletedCount()
: collection.deleteMany(session, docQuery).getDeletedCount();
}
public long delete(Class<?> entityClass, String query, Map<String, Object> params) {
String bindQuery = bindFilter(entityClass, query, params);
BsonDocument docQuery = BsonDocument.parse(bindQuery);
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return session == null ? collection.deleteMany(docQuery).getDeletedCount()
: collection.deleteMany(session, docQuery).getDeletedCount();
}
public long delete(Class<?> entityClass, String query, Parameters params) {
return delete(entityClass, query, params.map());
}
//specific Mongo query
public long delete(Class<?> entityClass, Bson query) {
MongoCollection collection = mongoCollection(entityClass);
ClientSession session = getSession(entityClass);
return session == null ? collection.deleteMany(query).getDeletedCount()
: collection.deleteMany(session, query).getDeletedCount();
}
public UpdateType update(Class<?> entityClass, String update, Map<String, Object> params) {
return executeUpdate(entityClass, update, params);
}
public UpdateType update(Class<?> entityClass, String update, Parameters params) {
return update(entityClass, update, params.map());
}
public UpdateType update(Class<?> entityClass, String update, Object... params) {
return executeUpdate(entityClass, update, params);
}
public UpdateType update(Class<?> entityClass, Bson update) {
return createUpdate(mongoCollection(entityClass), entityClass, update);
}
private UpdateType executeUpdate(Class<?> entityClass, String update, Object... params) {
String bindUpdate = bindUpdate(entityClass, update, params);
Bson docUpdate = Document.parse(bindUpdate);
return createUpdate(mongoCollection(entityClass), entityClass, docUpdate);
}
private UpdateType executeUpdate(Class<?> entityClass, String update, Map<String, Object> params) {
String bindUpdate = bindUpdate(entityClass, update, params);
Bson docUpdate = Document.parse(bindUpdate);
return createUpdate(mongoCollection(entityClass), entityClass, docUpdate);
}
public IllegalStateException implementationInjectionMissing() {
return new IllegalStateException(
"This method is normally automatically overridden in subclasses");
}
}
| MongoOperations |
java | apache__rocketmq | common/src/main/java/org/apache/rocketmq/common/utils/BinaryUtil.java | {
"start": 1014,
"end": 2193
} | class ____ {
public static byte[] calculateMd5(byte[] binaryData) {
MessageDigest messageDigest = null;
try {
messageDigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 algorithm not found.");
}
messageDigest.update(binaryData);
return messageDigest.digest();
}
public static String generateMd5(String bodyStr) {
byte[] bytes = calculateMd5(bodyStr.getBytes(Charset.forName("UTF-8")));
return Hex.encodeHexString(bytes, false);
}
public static String generateMd5(byte[] content) {
byte[] bytes = calculateMd5(content);
return Hex.encodeHexString(bytes, false);
}
/**
* Returns true if subject contains only bytes that are spec-compliant ASCII characters.
* @param subject
* @return
*/
public static boolean isAscii(byte[] subject) {
if (subject == null) {
return false;
}
for (byte b : subject) {
if (b < 32 || b > 126) {
return false;
}
}
return true;
}
} | BinaryUtil |
java | junit-team__junit5 | platform-tests/src/test/java/org/junit/platform/suite/engine/SuiteLauncherDiscoveryRequestBuilderTests.java | {
"start": 21626,
"end": 21969
} | class ____ {
}
LauncherDiscoveryRequest request = builder.applySelectorsAndFiltersFromSuite(Suite.class).build();
List<UriSelector> selectors = request.getSelectorsByType(UriSelector.class);
assertEquals(URI.create("path/to/root"), exactlyOne(selectors).getUri());
}
@Test
void selectUrisFiltersEmptyUris() {
@SelectUris("")
| Suite |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/ReflectionOptimizerTest.java | {
"start": 3003,
"end": 3094
} | interface ____ {
String getProperty();
void setProperty(String property);
}
}
| Interface |
java | google__guice | extensions/throwingproviders/test/com/google/inject/throwingproviders/ThrowingProviderTest.java | {
"start": 34091,
"end": 34189
} | interface ____<T, P> extends ThrowingProvider<T, Exception> {}
private static | TooManyTypeParameters |
java | square__retrofit | retrofit/java-test/src/test/java/retrofit2/RequestFactoryTest.java | {
"start": 80159,
"end": 80594
} | class ____ {
@Multipart //
@POST("/foo/bar/") //
Call<ResponseBody> method(@Part("ping") RequestBody ping) {
return null;
}
}
try {
buildRequest(Example.class, new Object[] {null});
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage()).isEqualTo("Multipart body must have at least one part.");
}
}
@Test
public void simpleFormEncoded() {
| Example |
java | micronaut-projects__micronaut-core | http-client/src/main/java/io/micronaut/http/client/netty/DefaultHttpClientBuilder.java | {
"start": 2645,
"end": 10953
} | class ____ {
@Nullable
LoadBalancer loadBalancer = null;
@Nullable
HttpVersionSelection explicitHttpVersion = null;
HttpClientConfiguration configuration;
@Nullable
String contextPath = null;
@NonNull
AnnotationMetadataResolver annotationMetadataResolver = AnnotationMetadataResolver.DEFAULT;
HttpClientFilterResolver<ClientFilterResolutionContext> filterResolver;
List<HttpFilterResolver.FilterEntry> clientFilterEntries = null;
@Nullable
ThreadFactory threadFactory;
ClientSslBuilder nettyClientSslBuilder;
NettyClientSslFactory sslFactory;
BeanProvider<CertificateProvider> certificateProviders;
MediaTypeCodecRegistry codecRegistry;
MessageBodyHandlerRegistry handlerRegistry;
@NonNull
WebSocketBeanRegistry webSocketBeanRegistry = WebSocketBeanRegistry.EMPTY;
RequestBinderRegistry requestBinderRegistry;
@Nullable
EventLoopGroup eventLoopGroup = null;
@NonNull
ChannelFactory<? extends Channel> socketChannelFactory = NioSocketChannel::new;
@NonNull
ChannelFactory<? extends Channel> udpChannelFactory = NioDatagramChannel::new;
NettyClientCustomizer clientCustomizer = CompositeNettyClientCustomizer.EMPTY;
@Nullable
String informationalServiceId = null;
@NonNull
ConversionService conversionService = ConversionService.SHARED;
@Nullable
AddressResolverGroup<?> resolverGroup = null;
@Nullable
ExecutorService blockingExecutor = null;
DefaultHttpClientBuilder() {
}
@NonNull
DefaultHttpClientBuilder loadBalancer(@Nullable LoadBalancer loadBalancer) {
this.loadBalancer = loadBalancer;
return this;
}
/**
* Set the optional URI for this client to use as the root.
*
* @param uri The URI
* @return This builder
*/
@NonNull
public DefaultHttpClientBuilder uri(@Nullable URI uri) {
return loadBalancer(uri == null ? null : LoadBalancer.fixed(uri));
}
@NonNull
DefaultHttpClientBuilder explicitHttpVersion(@Nullable HttpVersionSelection explicitHttpVersion) {
this.explicitHttpVersion = explicitHttpVersion;
return this;
}
/**
* Set the configuration.
*
* @param configuration The client configuration
* @return This builder
*/
@NonNull
public DefaultHttpClientBuilder configuration(@NonNull HttpClientConfiguration configuration) {
ArgumentUtils.requireNonNull("configuration", configuration);
this.configuration = configuration;
return this;
}
@NonNull
DefaultHttpClientBuilder contextPath(@Nullable String contextPath) {
this.contextPath = contextPath;
return this;
}
@NonNull
DefaultHttpClientBuilder filterResolver(@NonNull HttpClientFilterResolver<ClientFilterResolutionContext> filterResolver) {
ArgumentUtils.requireNonNull("filterResolver", filterResolver);
this.filterResolver = filterResolver;
return this;
}
@NonNull
DefaultHttpClientBuilder annotationMetadataResolver(@Nullable AnnotationMetadataResolver annotationMetadataResolver) {
if (annotationMetadataResolver != null) {
this.annotationMetadataResolver = annotationMetadataResolver;
}
return this;
}
@NonNull
DefaultHttpClientBuilder filters(HttpClientFilter... filters) {
return filterResolver(new DefaultHttpClientFilterResolver(null, annotationMetadataResolver, Arrays.asList(filters)));
}
@NonNull
DefaultHttpClientBuilder clientFilterEntries(@Nullable List<HttpFilterResolver.FilterEntry> clientFilterEntries) {
this.clientFilterEntries = clientFilterEntries;
return this;
}
@NonNull
DefaultHttpClientBuilder threadFactory(@Nullable ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
return this;
}
/**
* The netty SSL context builder. Used by the micronaut-oracle-cloud OKE workload identity
* client.
*
* @param nettyClientSslBuilder The SSL context builder
* @return This builder
*/
@NonNull
public DefaultHttpClientBuilder nettyClientSslBuilder(@NonNull ClientSslBuilder nettyClientSslBuilder) {
ArgumentUtils.requireNonNull("nettyClientSslBuilder", nettyClientSslBuilder);
this.nettyClientSslBuilder = nettyClientSslBuilder;
return this;
}
@NonNull
public DefaultHttpClientBuilder sslFactory(@NonNull NettyClientSslFactory sslFactory, @NonNull BeanProvider<CertificateProvider> certificateProviders) {
ArgumentUtils.requireNonNull("sslFactory", sslFactory);
ArgumentUtils.requireNonNull("certificateProviders", certificateProviders);
this.sslFactory = sslFactory;
this.certificateProviders = certificateProviders;
return this;
}
/**
* Set the codec registry. This has mostly been replaced by body handlers by now.
*
* @param codecRegistry The codec registry
* @return This builder
* @deprecated Use body handlers instead
*/
@NonNull
@Deprecated
DefaultHttpClientBuilder codecRegistry(@NonNull MediaTypeCodecRegistry codecRegistry) {
ArgumentUtils.requireNonNull("codecRegistry", codecRegistry);
this.codecRegistry = codecRegistry;
return this;
}
@NonNull
DefaultHttpClientBuilder handlerRegistry(@NonNull MessageBodyHandlerRegistry handlerRegistry) {
ArgumentUtils.requireNonNull("handlerRegistry", handlerRegistry);
this.handlerRegistry = handlerRegistry;
return this;
}
@NonNull
DefaultHttpClientBuilder webSocketBeanRegistry(@NonNull WebSocketBeanRegistry webSocketBeanRegistry) {
ArgumentUtils.requireNonNull("webSocketBeanRegistry", webSocketBeanRegistry);
this.webSocketBeanRegistry = webSocketBeanRegistry;
return this;
}
@NonNull
DefaultHttpClientBuilder requestBinderRegistry(@NonNull RequestBinderRegistry requestBinderRegistry) {
ArgumentUtils.requireNonNull("requestBinderRegistry", requestBinderRegistry);
this.requestBinderRegistry = requestBinderRegistry;
return this;
}
@NonNull
DefaultHttpClientBuilder eventLoopGroup(@Nullable EventLoopGroup eventLoopGroup) {
this.eventLoopGroup = eventLoopGroup;
return this;
}
@NonNull
DefaultHttpClientBuilder socketChannelFactory(@NonNull ChannelFactory<? extends Channel> socketChannelFactory) {
ArgumentUtils.requireNonNull("socketChannelFactory", socketChannelFactory);
this.socketChannelFactory = socketChannelFactory;
return this;
}
@NonNull
DefaultHttpClientBuilder udpChannelFactory(@NonNull ChannelFactory<? extends Channel> udpChannelFactory) {
ArgumentUtils.requireNonNull("udpChannelFactory", udpChannelFactory);
this.udpChannelFactory = udpChannelFactory;
return this;
}
@NonNull
DefaultHttpClientBuilder clientCustomizer(@NonNull NettyClientCustomizer clientCustomizer) {
ArgumentUtils.requireNonNull("clientCustomizer", clientCustomizer);
this.clientCustomizer = clientCustomizer;
return this;
}
@NonNull
DefaultHttpClientBuilder informationalServiceId(@Nullable String informationalServiceId) {
this.informationalServiceId = informationalServiceId;
return this;
}
@NonNull
DefaultHttpClientBuilder conversionService(@NonNull ConversionService conversionService) {
ArgumentUtils.requireNonNull("conversionService", conversionService);
this.conversionService = conversionService;
return this;
}
@NonNull
DefaultHttpClientBuilder resolverGroup(@Nullable AddressResolverGroup<?> resolverGroup) {
this.resolverGroup = resolverGroup;
return this;
}
@NonNull
DefaultHttpClientBuilder blockingExecutor(@Nullable ExecutorService blockingExecutor) {
this.blockingExecutor = blockingExecutor;
return this;
}
/**
* Build the final HTTP client. This method may only be called once.
*
* @return The client
*/
@NonNull
public DefaultHttpClient build() {
return new DefaultHttpClient(this);
}
}
| DefaultHttpClientBuilder |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/boot/database/qualfiedTableNaming/DefaultCatalogAndSchemaTest.java | {
"start": 44822,
"end": 45127
} | class ____ {
public static final String NAME = "EntityWithHbmXmlNoFileLevelQualifiers";
private Long id;
private String basic;
}
@Entity(name = EntityWithJoinedInheritanceWithDefaultQualifiers.NAME)
@Inheritance(strategy = InheritanceType.JOINED)
public static | EntityWithHbmXmlNoFileLevelQualifiers |
java | netty__netty | codec-http2/src/main/java/io/netty/handler/codec/http2/Http2Frame.java | {
"start": 706,
"end": 835
} | interface ____ {
/**
* Returns the name of the HTTP/2 frame e.g. DATA, GOAWAY, etc.
*/
String name();
}
| Http2Frame |
java | google__dagger | javatests/dagger/internal/codegen/MultibindsValidationTest.java | {
"start": 1238,
"end": 6362
} | class ____ {
@Parameters(name = "{0}")
public static Collection<Object[]> parameters() {
return ImmutableList.copyOf(new Object[][] {{Module.class}, {ProducerModule.class}});
}
private final String moduleDeclaration;
public MultibindsValidationTest(Class<? extends Annotation> moduleAnnotation) {
moduleDeclaration = "@" + moduleAnnotation.getCanonicalName() + " abstract class %s { %s }";
}
@Test
public void notWithinModule() {
assertThatMethodInUnannotatedClass("@Multibinds abstract Set<Object> emptySet();")
.hasError("@Multibinds methods can only be present within a @Module or @ProducerModule");
}
@Test
public void voidMethod() {
assertThatModuleMethod("@Multibinds abstract void voidMethod();")
.withDeclaration(moduleDeclaration)
.hasError("@Multibinds methods return type must be either a Set or Map type.");
}
@Test
public void primitiveMethod() {
assertThatModuleMethod("@Multibinds abstract int primitive();")
.withDeclaration(moduleDeclaration)
.hasError("@Multibinds methods return type must be either a Set or Map type.");
}
@Test
public void rawMap() {
assertThatModuleMethod("@Multibinds abstract Map rawMap();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot be a raw Map type");
}
@Test
public void wildcardMapValue() {
assertThatModuleMethod("@Multibinds abstract Map<String, ?> wildcardMap();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot use a wildcard as the Map value type.");
}
@Test
public void wildcardMapValueWithBounds() {
assertThatModuleMethod("@Multibinds abstract Map<String, ? extends Number> wildcardMap();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot use a wildcard as the Map value type.");
}
@Test
public void wildcardMapKey() {
assertThatModuleMethod("@Multibinds abstract Map<?, String> wildcardMap();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot use a wildcard as the Map key type.");
}
@Test
public void wildcardMapKeyWithBounds() {
assertThatModuleMethod("@Multibinds abstract Map<? extends Number, String> wildcardMap();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot use a wildcard as the Map key type.");
}
@Test
public void providerMap() {
assertThatModuleMethod("@Multibinds abstract Map<String, Provider<Object>> providerMap();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot use 'Provider' in the Map value type.");
}
@Test
public void producerMap() {
assertThatModuleMethod("@Multibinds abstract Map<String, Producer<Object>> producerMap();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot use 'Producer' in the Map value type.");
}
@Test
public void producedMap() {
assertThatModuleMethod("@Multibinds abstract Map<String, Produced<Object>> producedMap();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot use 'Produced' in the Map value type.");
}
@Test
public void rawSet() {
assertThatModuleMethod("@Multibinds abstract Set rawSet();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot be a raw Set type");
}
@Test
public void wildcardSet() {
assertThatModuleMethod("@Multibinds abstract Set<?> wildcardSet();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot use a wildcard as the Set value type.");
}
@Test
public void wildcardSetWithBounds() {
assertThatModuleMethod("@Multibinds abstract Set<? extends Number> wildcardSet();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot use a wildcard as the Set value type.");
}
@Test
public void producedSet() {
assertThatModuleMethod("@Multibinds abstract Set<Produced<Object>> producedSet();")
.withDeclaration(moduleDeclaration)
.hasError("return type cannot use 'Produced' in the Set value type.");
}
@Test
public void overqualifiedSet() {
assertThatModuleMethod(
"@Multibinds @SomeQualifier @OtherQualifier "
+ "abstract Set<Object> tooManyQualifiersSet();")
.withDeclaration(moduleDeclaration)
.importing(SomeQualifier.class, OtherQualifier.class)
.hasError("may not use more than one @Qualifier");
}
@Test
public void overqualifiedMap() {
assertThatModuleMethod(
"@Multibinds @SomeQualifier @OtherQualifier "
+ "abstract Map<String, Object> tooManyQualifiersMap();")
.withDeclaration(moduleDeclaration)
.importing(SomeQualifier.class, OtherQualifier.class)
.hasError("may not use more than one @Qualifier");
}
@Test
public void hasParameters() {
assertThatModuleMethod("@Multibinds abstract Set<String> parameters(Object param);")
.hasError("@Multibinds methods cannot have parameters");
}
@Qualifier
public @ | MultibindsValidationTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/odps/OdpsFormatCommentTest25.java | {
"start": 121,
"end": 494
} | class ____ extends TestCase {
public void test_drop_function() throws Exception {
String sql = "-- xxx"
+ "\n -- yyy"
+ "\ndrop function if exists mytables;";
assertEquals("-- xxx"
+ "\n-- yyy"
+ "\nDROP FUNCTION IF EXISTS mytables;", SQLUtils.formatOdps(sql));
}
}
| OdpsFormatCommentTest25 |
java | mockito__mockito | mockito-extensions/mockito-junit-jupiter/src/test/java/org/mockitousage/GenericTypeMockTest.java | {
"start": 12998,
"end": 13037
} | class ____ {}
;
public | One |
java | apache__camel | core/camel-management/src/test/java/org/apache/camel/management/ManagedSendProcessorTest.java | {
"start": 1429,
"end": 3087
} | class ____ extends ManagementTestSupport {
@Test
public void testManageSendProcessor() throws Exception {
MockEndpoint result = getMockEndpoint("mock:result");
result.expectedMessageCount(1);
MockEndpoint foo = getMockEndpoint("mock:foo");
foo.expectedMessageCount(0);
template.sendBody("direct:start", "Hello World");
assertMockEndpointsSatisfied();
// get the stats for the route
MBeanServer mbeanServer = getMBeanServer();
// get the object name for the delayer
ObjectName on = getCamelObjectName(TYPE_PROCESSOR, "mysend");
// should be on route1
String routeId = (String) mbeanServer.getAttribute(on, "RouteId");
assertEquals("route1", routeId);
String camelId = (String) mbeanServer.getAttribute(on, "CamelId");
assertEquals(context.getManagementName(), camelId);
String state = (String) mbeanServer.getAttribute(on, "State");
assertEquals(ServiceStatus.Started.name(), state);
String destination = (String) mbeanServer.getAttribute(on, "Destination");
assertEquals("mock://result", destination);
String pattern = (String) mbeanServer.getAttribute(on, "MessageExchangePattern");
assertNull(pattern);
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.to("mock:result").id("mysend");
from("direct:foo").to("mock:foo");
}
};
}
}
| ManagedSendProcessorTest |
java | apache__hadoop | hadoop-common-project/hadoop-kms/src/test/java/org/apache/hadoop/crypto/key/kms/server/MiniKMS.java | {
"start": 1363,
"end": 5876
} | class ____ {
private File kmsConfDir;
private String log4jConfFile;
private File keyStoreFile;
private String keyStorePassword;
private int inPort;
public Builder() {
kmsConfDir = new File("target/test-classes").getAbsoluteFile();
log4jConfFile = "kms-log4j.properties";
}
public Builder setKmsConfDir(File confDir) {
Preconditions.checkNotNull(confDir, "KMS conf dir is NULL");
Preconditions.checkArgument(confDir.exists(),
"KMS conf dir does not exist");
kmsConfDir = confDir;
return this;
}
public Builder setLog4jConfFile(String log4jConfFile) {
Preconditions.checkNotNull(log4jConfFile, "log4jconf file is NULL");
this.log4jConfFile = log4jConfFile;
return this;
}
public Builder setPort(int port) {
Preconditions.checkArgument(port > 0, "input port must be greater than 0");
this.inPort = port;
return this;
}
public Builder setSslConf(File keyStoreFile, String keyStorePassword) {
Preconditions.checkNotNull(keyStoreFile, "keystore file is NULL");
Preconditions.checkNotNull(keyStorePassword, "keystore password is NULL");
Preconditions.checkArgument(keyStoreFile.exists(),
"keystore file does not exist");
this.keyStoreFile = keyStoreFile;
this.keyStorePassword = keyStorePassword;
return this;
}
public MiniKMS build() {
Preconditions.checkArgument(kmsConfDir.exists(),
"KMS conf dir does not exist");
return new MiniKMS(kmsConfDir.getAbsolutePath(), log4jConfFile,
(keyStoreFile != null) ? keyStoreFile.getAbsolutePath() : null,
keyStorePassword, inPort);
}
}
private String kmsConfDir;
private String log4jConfFile;
private String keyStore;
private String keyStorePassword;
private KMSWebServer jetty;
private int inPort;
private URL kmsURL;
public MiniKMS(String kmsConfDir, String log4ConfFile, String keyStore,
String password, int inPort) {
this.kmsConfDir = kmsConfDir;
this.log4jConfFile = log4ConfFile;
this.keyStore = keyStore;
this.keyStorePassword = password;
this.inPort = inPort;
}
private void copyResource(String inputResourceName, File outputFile) throws
IOException {
try (InputStream is = ThreadUtil.getResourceAsStream(inputResourceName);
OutputStream os = new FileOutputStream(outputFile)) {
IOUtils.copy(is, os);
}
}
public void start() throws Exception {
System.setProperty(KMSConfiguration.KMS_CONFIG_DIR, kmsConfDir);
File aclsFile = new File(kmsConfDir, "kms-acls.xml");
if (!aclsFile.exists()) {
copyResource("mini-kms-acls-default.xml", aclsFile);
}
File coreFile = new File(kmsConfDir, "core-site.xml");
if (!coreFile.exists()) {
Configuration core = new Configuration();
Writer writer = new FileWriter(coreFile);
core.writeXml(writer);
writer.close();
}
File kmsFile = new File(kmsConfDir, "kms-site.xml");
if (!kmsFile.exists()) {
Configuration kms = new Configuration(false);
kms.set(KMSConfiguration.KEY_PROVIDER_URI,
"jceks://file@" + new Path(kmsConfDir, "kms.keystore").toUri());
kms.set("hadoop.kms.authentication.type", "simple");
Writer writer = new FileWriter(kmsFile);
kms.writeXml(writer);
writer.close();
}
System.setProperty("log4j.configuration", log4jConfFile);
final Configuration conf = KMSConfiguration.getKMSConf();
conf.set(KMSConfiguration.HTTP_HOST_KEY, "localhost");
conf.setInt(KMSConfiguration.HTTP_PORT_KEY, inPort);
Configuration sslConf = null;
if (keyStore != null) {
conf.setBoolean(KMSConfiguration.SSL_ENABLED_KEY, true);
sslConf = SSLFactory.readSSLConfiguration(conf, SSLFactory.Mode.SERVER);
sslConf.set(SSLFactory.SSL_SERVER_KEYSTORE_LOCATION, keyStore);
sslConf.set(SSLFactory.SSL_SERVER_KEYSTORE_PASSWORD, keyStorePassword);
sslConf.set(SSLFactory.SSL_SERVER_KEYSTORE_TYPE, "jks");
}
jetty = new KMSWebServer(conf, sslConf);
jetty.start();
kmsURL = jetty.getKMSUrl();
}
public URL getKMSUrl() {
return kmsURL;
}
public void stop() {
if (jetty != null && jetty.isRunning()) {
try {
jetty.stop();
jetty = null;
} catch (Exception ex) {
throw new RuntimeException("Could not stop MiniKMS embedded Jetty, " +
ex.getMessage(), ex);
}
}
}
}
| Builder |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/token/InvalidateTokenResponse.java | {
"start": 842,
"end": 2011
} | class ____ extends ActionResponse implements ToXContentObject {
private TokensInvalidationResult result;
public InvalidateTokenResponse() {}
public InvalidateTokenResponse(StreamInput in) throws IOException {
result = new TokensInvalidationResult(in);
}
public InvalidateTokenResponse(TokensInvalidationResult result) {
this.result = result;
}
public TokensInvalidationResult getResult() {
return result;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
result.writeTo(out);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException {
result.toXContent(builder, params);
return builder;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
InvalidateTokenResponse that = (InvalidateTokenResponse) o;
return Objects.equals(result, that.result);
}
@Override
public int hashCode() {
return Objects.hash(result);
}
}
| InvalidateTokenResponse |
java | apache__camel | components/camel-infinispan/camel-infinispan-embedded/src/test/java/org/apache/camel/component/infinispan/embedded/cluster/InfinispanEmbeddedClusteredRoutePolicyFactoryTest.java | {
"start": 1181,
"end": 2760
} | class ____ extends AbstractInfinispanEmbeddedClusteredTest {
@Override
protected void run(DefaultCacheManager cacheContainer, String namespace, String id) throws Exception {
int events = ThreadLocalRandom.current().nextInt(2, 6);
CountDownLatch contextLatch = new CountDownLatch(events);
//Set up a single node cluster.
InfinispanEmbeddedClusterService clusterService = new InfinispanEmbeddedClusterService();
clusterService.setCacheContainer(cacheContainer);
clusterService.setId("node-" + id);
try (DefaultCamelContext context = new DefaultCamelContext()) {
context.disableJMX();
context.getCamelContextExtension().setName("context-" + id);
context.addService(clusterService);
context.addRoutePolicyFactory(ClusteredRoutePolicyFactory.forNamespace(namespace));
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
fromF("timer:%s?delay=1000&period=1000", id)
.routeId("route-" + id)
.log("From ${routeId}")
.process(e -> contextLatch.countDown());
}
});
// Start the context after some random time so the startup order
// changes for each test.
Thread.sleep(ThreadLocalRandom.current().nextInt(500));
context.start();
contextLatch.await();
}
}
}
| InfinispanEmbeddedClusteredRoutePolicyFactoryTest |
java | spring-projects__spring-boot | cli/spring-boot-cli/src/main/java/org/springframework/boot/cli/command/init/InitializrService.java | {
"start": 1796,
"end": 9099
} | class ____ {
private static final String FILENAME_HEADER_PREFIX = "filename=\"";
/**
* Accept header to use to retrieve the JSON meta-data.
*/
public static final String ACCEPT_META_DATA = "application/vnd.initializr.v2.1+"
+ "json,application/vnd.initializr.v2+json";
/**
* Accept header to use to retrieve the service capabilities of the service. If the
* service does not offer such feature, the JSON meta-data are retrieved instead.
*/
public static final String ACCEPT_SERVICE_CAPABILITIES = "text/plain," + ACCEPT_META_DATA;
/**
* Late binding HTTP client.
*/
private @Nullable HttpClient http;
InitializrService() {
}
InitializrService(HttpClient http) {
this.http = http;
}
protected HttpClient getHttp() {
if (this.http == null) {
this.http = HttpClientBuilder.create().useSystemProperties().build();
}
return this.http;
}
/**
* Generate a project based on the specified {@link ProjectGenerationRequest}.
* @param request the generation request
* @return an entity defining the project
* @throws IOException if generation fails
*/
ProjectGenerationResponse generate(ProjectGenerationRequest request) throws IOException {
Log.info("Using service at " + request.getServiceUrl());
InitializrServiceMetadata metadata = loadMetadata(request.getServiceUrl());
URI url = request.generateUrl(metadata);
ClassicHttpResponse httpResponse = executeProjectGenerationRequest(url);
HttpEntity httpEntity = httpResponse.getEntity();
validateResponse(httpResponse, request.getServiceUrl());
return createResponse(httpResponse, httpEntity);
}
/**
* Load the {@link InitializrServiceMetadata} at the specified url.
* @param serviceUrl to url of the initializer service
* @return the metadata describing the service
* @throws IOException if the service's metadata cannot be loaded
*/
InitializrServiceMetadata loadMetadata(String serviceUrl) throws IOException {
ClassicHttpResponse httpResponse = executeInitializrMetadataRetrieval(serviceUrl);
validateResponse(httpResponse, serviceUrl);
return parseJsonMetadata(httpResponse.getEntity());
}
/**
* Loads the service capabilities of the service at the specified URL. If the service
* supports generating a textual representation of the capabilities, it is returned,
* otherwise {@link InitializrServiceMetadata} is returned.
* @param serviceUrl to url of the initializer service
* @return the service capabilities (as a String) or the
* {@link InitializrServiceMetadata} describing the service
* @throws IOException if the service capabilities cannot be loaded
*/
Object loadServiceCapabilities(String serviceUrl) throws IOException {
HttpGet request = new HttpGet(serviceUrl);
request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_SERVICE_CAPABILITIES));
ClassicHttpResponse httpResponse = execute(request, URI.create(serviceUrl), "retrieve help");
validateResponse(httpResponse, serviceUrl);
HttpEntity httpEntity = httpResponse.getEntity();
ContentType contentType = ContentType.create(httpEntity.getContentType());
if (contentType.getMimeType().equals("text/plain")) {
return getContent(httpEntity);
}
return parseJsonMetadata(httpEntity);
}
private InitializrServiceMetadata parseJsonMetadata(HttpEntity httpEntity) throws IOException {
try {
return new InitializrServiceMetadata(getContentAsJson(httpEntity));
}
catch (JSONException ex) {
throw new ReportableException("Invalid content received from server (" + ex.getMessage() + ")", ex);
}
}
private void validateResponse(ClassicHttpResponse httpResponse, String serviceUrl) {
if (httpResponse.getEntity() == null) {
throw new ReportableException("No content received from server '" + serviceUrl + "'");
}
if (httpResponse.getCode() != 200) {
throw createException(serviceUrl, httpResponse);
}
}
private ProjectGenerationResponse createResponse(ClassicHttpResponse httpResponse, HttpEntity httpEntity)
throws IOException {
ProjectGenerationResponse response = new ProjectGenerationResponse(
ContentType.create(httpEntity.getContentType()));
response.setContent(FileCopyUtils.copyToByteArray(httpEntity.getContent()));
String fileName = extractFileName(httpResponse.getFirstHeader("Content-Disposition"));
if (fileName != null) {
response.setFileName(fileName);
}
return response;
}
/**
* Request the creation of the project using the specified URL.
* @param url the URL
* @return the response
*/
private ClassicHttpResponse executeProjectGenerationRequest(URI url) {
return execute(new HttpGet(url), url, "generate project");
}
/**
* Retrieves the meta-data of the service at the specified URL.
* @param url the URL
* @return the response
*/
private ClassicHttpResponse executeInitializrMetadataRetrieval(String url) {
HttpGet request = new HttpGet(url);
request.setHeader(new BasicHeader(HttpHeaders.ACCEPT, ACCEPT_META_DATA));
return execute(request, URI.create(url), "retrieve metadata");
}
private ClassicHttpResponse execute(HttpUriRequest request, URI url, String description) {
try {
HttpHost host = HttpHost.create(url);
request.addHeader("User-Agent", "SpringBootCli/" + getClass().getPackage().getImplementationVersion());
return getHttp().executeOpen(host, request, null);
}
catch (IOException ex) {
throw new ReportableException(
"Failed to " + description + " from service at '" + url + "' (" + ex.getMessage() + ")");
}
}
private ReportableException createException(String url, ClassicHttpResponse httpResponse) {
StatusLine statusLine = new StatusLine(httpResponse);
String message = "Initializr service call failed using '" + url + "' - service returned "
+ statusLine.getReasonPhrase();
String error = extractMessage(httpResponse.getEntity());
if (StringUtils.hasText(error)) {
message += ": '" + error + "'";
}
else {
int statusCode = statusLine.getStatusCode();
message += " (unexpected " + statusCode + " error)";
}
throw new ReportableException(message);
}
private @Nullable String extractMessage(@Nullable HttpEntity entity) {
if (entity != null) {
try {
JSONObject error = getContentAsJson(entity);
if (error.has("message")) {
return error.getString("message");
}
}
catch (Exception ex) {
// Ignore
}
}
return null;
}
private JSONObject getContentAsJson(HttpEntity entity) throws IOException, JSONException {
return new JSONObject(getContent(entity));
}
private String getContent(HttpEntity entity) throws IOException {
ContentType contentType = ContentType.create(entity.getContentType());
Charset charset = contentType.getCharset();
charset = (charset != null) ? charset : StandardCharsets.UTF_8;
byte[] content = FileCopyUtils.copyToByteArray(entity.getContent());
return new String(content, charset);
}
private @Nullable String extractFileName(@Nullable Header header) {
if (header != null) {
String value = header.getValue();
int start = value.indexOf(FILENAME_HEADER_PREFIX);
if (start != -1) {
value = value.substring(start + FILENAME_HEADER_PREFIX.length());
int end = value.indexOf('\"');
if (end != -1) {
return value.substring(0, end);
}
}
}
return null;
}
}
| InitializrService |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/bytecode/enhance/internal/bytebuddy/ModelTypePool.java | {
"start": 370,
"end": 4219
} | class ____ extends TypePool.Default implements EnhancerClassLocator {
private final EnhancerClassFileLocator locator;
private final EnhancerCacheProvider poolCache;
private ModelTypePool(EnhancerCacheProvider cacheProvider, EnhancerClassFileLocator classFileLocator, CoreTypePool parent) {
super( cacheProvider, classFileLocator, ReaderMode.FAST, parent );
this.poolCache = cacheProvider;
this.locator = classFileLocator;
}
/**
* Creates a new empty EnhancerClassLocator instance which will load any application
* classes that need being reflected on from the ClassLoader passed as parameter.
* This TypePool will delegate, parent first, to a newly constructed empty instance
* of CoreTypePool; this parent pool will be used to load non-application types from
* the Hibernate classloader instead, not the one specified as argument.
* @see CoreTypePool
* @param classLoader
* @return the newly created EnhancerClassLocator
*/
public static EnhancerClassLocator buildModelTypePool(ClassLoader classLoader) {
return buildModelTypePool( ClassFileLocator.ForClassLoader.of( classLoader ) );
}
/**
* Similar to {@link #buildModelTypePool(ClassLoader)} except the application classes
* are not necessarily sourced from a standard classloader: it accepts a {@link ClassFileLocator},
* which offers some more flexibility.
* @param classFileLocator
* @return the newly created EnhancerClassLocator
*/
public static EnhancerClassLocator buildModelTypePool(ClassFileLocator classFileLocator) {
return buildModelTypePool( classFileLocator, new CoreTypePool() );
}
/**
* Similar to {@link #buildModelTypePool(ClassFileLocator)} but allows specifying an existing
* {@link CoreTypePool} to be used as parent pool.
* This forms allows constructing a custom CoreTypePool and also separated the cache of the parent pool,
* which might be useful to reuse for multiple enhancement processes while desiring a clean new
* state for the {@link ModelTypePool}.
* @param classFileLocator
* @param coreTypePool
* @return
*/
public static EnhancerClassLocator buildModelTypePool(ClassFileLocator classFileLocator, CoreTypePool coreTypePool) {
return buildModelTypePool( classFileLocator, coreTypePool, new EnhancerCacheProvider() );
}
/**
* The more advanced strategy to construct a new ModelTypePool, allowing customization of all its aspects.
* @param classFileLocator
* @param coreTypePool
* @param cacheProvider
* @return
*/
static EnhancerClassLocator buildModelTypePool(ClassFileLocator classFileLocator, CoreTypePool coreTypePool, EnhancerCacheProvider cacheProvider) {
Objects.requireNonNull( classFileLocator );
Objects.requireNonNull( coreTypePool );
Objects.requireNonNull( cacheProvider );
return new ModelTypePool( cacheProvider, new EnhancerClassFileLocator( cacheProvider, classFileLocator ), coreTypePool );
}
@Override
public void registerClassNameAndBytes(final String className, final byte[] bytes) {
final EnhancerCacheProvider.EnhancementState currentEnhancementState = poolCache.getEnhancementState();
if ( currentEnhancementState != null ) {
throw new IllegalStateException( "Re-entrant enhancement is not supported: " + className );
}
final EnhancerCacheProvider.EnhancementState state = new EnhancerCacheProvider.EnhancementState(
className,
new ClassFileLocator.Resolution.Explicit( Objects.requireNonNull( bytes ) )
);
// Set the state first because the ClassFileLocator needs this in the doDescribe() call below
poolCache.setEnhancementState( state );
state.setTypePoolResolution( doDescribe( className ) );
}
@Override
public void deregisterClassNameAndBytes(String className) {
poolCache.removeEnhancementState();
}
@Override
public ClassFileLocator asClassFileLocator() {
return locator;
}
}
| ModelTypePool |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/internal/util/SerializationHelper.java | {
"start": 8493,
"end": 8642
} | class ____ initiated the deserialization call. Here
* that would be Hibernate classes. However, there are cases where that is not the correct
* | which |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/ProtectedMembersInFinalClassTest.java | {
"start": 2310,
"end": 2860
} | class ____ extends Base {
public void publicMethod() {}
void packageMethod() {}
private void privateMethod() {}
@Override
protected void protectedMethod() {}
public int publicField;
int packageField;
private int privateField;
}
""")
.doTest();
}
@Test
public void diagnosticStringWithMultipleMemberMatches() {
compilationHelper
.addSourceLines(
"in/Test.java",
"""
final | Test |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/AvroEndpointBuilderFactory.java | {
"start": 1436,
"end": 1569
} | interface ____ {
/**
* Builder for endpoint consumers for the Avro RPC component.
*/
public | AvroEndpointBuilderFactory |
java | hibernate__hibernate-orm | hibernate-envers/src/main/java/org/hibernate/envers/boot/model/BasicAttribute.java | {
"start": 1422,
"end": 2375
} | class ____
*/
public BasicAttribute(String name, String type, boolean insertable, boolean key, String explicitType) {
this( name, type, insertable, false, key, explicitType );
}
/**
* Create a basic attribute
*
* @param name the attribute name
* @param type the attribute type
* @param insertable whether the attribute is insertable
* @param updatable whether the attribute is updatable
* @param key whether the attribute participates in a key
*/
public BasicAttribute(String name, String type, boolean insertable, boolean updatable, boolean key) {
this( name, type, insertable, updatable, key, null );
}
/**
* Creates a basic attribute
*
* @param name the attribute name
* @param type the attribute type
* @param insertable whether the attribute is insertable
* @param updatable whether the attribute is updatable
* @param key whether the attribute participates in a key
* @param explicitType the explicit | type |
java | elastic__elasticsearch | x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/syncjob/action/ClaimConnectorSyncJobAction.java | {
"start": 1891,
"end": 5873
} | class ____ extends ConnectorSyncJobActionRequest implements ToXContentObject {
private final String connectorSyncJobId;
private final String workerHostname;
private final Object syncCursor;
public String getConnectorSyncJobId() {
return connectorSyncJobId;
}
public String getWorkerHostname() {
return workerHostname;
}
public Object getSyncCursor() {
return syncCursor;
}
public Request(StreamInput in) throws IOException {
super(in);
this.connectorSyncJobId = in.readString();
this.workerHostname = in.readString();
this.syncCursor = in.readGenericValue();
}
public Request(String connectorSyncJobId, String workerHostname, Object syncCursor) {
this.connectorSyncJobId = connectorSyncJobId;
this.workerHostname = workerHostname;
this.syncCursor = syncCursor;
}
private static final ConstructingObjectParser<Request, String> PARSER = new ConstructingObjectParser<>(
"claim_connector_sync_job",
false,
(args, connectorSyncJobId) -> {
String workerHostname = (String) args[0];
Object syncCursor = args[1];
return new Request(connectorSyncJobId, workerHostname, syncCursor);
}
);
static {
PARSER.declareString(constructorArg(), ConnectorSyncJob.WORKER_HOSTNAME_FIELD);
PARSER.declareObject(optionalConstructorArg(), (parser, context) -> parser.map(), Connector.SYNC_CURSOR_FIELD);
}
public static Request fromXContent(XContentParser parser, String connectorSyncJobId) throws IOException {
return PARSER.parse(parser, connectorSyncJobId);
}
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
builder.startObject();
{
builder.field(ConnectorSyncJob.WORKER_HOSTNAME_FIELD.getPreferredName(), workerHostname);
if (syncCursor != null) {
builder.field(Connector.SYNC_CURSOR_FIELD.getPreferredName(), syncCursor);
}
}
builder.endObject();
return builder;
}
@Override
public ActionRequestValidationException validate() {
ActionRequestValidationException validationException = null;
if (Strings.isNullOrEmpty(connectorSyncJobId)) {
validationException = addValidationError(
ConnectorSyncJobConstants.EMPTY_CONNECTOR_SYNC_JOB_ID_ERROR_MESSAGE,
validationException
);
}
if (workerHostname == null) {
validationException = addValidationError(
ConnectorSyncJobConstants.EMPTY_WORKER_HOSTNAME_ERROR_MESSAGE,
validationException
);
}
return validationException;
}
@Override
public void writeTo(StreamOutput out) throws IOException {
super.writeTo(out);
out.writeString(connectorSyncJobId);
out.writeString(workerHostname);
out.writeGenericValue(syncCursor);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Request request = (Request) o;
return Objects.equals(connectorSyncJobId, request.connectorSyncJobId)
&& Objects.equals(workerHostname, request.workerHostname)
&& Objects.equals(syncCursor, request.syncCursor);
}
@Override
public int hashCode() {
return Objects.hash(connectorSyncJobId, workerHostname, syncCursor);
}
}
}
| Request |
java | alibaba__nacos | istio/src/main/java/com/alibaba/nacos/istio/model/IstioService.java | {
"start": 929,
"end": 3652
} | class ____ {
private final String name;
private final String groupName;
private final String namespace;
private final Long revision;
private int port = 0;
private String protocol;
private final List<IstioEndpoint> hosts;
private final Date createTimeStamp;
public IstioService(Service service, ServiceInfo serviceInfo) {
this.name = serviceInfo.getName();
this.groupName = serviceInfo.getGroupName();
this.namespace = service.getNamespace();
this.revision = service.getRevision();
// Record the create time of service to avoid trigger istio pull push.
// See https://github.com/istio/istio/pull/30684
createTimeStamp = new Date();
this.hosts = sanitizeServiceInfo(serviceInfo);
}
public IstioService(Service service, ServiceInfo serviceInfo, IstioService old) {
this.name = serviceInfo.getName();
this.groupName = serviceInfo.getGroupName();
this.namespace = service.getNamespace();
this.revision = service.getRevision();
// set the create time of service as old time to avoid trigger istio pull push.
// See https://github.com/istio/istio/pull/30684
createTimeStamp = old.getCreateTimeStamp();
this.hosts = sanitizeServiceInfo(serviceInfo);
}
private List<IstioEndpoint> sanitizeServiceInfo(ServiceInfo serviceInfo) {
List<IstioEndpoint> hosts = new ArrayList<>();
for (Instance instance : serviceInfo.getHosts()) {
if (instance.isHealthy() && instance.isEnabled()) {
IstioEndpoint istioEndpoint = new IstioEndpoint(instance);
if (port == 0) {
port = istioEndpoint.getPort();
protocol = istioEndpoint.getProtocol();
}
hosts.add(istioEndpoint);
}
}
// Panic mode, all instances are invalid, to push all instances to istio.
if (hosts.isEmpty()) {
for (Instance instance : serviceInfo.getHosts()) {
IstioEndpoint istioEndpoint = new IstioEndpoint(instance);
hosts.add(istioEndpoint);
}
}
return hosts;
}
public String getNamespace() {
return namespace;
}
public Long getRevision() {
return revision;
}
public int getPort() {
return port;
}
public String getProtocol() {
return protocol;
}
public List<IstioEndpoint> getHosts() {
return hosts;
}
public Date getCreateTimeStamp() {
return createTimeStamp;
}
} | IstioService |
java | netty__netty | buffer/src/main/java/io/netty/buffer/search/KmpSearchProcessorFactory.java | {
"start": 1376,
"end": 3001
} | class ____ implements SearchProcessor {
private final byte[] needle;
private final int[] jumpTable;
private long currentPosition;
Processor(byte[] needle, int[] jumpTable) {
this.needle = needle;
this.jumpTable = jumpTable;
}
@Override
public boolean process(byte value) {
while (currentPosition > 0 && PlatformDependent.getByte(needle, currentPosition) != value) {
currentPosition = PlatformDependent.getInt(jumpTable, currentPosition);
}
if (PlatformDependent.getByte(needle, currentPosition) == value) {
currentPosition++;
}
if (currentPosition == needle.length) {
currentPosition = PlatformDependent.getInt(jumpTable, currentPosition);
return false;
}
return true;
}
@Override
public void reset() {
currentPosition = 0;
}
}
KmpSearchProcessorFactory(byte[] needle) {
this.needle = needle.clone();
this.jumpTable = new int[needle.length + 1];
int j = 0;
for (int i = 1; i < needle.length; i++) {
while (j > 0 && needle[j] != needle[i]) {
j = jumpTable[j];
}
if (needle[j] == needle[i]) {
j++;
}
jumpTable[i + 1] = j;
}
}
/**
* Returns a new {@link Processor}.
*/
@Override
public Processor newSearchProcessor() {
return new Processor(needle, jumpTable);
}
}
| Processor |
java | apache__flink | flink-table/flink-table-common/src/main/java/org/apache/flink/table/functions/FunctionDefinition.java | {
"start": 1517,
"end": 3591
} | interface ____ {
/** Returns the kind of function this definition describes. */
FunctionKind getKind();
/**
* Returns the logic for performing type inference of a call to this function definition.
*
* <p>The type inference process is responsible for inferring unknown types of input arguments,
* validating input arguments, and producing result types. The type inference process happens
* independent of a function body. The output of the type inference is used to search for a
* corresponding runtime implementation.
*
* <p>Instances of type inference can be created by using {@link TypeInference#newBuilder()}.
*
* <p>See {@link BuiltInFunctionDefinitions} for concrete usage examples.
*/
TypeInference getTypeInference(DataTypeFactory typeFactory);
/** Returns the set of requirements this definition demands. */
default Set<FunctionRequirement> getRequirements() {
return Collections.emptySet();
}
/**
* Returns information about the determinism of the function's results.
*
* <p>It returns <code>true</code> if and only if a call to this function is guaranteed to
* always return the same result given the same parameters. <code>true</code> is assumed by
* default. If the function is not purely functional like <code>random(), date(), now(), ...
* </code> this method must return <code>false</code>.
*
* <p>Furthermore, return <code>false</code> if the planner should always execute this function
* on the cluster side. In other words: the planner should not perform constant expression
* reduction during planning for constant calls to this function.
*/
default boolean isDeterministic() {
return true;
}
/**
* If the constant-folding should be run during planning time on calls to this function. If not,
* the expression will be left as-is and the call will be made during runtime.
*/
default boolean supportsConstantFolding() {
return true;
}
}
| FunctionDefinition |
java | redisson__redisson | redisson/src/main/java/org/redisson/codec/ReferenceCodecProvider.java | {
"start": 1078,
"end": 1288
} | class ____ to lookup the codec.
* @return the cached codec instance.
*/
<T extends Codec> T getCodec(Class<T> codecClass);
/**
* Get a codec instance by a REntity annotation and the | used |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-client/src/main/java/org/apache/hadoop/hdfs/web/WebHdfsFileSystem.java | {
"start": 24935,
"end": 25081
} | class ____ for initialing a HTTP connection, connecting to server,
* obtaining a response, and also handling retry on failures.
*/
abstract | is |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/downsample/DownsampleShardStatusSerializingTests.java | {
"start": 606,
"end": 4286
} | class ____ extends AbstractXContentSerializingTestCase<DownsampleShardStatus> {
@Override
protected DownsampleShardStatus doParseInstance(XContentParser parser) throws IOException {
return DownsampleShardStatus.fromXContent(parser);
}
@Override
protected Reader<DownsampleShardStatus> instanceReader() {
return DownsampleShardStatus::new;
}
@Override
protected DownsampleShardStatus createTestInstance() {
long docsProcessed = randomLongBetween(500_000, 800_000);
long indexEndTimeMillis = System.currentTimeMillis() + randomLongBetween(400_000, 500_000);
long indexStartTimeMillis = System.currentTimeMillis() - randomLongBetween(400_000, 500_000);
long lastIndexingTimestamp = System.currentTimeMillis() + randomLongBetween(200_000, 300_000);
long lastTargetTimestamp = System.currentTimeMillis() - randomLongBetween(200_000, 300_000);
long lastSourceTimestamp = System.currentTimeMillis();
long totalShardDocCount = randomLongBetween(500_000, 800_000);
long numFailed = randomNonNegativeLong();
long numIndexed = randomNonNegativeLong();
long numSent = randomNonNegativeLong();
long numReceived = randomNonNegativeLong();
long rollupStart = randomMillisUpToYear9999();
final ShardId shardId = new ShardId(randomAlphaOfLength(5), randomAlphaOfLength(5), randomInt(5));
final DownsampleShardIndexerStatus downsampleShardIndexerStatus = randomFrom(DownsampleShardIndexerStatus.values());
return new DownsampleShardStatus(
shardId,
rollupStart,
numReceived,
numSent,
numIndexed,
numFailed,
totalShardDocCount,
lastSourceTimestamp,
lastTargetTimestamp,
lastIndexingTimestamp,
indexStartTimeMillis,
indexEndTimeMillis,
docsProcessed,
100.0F * docsProcessed / totalShardDocCount,
createTestRollupBulkInfo(),
createTestBeforeBulkInfoInstance(),
createTestAfterBulkInfoInstance(),
downsampleShardIndexerStatus
);
}
private DownsampleBulkInfo createTestRollupBulkInfo() {
return new DownsampleBulkInfo(
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomNonNegativeLong()
);
}
private DownsampleBeforeBulkInfo createTestBeforeBulkInfoInstance() {
return new DownsampleBeforeBulkInfo(
System.currentTimeMillis(),
randomNonNegativeLong(),
randomNonNegativeLong(),
randomIntBetween(1, 10)
);
}
private DownsampleAfterBulkInfo createTestAfterBulkInfoInstance() {
int randomRestStatusCode = randomBoolean() ? RestStatus.OK.getStatus()
: randomBoolean() ? RestStatus.INTERNAL_SERVER_ERROR.getStatus()
: RestStatus.BAD_REQUEST.getStatus();
return new DownsampleAfterBulkInfo(
System.currentTimeMillis(),
randomLongBetween(1_000, 5_000),
randomLongBetween(1_000, 5_000),
randomLongBetween(1_000, 5_000),
randomBoolean(),
randomRestStatusCode
);
}
@Override
protected DownsampleShardStatus mutateInstance(DownsampleShardStatus instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
}
| DownsampleShardStatusSerializingTests |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/RssEndpointBuilderFactory.java | {
"start": 23217,
"end": 31361
} | interface ____
extends
EndpointConsumerBuilder {
default RssEndpointBuilder basic() {
return (RssEndpointBuilder) this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedRssEndpointBuilder bridgeErrorHandler(boolean bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* Allows for bridging the consumer to the Camel routing Error Handler,
* which mean any exceptions (if possible) occurred while the Camel
* consumer is trying to pickup incoming messages, or the likes, will
* now be processed as a message and handled by the routing Error
* Handler. Important: This is only possible if the 3rd party component
* allows Camel to be alerted if an exception was thrown. Some
* components handle this internally only, and therefore
* bridgeErrorHandler is not possible. In other situations we may
* improve the Camel component to hook into the 3rd party component and
* make this possible for future releases. By default the consumer will
* use the org.apache.camel.spi.ExceptionHandler to deal with
* exceptions, that will be logged at WARN or ERROR level and ignored.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: consumer (advanced)
*
* @param bridgeErrorHandler the value to set
* @return the dsl builder
*/
default AdvancedRssEndpointBuilder bridgeErrorHandler(String bridgeErrorHandler) {
doSetProperty("bridgeErrorHandler", bridgeErrorHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option is a: <code>org.apache.camel.spi.ExceptionHandler</code>
* type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedRssEndpointBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* To let the consumer use a custom ExceptionHandler. Notice if the
* option bridgeErrorHandler is enabled then this option is not in use.
* By default the consumer will deal with exceptions, that will be
* logged at WARN or ERROR level and ignored.
*
* The option will be converted to a
* <code>org.apache.camel.spi.ExceptionHandler</code> type.
*
* Group: consumer (advanced)
*
* @param exceptionHandler the value to set
* @return the dsl builder
*/
default AdvancedRssEndpointBuilder exceptionHandler(String exceptionHandler) {
doSetProperty("exceptionHandler", exceptionHandler);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option is a: <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedRssEndpointBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* Sets the exchange pattern when the consumer creates an exchange.
*
* The option will be converted to a
* <code>org.apache.camel.ExchangePattern</code> type.
*
* Group: consumer (advanced)
*
* @param exchangePattern the value to set
* @return the dsl builder
*/
default AdvancedRssEndpointBuilder exchangePattern(String exchangePattern) {
doSetProperty("exchangePattern", exchangePattern);
return this;
}
/**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option is a:
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*
* @param pollStrategy the value to set
* @return the dsl builder
*/
default AdvancedRssEndpointBuilder pollStrategy(org.apache.camel.spi.PollingConsumerPollStrategy pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
}
/**
* A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing
* you to provide your custom implementation to control error handling
* usually occurred during the poll operation before an Exchange have
* been created and being routed in Camel.
*
* The option will be converted to a
* <code>org.apache.camel.spi.PollingConsumerPollStrategy</code> type.
*
* Group: consumer (advanced)
*
* @param pollStrategy the value to set
* @return the dsl builder
*/
default AdvancedRssEndpointBuilder pollStrategy(String pollStrategy) {
doSetProperty("pollStrategy", pollStrategy);
return this;
}
/**
* Sets whether to add the feed object as a header.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param feedHeader the value to set
* @return the dsl builder
*/
default AdvancedRssEndpointBuilder feedHeader(boolean feedHeader) {
doSetProperty("feedHeader", feedHeader);
return this;
}
/**
* Sets whether to add the feed object as a header.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: advanced
*
* @param feedHeader the value to set
* @return the dsl builder
*/
default AdvancedRssEndpointBuilder feedHeader(String feedHeader) {
doSetProperty("feedHeader", feedHeader);
return this;
}
}
public | AdvancedRssEndpointBuilder |
java | quarkusio__quarkus | extensions/kubernetes/vanilla/deployment/src/main/java/io/quarkus/kubernetes/deployment/RemoveDeploymentTriggerDecorator.java | {
"start": 386,
"end": 1057
} | class ____ extends NamedResourceDecorator<DeploymentConfigSpecFluent<?>> {
public RemoveDeploymentTriggerDecorator(String name) {
super(name);
}
@Override
public void andThenVisit(DeploymentConfigSpecFluent<?> deploymentConfigSpec, ObjectMeta objectMeta) {
deploymentConfigSpec.withTriggers(Collections.emptyList());
}
@Override
public Class<? extends Decorator>[] after() {
return new Class[] { ApplyDeploymentTriggerDecorator.class };
}
@Override
public Class<? extends Decorator>[] before() {
return new Class[] { ChangeDeploymentTriggerDecorator.class };
}
}
| RemoveDeploymentTriggerDecorator |
java | apache__kafka | connect/runtime/src/main/java/org/apache/kafka/connect/runtime/TaskStatus.java | {
"start": 1321,
"end": 2763
} | interface ____ {
/**
* Invoked after successful startup of the task.
* @param id The id of the task
*/
void onStartup(ConnectorTaskId id);
/**
* Invoked after the task has been paused.
* @param id The id of the task
*/
void onPause(ConnectorTaskId id);
/**
* Invoked after the task has been resumed.
* @param id The id of the task
*/
void onResume(ConnectorTaskId id);
/**
* Invoked if the task raises an error. No shutdown event will follow.
* @param id The id of the task
* @param cause The error raised by the task.
*/
void onFailure(ConnectorTaskId id, Throwable cause);
/**
* Invoked after successful shutdown of the task.
* @param id The id of the task
*/
void onShutdown(ConnectorTaskId id);
/**
* Invoked after the task has been deleted. Can be called if the
* connector tasks have been reduced, or if the connector itself has
* been deleted.
* @param id The id of the task
*/
void onDeletion(ConnectorTaskId id);
/**
* Invoked when the task is restarted asynchronously by the herder on processing a restart request.
* @param id The id of the task
*/
void onRestart(ConnectorTaskId id);
}
}
| Listener |
java | elastic__elasticsearch | x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/operator/OperatorPrivileges.java | {
"start": 4095,
"end": 11360
} | class ____ implements OperatorPrivilegesService {
private final FileOperatorUsersStore fileOperatorUsersStore;
private final OperatorOnlyRegistry operatorOnlyRegistry;
private final XPackLicenseState licenseState;
public DefaultOperatorPrivilegesService(
XPackLicenseState licenseState,
FileOperatorUsersStore fileOperatorUsersStore,
OperatorOnlyRegistry operatorOnlyRegistry
) {
this.fileOperatorUsersStore = fileOperatorUsersStore;
this.operatorOnlyRegistry = operatorOnlyRegistry;
this.licenseState = licenseState;
}
public void maybeMarkOperatorUser(Authentication authentication, ThreadContext threadContext) {
// Always mark the thread context for operator users regardless of license state which is enforced at check time
final User user = authentication.getEffectiveSubject().getUser();
// Let internal users pass, and mark him as an operator
// Also check run_as, it is impossible to run_as internal users, but just to be extra safe
// mark internalUser with operator privileges
if (user instanceof InternalUser && false == authentication.isRunAs()) {
if (threadContext.getHeader(AuthenticationField.PRIVILEGE_CATEGORY_KEY) == null) {
threadContext.putHeader(
AuthenticationField.PRIVILEGE_CATEGORY_KEY,
AuthenticationField.PRIVILEGE_CATEGORY_VALUE_OPERATOR
);
}
return;
}
// The header is already set by previous authentication either on this node or a remote node
if (threadContext.getHeader(AuthenticationField.PRIVILEGE_CATEGORY_KEY) != null) {
return;
}
// An operator user must not be a run_as user, it also must be recognised by the operatorUserStore
if (false == authentication.isRunAs() && fileOperatorUsersStore.isOperatorUser(authentication)) {
logger.debug("Marking user [{}] as an operator", user);
threadContext.putHeader(AuthenticationField.PRIVILEGE_CATEGORY_KEY, AuthenticationField.PRIVILEGE_CATEGORY_VALUE_OPERATOR);
} else {
threadContext.putHeader(AuthenticationField.PRIVILEGE_CATEGORY_KEY, AuthenticationField.PRIVILEGE_CATEGORY_VALUE_EMPTY);
}
}
public ElasticsearchSecurityException check(
Authentication authentication,
String action,
TransportRequest request,
ThreadContext threadContext
) {
if (false == shouldProcess()) {
return null;
}
final User user = authentication.getEffectiveSubject().getUser();
// internal user is also an operator
if (false == isOperator(threadContext)) {
// Only check whether request is operator-only when user is NOT an operator
logger.trace("Checking operator-only violation for user [{}] and action [{}]", user, action);
final OperatorPrivilegesViolation violation = operatorOnlyRegistry.check(action, request);
if (violation != null) {
return new ElasticsearchSecurityException("Operator privileges are required for " + violation.message());
}
}
return null;
}
@Override
public boolean checkRest(RestHandler restHandler, RestRequest restRequest, RestChannel restChannel, ThreadContext threadContext) {
if (false == shouldProcess()) {
return true;
}
if (false == isOperator(threadContext)) {
// Only check whether request is operator-only when user is NOT an operator
if (logger.isTraceEnabled()) {
final User user = getUser(threadContext);
logger.trace("Checking for any operator-only REST violations for user [{}] and uri [{}]", user, restRequest.uri());
}
try {
operatorOnlyRegistry.checkRest(restHandler, restRequest);
} catch (ElasticsearchException e) {
if (logger.isDebugEnabled()) {
logger.debug(
"Found the following operator-only violation [{}] for user [{}] and uri [{}]",
e.getMessage(),
getUser(threadContext),
restRequest.uri()
);
}
throw e;
} catch (Exception e) {
logger.info(
"Unexpected exception [{}] while processing operator privileges for user [{}] and uri [{}]",
e.getMessage(),
getUser(threadContext),
restRequest.uri()
);
throw e;
}
} else {
restRequest.markAsOperatorRequest();
logger.trace("Marked request for uri [{}] as operator request", restRequest.uri());
}
return true;
}
private static User getUser(ThreadContext threadContext) {
Authentication authentication = threadContext.getTransient(AuthenticationField.AUTHENTICATION_KEY);
return authentication.getEffectiveSubject().getUser();
}
public void maybeInterceptRequest(ThreadContext threadContext, TransportRequest request) {
if (request instanceof RestoreSnapshotRequest) {
logger.debug("Intercepting [{}] for operator privileges", request);
((RestoreSnapshotRequest) request).skipOperatorOnlyState(shouldProcess());
}
}
private boolean shouldProcess() {
return Security.OPERATOR_PRIVILEGES_FEATURE.check(licenseState);
}
// for testing
public OperatorOnlyRegistry getOperatorOnlyRegistry() {
return operatorOnlyRegistry;
}
}
public static final OperatorPrivilegesService NOOP_OPERATOR_PRIVILEGES_SERVICE = new OperatorPrivilegesService() {
@Override
public void maybeMarkOperatorUser(Authentication authentication, ThreadContext threadContext) {}
@Override
public ElasticsearchSecurityException check(
Authentication authentication,
String action,
TransportRequest request,
ThreadContext threadContext
) {
return null;
}
@Override
public boolean checkRest(RestHandler restHandler, RestRequest restRequest, RestChannel restChannel, ThreadContext threadContext) {
return true;
}
@Override
public void maybeInterceptRequest(ThreadContext threadContext, TransportRequest request) {
if (request instanceof RestoreSnapshotRequest) {
((RestoreSnapshotRequest) request).skipOperatorOnlyState(false);
}
}
};
}
| DefaultOperatorPrivilegesService |
java | elastic__elasticsearch | modules/mapper-extras/src/main/java/org/elasticsearch/index/mapper/extras/ScaledFloatFieldMapper.java | {
"start": 29510,
"end": 31847
} | class ____ extends IndexNumericFieldData {
private final IndexNumericFieldData scaledFieldData;
private final double scalingFactor;
private final ToScriptFieldFactory<SortedNumericDoubleValues> toScriptFieldFactory;
ScaledFloatIndexFieldData(
IndexNumericFieldData scaledFieldData,
double scalingFactor,
ToScriptFieldFactory<SortedNumericDoubleValues> toScriptFieldFactory
) {
this.scaledFieldData = scaledFieldData;
this.scalingFactor = scalingFactor;
this.toScriptFieldFactory = toScriptFieldFactory;
}
@Override
public String getFieldName() {
return scaledFieldData.getFieldName();
}
@Override
public ValuesSourceType getValuesSourceType() {
return scaledFieldData.getValuesSourceType();
}
@Override
public LeafNumericFieldData load(LeafReaderContext context) {
return new ScaledFloatLeafFieldData(scaledFieldData.load(context), scalingFactor, toScriptFieldFactory);
}
@Override
public LeafNumericFieldData loadDirect(LeafReaderContext context) throws Exception {
return new ScaledFloatLeafFieldData(scaledFieldData.loadDirect(context), scalingFactor, toScriptFieldFactory);
}
@Override
protected boolean sortRequiresCustomComparator() {
/*
* We need to use a custom comparator because the non-custom
* comparator wouldn't properly decode the long bits into the
* double. Sorting on the long representation *would* put the
* docs in order. We just don't have a way to convert the long
* into a double the right way afterwords.
*/
return true;
}
@Override
protected IndexType indexType() {
return IndexType.NONE; // We don't know how to take advantage of the index with half floats anyway
}
@Override
public NumericType getNumericType() {
/*
* {@link ScaledFloatLeafFieldData#getDoubleValues()} transforms the raw long values in `scaled` floats.
*/
return NumericType.DOUBLE;
}
}
private static | ScaledFloatIndexFieldData |
java | elastic__elasticsearch | x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/datafeed/extractor/aggregation/CompositeAggregationDataExtractorTests.java | {
"start": 3232,
"end": 18958
} | class ____ extends ESTestCase {
private Client client;
private String jobId;
private String timeField;
private Set<String> fields;
private List<String> indices;
private QueryBuilder query;
private DatafeedTimingStatsReporter timingStatsReporter;
private CompositeAggregationBuilder compositeAggregationBuilder;
private AggregatedSearchRequestBuilder aggregatedSearchRequestBuilder;
private Map<String, Object> runtimeMappings;
@Before
public void setUpTests() {
client = mock(Client.class);
when(client.threadPool()).thenReturn(mock(ThreadPool.class));
when(client.threadPool().getThreadContext()).thenReturn(new ThreadContext(Settings.EMPTY));
jobId = "test-job";
timeField = "time";
fields = new HashSet<>();
fields.addAll(Arrays.asList("time", "airline", "responsetime"));
indices = Arrays.asList("index-1", "index-2");
query = QueryBuilders.matchAllQuery();
compositeAggregationBuilder = AggregationBuilders.composite(
"buckets",
Arrays.asList(
new DateHistogramValuesSourceBuilder("time_bucket").field("time").fixedInterval(new DateHistogramInterval("1000ms")),
new TermsValuesSourceBuilder("airline").field("airline")
)
)
.size(10)
.subAggregation(AggregationBuilders.max("time").field("time"))
.subAggregation(AggregationBuilders.avg("responsetime").field("responsetime"));
runtimeMappings = Collections.emptyMap();
timingStatsReporter = mock(DatafeedTimingStatsReporter.class);
aggregatedSearchRequestBuilder = (searchSourceBuilder) -> new SearchRequestBuilder(client).setSource(searchSourceBuilder)
.setAllowPartialSearchResults(false)
.setIndices(indices.toArray(String[]::new));
}
public void testExtraction() throws IOException {
List<InternalComposite.InternalBucket> compositeBucket = Arrays.asList(
createCompositeBucket(
1000L,
"time_bucket",
1,
Arrays.asList(createMax("time", 1999), createAvg("responsetime", 11.0)),
Collections.singletonList(Tuple.tuple("airline", "a"))
),
createCompositeBucket(
1000L,
"time_bucket",
2,
Arrays.asList(createMax("time", 1999), createAvg("responsetime", 12.0)),
Collections.singletonList(Tuple.tuple("airline", "b"))
),
createCompositeBucket(2000L, "time_bucket", 0, Collections.emptyList(), Collections.emptyList()),
createCompositeBucket(
3000L,
"time_bucket",
4,
Arrays.asList(createMax("time", 3999), createAvg("responsetime", 31.0)),
Collections.singletonList(Tuple.tuple("airline", "c"))
),
createCompositeBucket(
3000L,
"time_bucket",
3,
Arrays.asList(createMax("time", 3999), createAvg("responsetime", 32.0)),
Collections.singletonList(Tuple.tuple("airline", "b"))
)
);
CompositeAggregationDataExtractor extractor = new CompositeAggregationDataExtractor(
compositeAggregationBuilder,
client,
createContext(1000L, 4000L),
timingStatsReporter,
aggregatedSearchRequestBuilder
);
ArgumentCaptor<SearchRequest> searchRequestCaptor = ArgumentCaptor.forClass(SearchRequest.class);
ActionFuture<SearchResponse> searchResponse = toActionFuture(
createSearchResponse("buckets", compositeBucket, Map.of("time_bucket", 4000L, "airline", "d"))
);
when(client.execute(eq(TransportSearchAction.TYPE), searchRequestCaptor.capture())).thenReturn(searchResponse);
assertThat(extractor.hasNext(), is(true));
DataExtractor.Result result = extractor.next();
assertThat(result.searchInterval(), equalTo(new SearchInterval(1000L, 4000L)));
Optional<InputStream> stream = result.data();
assertThat(stream.isPresent(), is(true));
String expectedStream = """
{"airline":"a","time":1999,"responsetime":11.0,"doc_count":1} \
{"airline":"b","time":1999,"responsetime":12.0,"doc_count":2} \
{"airline":"c","time":3999,"responsetime":31.0,"doc_count":4} \
{"airline":"b","time":3999,"responsetime":32.0,"doc_count":3}""";
assertThat(asString(stream.get()), equalTo(expectedStream));
String searchRequest = searchRequestCaptor.getValue().toString().replaceAll("\\s", "");
assertThat(searchRequest, containsString("\"size\":0"));
assertThat(
searchRequest,
containsString(
"\"query\":{\"bool\":{\"filter\":[{\"match_all\":{\"boost\":1.0}},"
+ "{\"range\":{\"time\":{\"gte\":1000,\"lt\":4000,"
+ "\"format\":\"epoch_millis\",\"boost\":1.0}}}]"
)
);
assertThat(
searchRequest,
stringContainsInOrder(Arrays.asList("aggregations", "composite", "time", "terms", "airline", "avg", "responsetime"))
);
}
public void testExtractionGivenResponseHasNullAggs() throws IOException {
CompositeAggregationDataExtractor extractor = new CompositeAggregationDataExtractor(
compositeAggregationBuilder,
client,
createContext(1000L, 2000L),
timingStatsReporter,
aggregatedSearchRequestBuilder
);
ActionFuture<SearchResponse> searchResponse = toActionFuture(createSearchResponse(null));
when(client.execute(eq(TransportSearchAction.TYPE), any())).thenReturn(searchResponse);
assertThat(extractor.hasNext(), is(true));
assertThat(extractor.next().data().isPresent(), is(false));
assertThat(extractor.hasNext(), is(false));
verify(client).execute(eq(TransportSearchAction.TYPE), any());
}
public void testExtractionGivenResponseHasEmptyAggs() throws IOException {
CompositeAggregationDataExtractor extractor = new CompositeAggregationDataExtractor(
compositeAggregationBuilder,
client,
createContext(1000L, 2000L),
timingStatsReporter,
aggregatedSearchRequestBuilder
);
InternalAggregations emptyAggs = AggregationTestUtils.createAggs(Collections.emptyList());
ActionFuture<SearchResponse> searchResponse = toActionFuture(createSearchResponse(emptyAggs));
when(client.execute(eq(TransportSearchAction.TYPE), any())).thenReturn(searchResponse);
assertThat(extractor.hasNext(), is(true));
assertThat(extractor.next().data().isPresent(), is(false));
assertThat(extractor.hasNext(), is(false));
verify(client).execute(eq(TransportSearchAction.TYPE), any());
}
public void testExtractionGivenCancelBeforeNext() {
CompositeAggregationDataExtractor extractor = new CompositeAggregationDataExtractor(
compositeAggregationBuilder,
client,
createContext(1000L, 4000L),
timingStatsReporter,
aggregatedSearchRequestBuilder
);
ActionFuture<SearchResponse> searchResponse = toActionFuture(
createSearchResponse("time", Collections.emptyList(), Collections.emptyMap())
);
when(client.execute(eq(TransportSearchAction.TYPE), any())).thenReturn(searchResponse);
extractor.cancel();
// Composite aggs should be true because we need to make sure the first search has occurred or not
assertThat(extractor.hasNext(), is(true));
}
public void testExtractionCancelOnFirstPage() throws IOException {
int numBuckets = 10;
List<InternalComposite.InternalBucket> buckets = new ArrayList<>(numBuckets);
long timestamp = 1000;
for (int i = 0; i < numBuckets; i++) {
buckets.add(
createCompositeBucket(
timestamp,
"time_bucket",
3,
Arrays.asList(createMax("time", randomLongBetween(timestamp, timestamp + 1000)), createAvg("responsetime", 32.0)),
Collections.singletonList(Tuple.tuple("airline", "c"))
)
);
}
CompositeAggregationDataExtractor extractor = new CompositeAggregationDataExtractor(
compositeAggregationBuilder,
client,
createContext(1000L, timestamp + 1000 + 1),
timingStatsReporter,
aggregatedSearchRequestBuilder
);
ActionFuture<SearchResponse> searchResponse = toActionFuture(
createSearchResponse("buckets", buckets, Map.of("time_bucket", 1000L, "airline", "d"))
);
when(client.execute(eq(TransportSearchAction.TYPE), any())).thenReturn(searchResponse);
extractor.cancel();
// We should have next right now as we have not yet determined if we have handled a page or not
assertThat(extractor.hasNext(), is(true));
// Should be empty
assertThat(countMatches('{', asString(extractor.next().data().get())), equalTo(0L));
// Determined that we were on the first page and ended
assertThat(extractor.hasNext(), is(false));
}
public void testExtractionGivenCancelHalfWay() throws IOException {
int numBuckets = 10;
List<InternalComposite.InternalBucket> buckets = new ArrayList<>(numBuckets);
long timestamp = 1000;
for (int i = 0; i < numBuckets; i++) {
buckets.add(
createCompositeBucket(
timestamp,
"time_bucket",
3,
Arrays.asList(createMax("time", randomLongBetween(timestamp, timestamp + 999)), createAvg("responsetime", 32.0)),
Collections.singletonList(Tuple.tuple("airline", "c"))
)
);
}
CompositeAggregationDataExtractor extractor = new CompositeAggregationDataExtractor(
compositeAggregationBuilder,
client,
createContext(1000L, timestamp + 1000 + 1),
timingStatsReporter,
aggregatedSearchRequestBuilder
);
ActionFuture<SearchResponse> searchResponse = toActionFuture(
createSearchResponse("buckets", buckets, Map.of("time_bucket", 1000L, "airline", "d"))
);
when(client.execute(eq(TransportSearchAction.TYPE), any())).thenReturn(searchResponse);
assertThat(extractor.hasNext(), is(true));
assertThat(countMatches('{', asString(extractor.next().data().get())), equalTo(10L));
buckets = new ArrayList<>(numBuckets);
for (int i = 0; i < 6; i++) {
buckets.add(
createCompositeBucket(
timestamp,
"time_bucket",
3,
Arrays.asList(createMax("time", randomLongBetween(timestamp, timestamp + 999)), createAvg("responsetime", 32.0)),
Collections.singletonList(Tuple.tuple("airline", "c"))
)
);
}
timestamp += 1000;
for (int i = 0; i < 4; i++) {
buckets.add(
createCompositeBucket(
timestamp,
"time_bucket",
3,
Arrays.asList(createMax("time", randomLongBetween(timestamp, timestamp + 999)), createAvg("responsetime", 32.0)),
Collections.singletonList(Tuple.tuple("airline", "c"))
)
);
}
searchResponse = toActionFuture(createSearchResponse("buckets", buckets, Map.of("time_bucket", 3000L, "airline", "a")));
when(client.execute(eq(TransportSearchAction.TYPE), any())).thenReturn(searchResponse);
extractor.cancel();
assertThat(extractor.hasNext(), is(true));
assertThat(extractor.isCancelled(), is(true));
// Only the docs in the previous bucket before cancelling
assertThat(countMatches('{', asString(extractor.next().data().get())), equalTo(6L));
// Once we have handled the 6 remaining in that time bucket, we shouldn't finish the page and the extractor should end
assertThat(extractor.hasNext(), is(false));
verify(client, times(2)).execute(eq(TransportSearchAction.TYPE), any());
}
public void testExtractionGivenSearchResponseHasError() {
CompositeAggregationDataExtractor extractor = new CompositeAggregationDataExtractor(
compositeAggregationBuilder,
client,
createContext(1000L, 2000L),
timingStatsReporter,
aggregatedSearchRequestBuilder
);
when(client.execute(eq(TransportSearchAction.TYPE), any())).thenThrow(
new SearchPhaseExecutionException("phase 1", "boom", ShardSearchFailure.EMPTY_ARRAY)
);
assertThat(extractor.hasNext(), is(true));
expectThrows(SearchPhaseExecutionException.class, extractor::next);
}
private CompositeAggregationDataExtractorContext createContext(long start, long end) {
return new CompositeAggregationDataExtractorContext(
jobId,
timeField,
fields,
indices,
query,
compositeAggregationBuilder,
"time_bucket",
start,
end,
true,
Collections.emptyMap(),
SearchRequest.DEFAULT_INDICES_OPTIONS,
runtimeMappings
);
}
private <T> ActionFuture<T> toActionFuture(T t) {
@SuppressWarnings("unchecked")
ActionFuture<T> future = (ActionFuture<T>) mock(ActionFuture.class);
when(future.actionGet()).thenReturn(t);
return future;
}
private SearchResponse createSearchResponse(
String aggName,
List<InternalComposite.InternalBucket> buckets,
Map<String, Object> afterKey
) {
InternalComposite compositeAggregation = mock(InternalComposite.class);
when(compositeAggregation.getName()).thenReturn(aggName);
when(compositeAggregation.afterKey()).thenReturn(afterKey);
when(compositeAggregation.getBuckets()).thenReturn(buckets);
InternalAggregations searchAggs = AggregationTestUtils.createAggs(Collections.singletonList(compositeAggregation));
return createSearchResponse(searchAggs);
}
private SearchResponse createSearchResponse(InternalAggregations aggregations) {
SearchResponse searchResponse = mock(SearchResponse.class);
when(searchResponse.status()).thenReturn(RestStatus.OK);
when(searchResponse.getScrollId()).thenReturn(randomAlphaOfLength(1000));
when(searchResponse.getAggregations()).thenReturn(aggregations);
when(searchResponse.getTook()).thenReturn(TimeValue.timeValueMillis(randomNonNegativeLong()));
return searchResponse;
}
private static String asString(InputStream inputStream) throws IOException {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
return reader.lines().collect(Collectors.joining("\n"));
}
}
private static long countMatches(char c, String text) {
return text.chars().filter(current -> current == c).count();
}
}
| CompositeAggregationDataExtractorTests |
java | apache__kafka | clients/src/test/java/org/apache/kafka/clients/producer/internals/ProducerBatchTest.java | {
"start": 16824,
"end": 17204
} | class ____ implements Callback {
private int invocations = 0;
private RecordMetadata metadata;
private Exception exception;
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
invocations++;
this.metadata = metadata;
this.exception = exception;
}
}
}
| MockCallback |
java | elastic__elasticsearch | x-pack/plugin/rank-rrf/src/main/java/org/elasticsearch/xpack/rank/RankRRFFeatures.java | {
"start": 973,
"end": 2118
} | class ____ implements FeatureSpecification {
public static final NodeFeature LINEAR_RETRIEVER_SUPPORTED = new NodeFeature("linear_retriever_supported");
public static final NodeFeature LINEAR_RETRIEVER_TOP_LEVEL_NORMALIZER = new NodeFeature("linear_retriever.top_level_normalizer");
@Override
public Set<NodeFeature> getFeatures() {
return Set.of(LINEAR_RETRIEVER_SUPPORTED);
}
@Override
public Set<NodeFeature> getTestFeatures() {
return Set.of(
INNER_RETRIEVERS_FILTER_SUPPORT,
LINEAR_RETRIEVER_MINMAX_SINGLE_DOC_FIX,
LINEAR_RETRIEVER_L2_NORM,
LINEAR_RETRIEVER_MINSCORE_FIX,
LinearRetrieverBuilder.MULTI_FIELDS_QUERY_FORMAT_SUPPORT,
RRFRetrieverBuilder.MULTI_FIELDS_QUERY_FORMAT_SUPPORT,
RRFRetrieverBuilder.WEIGHTED_SUPPORT,
RRFRetrieverBuilder.SIMPLIFIED_WEIGHTED_SUPPORT,
LINEAR_RETRIEVER_TOP_LEVEL_NORMALIZER,
LinearRetrieverBuilder.MULTI_INDEX_SIMPLIFIED_FORMAT_SUPPORT,
RRFRetrieverBuilder.MULTI_INDEX_SIMPLIFIED_FORMAT_SUPPORT
);
}
}
| RankRRFFeatures |
java | redisson__redisson | redisson-hibernate/redisson-hibernate-53/src/main/java/org/redisson/hibernate/RedissonStorage.java | {
"start": 1149,
"end": 6121
} | class ____ implements DomainDataStorageAccess {
private static final Logger logger = LoggerFactory.getLogger(RedissonStorage.class);
private final RMapCache<Object, Object> mapCache;
private final ServiceManager serviceManager;
int ttl;
int maxIdle;
int size;
boolean fallback;
volatile boolean fallbackMode;
public RedissonStorage(String regionName, RMapCache<Object, Object> mapCache, ServiceManager serviceManager, Map<String, Object> properties, String defaultKey) {
super();
this.mapCache = mapCache;
this.serviceManager = serviceManager;
String maxEntries = getProperty(properties, mapCache.getName(), regionName, defaultKey, RedissonRegionFactory.MAX_ENTRIES_SUFFIX);
if (maxEntries != null) {
size = Integer.valueOf(maxEntries);
mapCache.setMaxSize(size);
}
String timeToLive = getProperty(properties, mapCache.getName(), regionName, defaultKey, RedissonRegionFactory.TTL_SUFFIX);
if (timeToLive != null) {
ttl = Integer.valueOf(timeToLive);
}
String maxIdleTime = getProperty(properties, mapCache.getName(), regionName, defaultKey, RedissonRegionFactory.MAX_IDLE_SUFFIX);
if (maxIdleTime != null) {
maxIdle = Integer.valueOf(maxIdleTime);
}
String fallbackValue = (String) properties.getOrDefault(RedissonRegionFactory.FALLBACK, "false");
fallback = Boolean.valueOf(fallbackValue);
}
private String getProperty(Map<String, Object> properties, String name, String regionName, String defaultKey, String suffix) {
String maxEntries = (String) properties.get(RedissonRegionFactory.CONFIG_PREFIX + name + suffix);
if (maxEntries != null) {
return maxEntries;
}
maxEntries = (String) properties.get(RedissonRegionFactory.CONFIG_PREFIX + regionName + suffix);
if (maxEntries != null) {
return maxEntries;
}
return (String) properties.get(RedissonRegionFactory.CONFIG_PREFIX + defaultKey + suffix);
}
private void ping() {
fallbackMode = true;
serviceManager.newTimeout(t -> {
RFuture<Boolean> future = mapCache.isExistsAsync();
future.whenComplete((r, ex) -> {
if (ex == null) {
fallbackMode = false;
} else {
ping();
}
});
}, 1, TimeUnit.SECONDS);
}
@Override
public Object getFromCache(Object key, SharedSessionContractImplementor session) {
if (fallbackMode) {
return null;
}
try {
if (maxIdle == 0 && size == 0) {
return mapCache.getWithTTLOnly(key);
}
return mapCache.get(key);
} catch (Exception e) {
if (fallback) {
ping();
logger.error(e.getMessage(), e);
return null;
}
throw new CacheException(e);
}
}
@Override
public void putIntoCache(Object key, Object value, SharedSessionContractImplementor session) {
if (fallbackMode) {
return;
}
try {
mapCache.fastPut(key, value, ttl, TimeUnit.MILLISECONDS, maxIdle, TimeUnit.MILLISECONDS);
} catch (Exception e) {
if (fallback) {
ping();
logger.error(e.getMessage(), e);
return;
}
throw new CacheException(e);
}
}
@Override
public boolean contains(Object key) {
if (fallbackMode) {
return false;
}
try {
return mapCache.containsKey(key);
} catch (Exception e) {
if (fallback) {
ping();
logger.error(e.getMessage(), e);
return false;
}
throw new CacheException(e);
}
}
@Override
public void evictData() {
if (fallbackMode) {
return;
}
try {
mapCache.clear();
} catch (Exception e) {
if (fallback) {
ping();
logger.error(e.getMessage(), e);
return;
}
throw new CacheException(e);
}
}
@Override
public void evictData(Object key) {
if (fallbackMode) {
return;
}
try {
mapCache.fastRemove(key);
} catch (Exception e) {
if (fallback) {
ping();
logger.error(e.getMessage(), e);
return;
}
throw new CacheException(e);
}
}
@Override
public void release() {
try {
mapCache.destroy();
} catch (Exception e) {
throw new CacheException(e);
}
}
}
| RedissonStorage |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.