language stringclasses 1 value | repo stringclasses 60 values | path stringlengths 22 294 | class_span dict | source stringlengths 13 1.16M | target stringlengths 1 113 |
|---|---|---|---|---|---|
java | apache__dubbo | dubbo-remoting/dubbo-remoting-http12/src/main/java/org/apache/dubbo/remoting/http12/exception/HttpOverPayloadException.java | {
"start": 862,
"end": 1069
} | class ____ extends HttpStatusException {
private static final long serialVersionUID = 1L;
public HttpOverPayloadException(String message) {
super(500, message);
}
}
| HttpOverPayloadException |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableRefCountTest.java | {
"start": 22013,
"end": 24837
} | enum ____ implements Observer<Integer> {
INSTANCE;
@Override
public void onSubscribe(Disposable d) {
d.dispose();
}
@Override
public void onNext(Integer t) {
}
@Override
public void onError(Throwable t) {
}
@Override
public void onComplete() {
}
}
@Test
public void disposed() {
TestHelper.checkDisposed(Observable.just(1).publish().refCount());
}
@Test
public void noOpConnect() {
final int[] calls = { 0 };
Observable<Integer> o = new ConnectableObservable<Integer>() {
@Override
public void connect(Consumer<? super Disposable> connection) {
calls[0]++;
}
@Override
public void reset() {
// nothing to do in this test
}
@Override
protected void subscribeActual(Observer<? super Integer> observer) {
observer.onSubscribe(Disposable.disposed());
}
}.refCount();
o.test();
o.test();
assertEquals(1, calls[0]);
}
Observable<Object> source;
@Test
public void replayNoLeak() throws Exception {
System.gc();
Thread.sleep(100);
long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
source = Observable.fromCallable(new Callable<Object>() {
@Override
public Object call() throws Exception {
return new byte[100 * 1000 * 1000];
}
})
.replay(1)
.refCount();
source.subscribe();
long after = TestHelper.awaitGC(GC_SLEEP_TIME, 20, start + 20 * 1000 * 1000);
source = null;
assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after);
}
@Test
public void replayNoLeak2() throws Exception {
System.gc();
Thread.sleep(100);
long start = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
source = Observable.fromCallable(new Callable<Object>() {
@Override
public Object call() throws Exception {
return new byte[100 * 1000 * 1000];
}
}).concatWith(Observable.never())
.replay(1)
.refCount();
Disposable d1 = source.subscribe();
Disposable d2 = source.subscribe();
d1.dispose();
d2.dispose();
d1 = null;
d2 = null;
long after = TestHelper.awaitGC(GC_SLEEP_TIME, 20, start + 20 * 1000 * 1000);
source = null;
assertTrue(String.format("%,3d -> %,3d%n", start, after), start + 20 * 1000 * 1000 > after);
}
static final | DisposingObserver |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesServiceAccountsEndpointBuilderFactory.java | {
"start": 18918,
"end": 21267
} | class ____ {
/**
* The internal instance of the builder used to access to all the
* methods representing the name of headers.
*/
private static final KubernetesServiceAccountsHeaderNameBuilder INSTANCE = new KubernetesServiceAccountsHeaderNameBuilder();
/**
* The Producer operation.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code KubernetesOperation}.
*/
public String kubernetesOperation() {
return "CamelKubernetesOperation";
}
/**
* The namespace name.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code KubernetesNamespaceName}.
*/
public String kubernetesNamespaceName() {
return "CamelKubernetesNamespaceName";
}
/**
* The service account labels.
*
* The option is a: {@code Map<String, String>} type.
*
* Group: producer
*
* @return the name of the header {@code
* KubernetesServiceAccountsLabels}.
*/
public String kubernetesServiceAccountsLabels() {
return "CamelKubernetesServiceAccountsLabels";
}
/**
* The service account name.
*
* The option is a: {@code String} type.
*
* Group: producer
*
* @return the name of the header {@code KubernetesServiceAccountName}.
*/
public String kubernetesServiceAccountName() {
return "CamelKubernetesServiceAccountName";
}
/**
* A service account object.
*
* The option is a: {@code
* io.fabric8.kubernetes.api.model.ServiceAccount} type.
*
* Group: producer
*
* @return the name of the header {@code KubernetesServiceAccount}.
*/
public String kubernetesServiceAccount() {
return "CamelKubernetesServiceAccount";
}
}
static KubernetesServiceAccountsEndpointBuilder endpointBuilder(String componentName, String path) {
| KubernetesServiceAccountsHeaderNameBuilder |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/plan/nodes/exec/stream/GroupAggregateTestPrograms.java | {
"start": 1761,
"end": 24431
} | class ____ {
static final SourceTestStep SOURCE_ONE =
SourceTestStep.newBuilder("source_t")
.addSchema("a INT", "b BIGINT", "c VARCHAR")
.producedBeforeRestore(
Row.of(1, 1L, "Hi"),
Row.of(2, 2L, "Hello"),
Row.of(2, 2L, "Hello World"))
.producedAfterRestore(
Row.of(1, 1L, "Hi Again!"),
Row.of(2, 2L, "Hello Again!"),
Row.of(2, 2L, "Hello World Again!"))
.build();
static final SourceTestStep SOURCE_TWO =
SourceTestStep.newBuilder("source_t")
.addSchema("a INT", "b BIGINT", "c INT", "d VARCHAR", "e BIGINT")
.producedBeforeRestore(
Row.of(2, 3L, 2, "Hello World Like", 1L),
Row.of(3, 4L, 3, "Hello World Its nice", 2L),
Row.of(2, 2L, 1, "Hello World", 2L),
Row.of(1, 1L, 0, "Hello", 1L),
Row.of(5, 11L, 10, "GHI", 1L),
Row.of(3, 5L, 4, "ABC", 2L),
Row.of(4, 10L, 9, "FGH", 2L),
Row.of(4, 7L, 6, "CDE", 2L),
Row.of(5, 14L, 13, "JKL", 2L),
Row.of(4, 9L, 8, "EFG", 1L),
Row.of(5, 15L, 14, "KLM", 2L),
Row.of(5, 12L, 11, "HIJ", 3L),
Row.of(4, 8L, 7, "DEF", 1L),
Row.of(5, 13L, 12, "IJK", 3L),
Row.of(3, 6L, 5, "BCD", 3L))
.producedAfterRestore(
Row.of(1, 1L, 0, "Hello", 1L),
Row.of(3, 5L, 4, "ABC", 2L),
Row.of(4, 10L, 9, "FGH", 2L),
Row.of(4, 7L, 6, "CDE", 2L),
Row.of(7, 7L, 7, "MNO", 7L),
Row.of(3, 6L, 5, "BCD", 3L),
Row.of(7, 7L, 7, "XYZ", 7L))
.build();
static final TableTestProgram GROUP_BY_SIMPLE =
TableTestProgram.of(
"group-aggregate-simple", "validates basic aggregation using group by")
.setupTableSource(SOURCE_ONE)
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema(
"b BIGINT",
"cnt BIGINT",
"avg_a DOUBLE",
"min_c VARCHAR",
"PRIMARY KEY (b) NOT ENFORCED")
.consumedBeforeRestore(
"+I[1, 1, null, Hi]",
"+I[2, 1, 2.0, Hello]",
"+U[2, 2, 2.0, Hello]")
.consumedAfterRestore(
"+U[1, 2, null, Hi]",
"+U[2, 3, 2.0, Hello]",
"+U[2, 4, 2.0, Hello]")
.build())
.runSql(
"INSERT INTO sink_t SELECT "
+ "b, "
+ "COUNT(*) AS cnt, "
+ "AVG(a) FILTER (WHERE a > 1) AS avg_a, "
+ "MIN(c) AS min_c "
+ "FROM source_t GROUP BY b")
.build();
static final TableTestProgram GROUP_BY_SIMPLE_MINI_BATCH =
TableTestProgram.of(
"group-aggregate-simple-mini-batch",
"validates basic aggregation using group by with mini batch")
.setupTableSource(SOURCE_ONE)
.setupConfig(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ENABLED, true)
.setupConfig(
ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ALLOW_LATENCY,
Duration.ofSeconds(10))
.setupConfig(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_SIZE, 5L)
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema(
GROUP_BY_SIMPLE
.getSetupSinkTestSteps()
.get(0)
.schemaComponents)
.consumedBeforeRestore(
"+I[1, 1, null, Hi]", "+I[2, 2, 2.0, Hello]")
.consumedAfterRestore(
"+U[1, 2, null, Hi]", "+U[2, 4, 2.0, Hello]")
.build())
.runSql(GroupAggregateTestPrograms.GROUP_BY_SIMPLE.getRunSqlTestStep().sql)
.build();
static final TableTestProgram GROUP_BY_DISTINCT =
TableTestProgram.of("group-aggregate-distinct", "validates group by distinct")
.setupTableSource(SOURCE_TWO)
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema(
"e BIGINT",
"cnt_a1 BIGINT",
"cnt_a2 BIGINT",
"sum_a BIGINT",
"sum_b BIGINT",
"avg_b DOUBLE",
"cnt_d BIGINT",
"PRIMARY KEY (e) NOT ENFORCED")
.consumedBeforeRestore(
"+I[1, 0, 1, 2, 3, 3.0, 1]",
"+I[2, 0, 1, 3, 4, 4.0, 1]",
"+U[2, 0, 2, 5, 6, 3.0, 2]",
"+U[1, 0, 2, 3, 4, 2.0, 2]",
"+U[1, 1, 3, 8, 15, 5.0, 3]",
"+U[2, 0, 2, 5, 11, 3.0, 3]",
"+U[2, 0, 3, 9, 21, 5.0, 4]",
"+U[2, 0, 3, 9, 28, 5.0, 5]",
"+U[2, 1, 4, 14, 42, 7.0, 6]",
"+U[1, 1, 4, 12, 24, 6.0, 4]",
"+U[2, 1, 4, 14, 57, 8.0, 7]",
"+I[3, 1, 1, 5, 12, 12.0, 1]",
"+U[1, 1, 4, 12, 32, 6.0, 5]",
"+U[3, 1, 1, 5, 25, 12.0, 2]",
"+U[3, 1, 2, 8, 31, 10.0, 3]")
.consumedAfterRestore(
"+U[1, 1, 4, 12, 32, 5.0, 5]",
"+U[2, 1, 4, 14, 57, 7.0, 7]",
"+U[2, 1, 4, 14, 57, 8.0, 7]",
"+U[2, 1, 4, 14, 57, 7.0, 7]",
"+I[7, 0, 1, 7, 7, 7.0, 1]",
"+U[3, 1, 2, 8, 31, 9.0, 3]",
"+U[7, 0, 1, 7, 7, 7.0, 2]")
.build())
.runSql(
"INSERT INTO sink_t SELECT "
+ "e, "
+ "COUNT(DISTINCT a) FILTER (WHERE b > 10) AS cnt_a1, "
+ "COUNT(DISTINCT a) AS cnt_a2, "
+ "SUM(DISTINCT a) AS sum_a, "
+ "SUM(DISTINCT b) AS sum_b, "
+ "AVG(b) AS avg_b, "
+ "COUNT(DISTINCT d) AS concat_d "
+ "FROM source_t GROUP BY e")
.build();
static final TableTestProgram GROUP_BY_DISTINCT_MINI_BATCH =
TableTestProgram.of(
"group-aggregate-distinct-mini-batch",
"validates group by distinct with mini batch")
.setupConfig(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ENABLED, true)
.setupConfig(
ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ALLOW_LATENCY,
Duration.ofSeconds(10))
.setupConfig(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_SIZE, 5L)
.setupTableSource(SOURCE_TWO)
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema(
GROUP_BY_DISTINCT
.getSetupSinkTestSteps()
.get(0)
.schemaComponents)
.consumedBeforeRestore(
"+I[3, 1, 2, 8, 31, 10.0, 3]",
"+I[2, 1, 4, 14, 42, 7.0, 6]",
"+I[1, 1, 4, 12, 24, 6.0, 4]",
"+U[2, 1, 4, 14, 57, 8.0, 7]",
"+U[1, 1, 4, 12, 32, 6.0, 5]")
.consumedAfterRestore(
"+U[3, 1, 2, 8, 31, 9.0, 3]",
"+U[2, 1, 4, 14, 57, 7.0, 7]",
"+I[7, 0, 1, 7, 7, 7.0, 2]",
"+U[1, 1, 4, 12, 32, 5.0, 5]")
.build())
.runSql(GROUP_BY_DISTINCT.getRunSqlTestStep().sql)
.build();
static final TableTestProgram GROUP_BY_UDF_WITH_MERGE =
TableTestProgram.of(
"group-aggregate-udf-with-merge",
"validates udfs with merging using group by")
.setupCatalogFunction("my_avg", WeightedAvgWithMerge.class)
.setupTemporarySystemFunction("my_concat", ConcatDistinctAggFunction.class)
.setupTableSource(SOURCE_TWO)
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema(
"d BIGINT",
"s1 BIGINT",
"c1 VARCHAR",
"PRIMARY KEY (d) NOT ENFORCED")
.consumedBeforeRestore(
"+I[1, 1, Hello World Like]",
"+I[2, 2, Hello World Its nice]",
"+U[2, 2, Hello World Its nice|Hello World]",
"+U[1, 1, Hello World Like|Hello]",
"+U[1, 1, Hello World Like|Hello|GHI]",
"+U[2, 2, Hello World Its nice|Hello World|ABC]",
"+U[2, 2, Hello World Its nice|Hello World|ABC|FGH]",
"+U[2, 2, Hello World Its nice|Hello World|ABC|FGH|CDE]",
"+U[2, 2, Hello World Its nice|Hello World|ABC|FGH|CDE|JKL]",
"+U[1, 1, Hello World Like|Hello|GHI|EFG]",
"+U[2, 2, Hello World Its nice|Hello World|ABC|FGH|CDE|JKL|KLM]",
"+I[3, 3, HIJ]",
"+U[1, 1, Hello World Like|Hello|GHI|EFG|DEF]",
"+U[3, 3, HIJ|IJK]",
"+U[3, 3, HIJ|IJK|BCD]")
.consumedAfterRestore("+I[7, 7, MNO]", "+U[7, 7, MNO|XYZ]")
.build())
.runSql(
"INSERT INTO sink_t SELECT "
+ "e, "
+ "my_avg(e, a) as s1, "
+ "my_concat(d) as c1 "
+ "FROM source_t GROUP BY e")
.build();
static final TableTestProgram GROUP_BY_UDF_WITH_MERGE_MINI_BATCH =
TableTestProgram.of(
"group-aggregate-udf-with-merge-mini-batch",
"validates udfs with merging using group by with mini batch")
.setupConfig(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ENABLED, true)
.setupConfig(
ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ALLOW_LATENCY,
Duration.ofSeconds(10))
.setupConfig(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_SIZE, 5L)
.setupCatalogFunction("my_avg", WeightedAvgWithMerge.class)
.setupTemporarySystemFunction("my_concat", ConcatDistinctAggFunction.class)
.setupTableSource(SOURCE_TWO)
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema(
GROUP_BY_UDF_WITH_MERGE
.getSetupSinkTestSteps()
.get(0)
.schemaComponents)
.consumedBeforeRestore(
"+I[2, 2, Hello World Its nice|Hello World|ABC|FGH|CDE|JKL]",
"+I[1, 1, Hello World Like|Hello|GHI|EFG]",
"+U[2, 2, Hello World Its nice|Hello World|ABC|FGH|CDE|JKL|KLM]",
"+U[1, 1, Hello World Like|Hello|GHI|EFG|DEF]",
"+I[3, 3, HIJ|IJK|BCD]")
.consumedAfterRestore("+I[7, 7, MNO|XYZ]")
.build())
.runSql(GROUP_BY_UDF_WITH_MERGE.getRunSqlTestStep().sql)
.build();
static final TableTestProgram GROUP_BY_UDF_WITHOUT_MERGE =
TableTestProgram.of(
"group-aggregate-udf-without-merge",
"validates udfs without merging using group by")
.setupTemporarySystemFunction("my_sum1", VarSum1AggFunction.class)
.setupCatalogFunction("my_avg", WeightedAvg.class)
.setupTemporarySystemFunction("my_sum2", VarSum2AggFunction.class)
.setupTableSource(SOURCE_TWO)
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema(
"d BIGINT",
"s1 BIGINT",
"s2 BIGINT",
"s3 BIGINT",
"PRIMARY KEY (d) NOT ENFORCED")
.consumedBeforeRestore(
"+I[1, 12, 0, 1]",
"+I[2, 13, 0, 2]",
"+U[2, 24, 0, 2]",
"+U[1, 22, 0, 1]",
"+U[1, 42, 0, 1]",
"+U[2, 38, 0, 2]",
"+U[2, 57, 0, 2]",
"+U[2, 73, 0, 2]",
"+U[2, 96, 0, 2]",
"+U[1, 60, 0, 1]",
"+U[2, 120, 0, 2]",
"+I[3, 21, 0, 3]",
"+U[1, 77, 0, 1]",
"+U[3, 43, 0, 3]",
"+U[3, 58, 0, 3]")
.consumedAfterRestore(
"+U[1, 87, 0, 1]",
"+U[2, 134, 0, 2]",
"+U[2, 153, 0, 2]",
"+U[2, 169, 0, 2]",
"+I[7, 17, 0, 7]",
"+U[3, 73, 0, 3]",
"+U[7, 34, 0, 7]")
.build())
.runSql(
"INSERT INTO sink_t SELECT "
+ "e, "
+ "my_sum1(c, 10) as s1, "
+ "my_sum2(5, c) as s2, "
+ "my_avg(e, a) as s3 "
+ "FROM source_t GROUP BY e")
.build();
static final TableTestProgram GROUP_BY_UDF_WITHOUT_MERGE_MINI_BATCH =
TableTestProgram.of(
"group-aggregate-udf-without-merge-mini-batch",
"validates udfs without merging using group by with mini batch")
.setupConfig(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ENABLED, true)
.setupConfig(
ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_ALLOW_LATENCY,
Duration.ofSeconds(10))
.setupConfig(ExecutionConfigOptions.TABLE_EXEC_MINIBATCH_SIZE, 5L)
.setupTemporarySystemFunction("my_sum1", VarSum1AggFunction.class)
.setupCatalogFunction("my_avg", WeightedAvg.class)
.setupTemporarySystemFunction("my_sum2", VarSum2AggFunction.class)
.setupTableSource(SOURCE_TWO)
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema(
GROUP_BY_UDF_WITHOUT_MERGE
.getSetupSinkTestSteps()
.get(0)
.schemaComponents)
.consumedBeforeRestore(
"+I[2, 24, 0, 2]",
"+I[1, 42, 0, 1]",
"+U[2, 96, 0, 2]",
"+U[1, 60, 0, 1]",
"+I[3, 58, 0, 3]",
"+U[2, 120, 0, 2]",
"+U[1, 77, 0, 1]")
.consumedAfterRestore(
"+I[7, 17, 0, 7]",
"+U[1, 87, 0, 1]",
"+U[2, 169, 0, 2]",
"+U[3, 73, 0, 3]",
"+U[7, 34, 0, 7]")
.build())
.runSql(GROUP_BY_UDF_WITHOUT_MERGE.getRunSqlTestStep().sql)
.build();
static final TableTestProgram AGG_WITH_STATE_TTL_HINT =
TableTestProgram.of("agg-with-state-ttl-hint", "agg with state ttl hint")
.setupTableSource(SOURCE_ONE)
.setupTableSink(
SinkTestStep.newBuilder("sink_t")
.addSchema(
"b BIGINT",
"cnt BIGINT",
"avg_a DOUBLE",
"min_c VARCHAR",
"PRIMARY KEY (b) NOT ENFORCED")
.consumedBeforeRestore(
"+I[1, 1, null, Hi]",
"+I[2, 1, 2.0, Hello]",
"+U[2, 2, 2.0, Hello]")
// Due to state TTL in hint, the state in the metadata
// savepoint has expired.
.consumedAfterRestore(
"+I[1, 1, null, Hi Again!]",
"+I[2, 1, 2.0, Hello Again!]",
"+U[2, 2, 2.0, Hello Again!]")
.build())
.runSql(
"INSERT INTO sink_t SELECT /*+ STATE_TTL('source_t' = '1s') */"
+ "b, "
+ "COUNT(*) AS cnt, "
+ "AVG(a) FILTER (WHERE a > 1) AS avg_a, "
+ "MIN(c) AS min_c "
+ "FROM source_t GROUP BY b")
.build();
}
| GroupAggregateTestPrograms |
java | quarkusio__quarkus | extensions/hibernate-orm/deployment/src/test/java/io/quarkus/hibernate/orm/sql_load_script/SqlLoadScriptPresentTestCase.java | {
"start": 300,
"end": 939
} | class ____ {
@RegisterExtension
static QuarkusUnitTest runner = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(MyEntity.class, SqlLoadScriptTestResource.class)
.addAsResource("application-other-load-script-test.properties", "application.properties")
.addAsResource("load-script-test.sql"));
@Test
public void testSqlLoadScriptPresentTest() {
String name = "other-load-script sql load script entity";
RestAssured.when().get("/orm-sql-load-script/3").then().body(Matchers.is(name));
}
}
| SqlLoadScriptPresentTestCase |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/watcher/ResourceWatcherService.java | {
"start": 1571,
"end": 1728
} | class ____ implements Closeable {
private static final Logger logger = LogManager.getLogger(ResourceWatcherService.class);
public | ResourceWatcherService |
java | spring-projects__spring-framework | spring-webflux/src/test/java/org/springframework/web/reactive/function/server/DispatcherHandlerIntegrationTests.java | {
"start": 6920,
"end": 8313
} | class ____ {
@SuppressWarnings("unchecked")
public Mono<ServerResponse> attributes(ServerRequest request) {
assertThat(request.attributes().containsKey(RouterFunctions.REQUEST_ATTRIBUTE)).isTrue();
assertThat(request.attributes().containsKey(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE)).isTrue();
Map<String, String> pathVariables =
(Map<String, String>) request.attributes().get(RouterFunctions.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
assertThat(pathVariables).isNotNull();
assertThat(pathVariables).hasSize(1);
assertThat(pathVariables.get("foo")).isEqualTo("bar");
pathVariables =
(Map<String, String>) request.attributes().get(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
assertThat(pathVariables).isNotNull();
assertThat(pathVariables).hasSize(1);
assertThat(pathVariables.get("foo")).isEqualTo("bar");
PathPattern pattern =
(PathPattern) request.attributes().get(RouterFunctions.MATCHING_PATTERN_ATTRIBUTE);
assertThat(pattern).isNotNull();
assertThat(pattern.getPatternString()).isEqualTo("/attributes/{foo}");
pattern = (PathPattern) request.attributes()
.get(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
assertThat(pattern).isNotNull();
assertThat(pattern.getPatternString()).isEqualTo("/attributes/{foo}");
return ServerResponse.ok().build();
}
}
@Controller
public static | AttributesHandler |
java | spring-projects__spring-security | web/src/test/java/org/springframework/security/web/FilterInvocationTests.java | {
"start": 1657,
"end": 6249
} | class ____ {
@Test
public void testGettersAndStringMethods() {
MockHttpServletRequest request = get().requestUri("/mycontext", "/HelloWorld", "/some/more/segments.html")
.build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain chain = mock(FilterChain.class);
FilterInvocation fi = new FilterInvocation(request, response, chain);
assertThat(fi.getRequest()).isEqualTo(request);
assertThat(fi.getHttpRequest()).isEqualTo(request);
assertThat(fi.getResponse()).isEqualTo(response);
assertThat(fi.getHttpResponse()).isEqualTo(response);
assertThat(fi.getChain()).isEqualTo(chain);
assertThat(fi.getRequestUrl()).isEqualTo("/HelloWorld/some/more/segments.html");
assertThat(fi.toString()).isEqualTo("filter invocation [GET /HelloWorld/some/more/segments.html]");
assertThat(fi.getFullRequestUrl()).isEqualTo("http://localhost/mycontext/HelloWorld/some/more/segments.html");
}
@Test
public void testRejectsNullFilterChain() {
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
MockHttpServletResponse response = new MockHttpServletResponse();
assertThatIllegalArgumentException().isThrownBy(() -> new FilterInvocation(request, response, null));
}
@Test
public void testRejectsNullServletRequest() {
MockHttpServletResponse response = new MockHttpServletResponse();
assertThatIllegalArgumentException()
.isThrownBy(() -> new FilterInvocation(null, response, mock(FilterChain.class)));
}
@Test
public void testRejectsNullServletResponse() {
MockHttpServletRequest request = new MockHttpServletRequest(null, null);
assertThatIllegalArgumentException()
.isThrownBy(() -> new FilterInvocation(request, null, mock(FilterChain.class)));
}
@Test
public void testStringMethodsWithAQueryString() {
MockHttpServletRequest request = get().requestUri("/mycontext", "/HelloWorld", null)
.queryString("foo=bar")
.build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
assertThat(fi.getRequestUrl()).isEqualTo("/HelloWorld?foo=bar");
assertThat(fi.toString()).isEqualTo("filter invocation [GET /HelloWorld?foo=bar]");
assertThat(fi.getFullRequestUrl()).isEqualTo("http://localhost/mycontext/HelloWorld?foo=bar");
}
@Test
public void testStringMethodsWithoutAnyQueryString() {
MockHttpServletRequest request = get().requestUri("/mycontext", "/HelloWorld", null).build();
MockHttpServletResponse response = new MockHttpServletResponse();
FilterInvocation fi = new FilterInvocation(request, response, mock(FilterChain.class));
assertThat(fi.getRequestUrl()).isEqualTo("/HelloWorld");
assertThat(fi.toString()).isEqualTo("filter invocation [GET /HelloWorld]");
assertThat(fi.getFullRequestUrl()).isEqualTo("http://localhost/mycontext/HelloWorld");
}
@Test
public void dummyChainRejectsInvocation() throws Exception {
assertThatExceptionOfType(UnsupportedOperationException.class).isThrownBy(() -> FilterInvocation.DUMMY_CHAIN
.doFilter(mock(HttpServletRequest.class), mock(HttpServletResponse.class)));
}
@Test
public void dummyRequestIsSupportedByUrlUtils() {
DummyRequest request = new DummyRequest();
request.setContextPath("");
request.setRequestURI("/something");
UrlUtils.buildRequestUrl(request);
}
@Test
public void constructorWhenServletContextProvidedThenSetServletContextInRequest() {
String contextPath = "";
String servletPath = "/path";
String method = "";
MockServletContext mockServletContext = new MockServletContext();
FilterInvocation filterInvocation = new FilterInvocation(contextPath, servletPath, method, mockServletContext);
assertThat(filterInvocation.getRequest().getServletContext()).isSameAs(mockServletContext);
}
@Test
public void testDummyRequestGetHeaders() {
DummyRequest request = new DummyRequest();
request.addHeader("known", "val");
Enumeration<String> headers = request.getHeaders("known");
assertThat(headers.hasMoreElements()).isTrue();
assertThat(headers.nextElement()).isEqualTo("val");
assertThat(headers.hasMoreElements()).isFalse();
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(headers::nextElement);
}
@Test
public void testDummyRequestGetHeadersNull() {
DummyRequest request = new DummyRequest();
Enumeration<String> headers = request.getHeaders("unknown");
assertThat(headers.hasMoreElements()).isFalse();
assertThatExceptionOfType(NoSuchElementException.class).isThrownBy(headers::nextElement);
}
}
| FilterInvocationTests |
java | lettuce-io__lettuce-core | src/main/java/io/lettuce/core/ZPopArgs.java | {
"start": 684,
"end": 1994
} | class ____ {
/**
* Utility constructor.
*/
private Builder() {
}
/**
* Creates new {@link ZPopArgs} and enabling {@literal MIN}.
*
* @return new {@link ZPopArgs} with {@literal MIN} enabled.
* @see ZPopArgs#min()
*/
public static ZPopArgs min() {
return new ZPopArgs().min();
}
/**
* Creates new {@link ZPopArgs} and enabling {@literal MAX}.
*
* @return new {@link ZPopArgs} with {@literal MAX} enabled.
* @see ZPopArgs#min()
*/
public static ZPopArgs max() {
return new ZPopArgs().max();
}
}
/**
* Elements popped are those with the lowest scores from the first non-empty sorted set
*
* @return {@code this} {@link ZPopArgs}.
*/
public ZPopArgs min() {
this.modifier = MIN;
return this;
}
/**
* Elements popped are those with the highest scores from the first non-empty sorted set
*
* @return {@code this} {@link ZPopArgs}.
*/
public ZPopArgs max() {
this.modifier = MAX;
return this;
}
@Override
public <K, V> void build(CommandArgs<K, V> args) {
args.add(modifier);
}
}
| Builder |
java | grpc__grpc-java | core/src/main/java/io/grpc/internal/ManagedChannelImpl.java | {
"start": 26756,
"end": 28962
} | class ____ implements CallTracer.Factory {
@Override
public CallTracer create() {
return new CallTracer(timeProvider);
}
}
this.callTracerFactory = new ChannelCallTracerFactory();
channelCallTracer = callTracerFactory.create();
this.channelz = checkNotNull(builder.channelz);
channelz.addRootChannel(this);
if (!lookUpServiceConfig) {
if (defaultServiceConfig != null) {
channelLogger.log(
ChannelLogLevel.INFO, "Service config look-up disabled, using default service config");
}
serviceConfigUpdated = true;
}
}
@VisibleForTesting
static NameResolver getNameResolver(
URI targetUri, @Nullable final String overrideAuthority,
NameResolverProvider provider, NameResolver.Args nameResolverArgs) {
NameResolver resolver = provider.newNameResolver(targetUri, nameResolverArgs);
if (resolver == null) {
throw new IllegalArgumentException("cannot create a NameResolver for " + targetUri);
}
// We wrap the name resolver in a RetryingNameResolver to give it the ability to retry failures.
// TODO: After a transition period, all NameResolver implementations that need retry should use
// RetryingNameResolver directly and this step can be removed.
NameResolver usedNameResolver = RetryingNameResolver.wrap(resolver, nameResolverArgs);
if (overrideAuthority == null) {
return usedNameResolver;
}
return new ForwardingNameResolver(usedNameResolver) {
@Override
public String getServiceAuthority() {
return overrideAuthority;
}
};
}
@VisibleForTesting
InternalConfigSelector getConfigSelector() {
return realChannel.configSelector.get();
}
@VisibleForTesting
boolean hasThrottle() {
return this.transportProvider.throttle != null;
}
/**
* Initiates an orderly shutdown in which preexisting calls continue but new calls are immediately
* cancelled.
*/
@Override
public ManagedChannelImpl shutdown() {
channelLogger.log(ChannelLogLevel.DEBUG, "shutdown() called");
if (!shutdown.compareAndSet(false, true)) {
return this;
}
final | ChannelCallTracerFactory |
java | greenrobot__EventBus | EventBusTestJava/src/main/java/org/greenrobot/eventbus/EventBusSubscriberLegalTest.java | {
"start": 2230,
"end": 2419
} | class ____ extends Abstract {
@Override
@Subscribe
public void onEvent(String event) {
trackEvent(event);
}
}
// public static | AbstractImpl |
java | spring-projects__spring-security | data/src/main/java/org/springframework/security/data/repository/query/SecurityEvaluationContextExtension.java | {
"start": 2431,
"end": 2785
} | class ____ {
* @Id
* @GeneratedValue(strategy = GenerationType.AUTO)
* private Long id;
*
* @OneToOne
* private User to;
*
* ...
* }
* </pre>
*
* You can use the following {@code Query} annotation to search for only messages that are
* to the current user:
*
* <pre>
* @Repository
* public | Message |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/time/InvalidJavaTimeConstantTest.java | {
"start": 3585,
"end": 4403
} | class ____ {
// BUG: Diagnostic contains: MonthOfYear (valid values 1 - 12): -1
private static final LocalDate LD0 = LocalDate.of(1985, -1, 31);
// BUG: Diagnostic contains: MonthOfYear (valid values 1 - 12): 0
private static final LocalDate LD1 = LocalDate.of(1985, 0, 31);
// BUG: Diagnostic contains: MonthOfYear (valid values 1 - 12): 13
private static final LocalDate LD2 = LocalDate.of(1985, 13, 31);
}
""")
.doTest();
}
@Test
public void localDate_withBadYears() {
compilationHelper
.addSourceLines(
"test/TestCase.java",
"""
package test;
import java.time.LocalDate;
import java.time.Year;
public | TestCase |
java | redisson__redisson | redisson/src/main/java/org/redisson/cache/CachedValue.java | {
"start": 726,
"end": 845
} | interface ____<K, V> extends ExpirableValue {
K getKey();
V getValue();
WrappedLock getLock();
}
| CachedValue |
java | alibaba__nacos | api/src/main/java/com/alibaba/nacos/api/lock/remote/AbstractLockRequest.java | {
"start": 917,
"end": 1048
} | class ____ extends Request {
@Override
public String getModule() {
return LOCK_MODULE;
}
}
| AbstractLockRequest |
java | apache__kafka | streams/src/main/java/org/apache/kafka/streams/processor/assignment/KafkaStreamsAssignment.java | {
"start": 5370,
"end": 6538
} | enum ____ {
ACTIVE,
STANDBY
}
/**
*
* @return the id of the {@code AssignedTask}
*/
public TaskId id() {
return id;
}
/**
*
* @return the type of the {@code AssignedTask}
*/
public Type type() {
return taskType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = prime + this.id.hashCode();
result = prime * result + this.type().hashCode();
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final AssignedTask other = (AssignedTask) obj;
return this.id.equals(other.id()) && this.taskType == other.taskType;
}
@Override
public String toString() {
return String.format("AssignedTask{%s, %s}", taskType, id);
}
}
}
| Type |
java | apache__dubbo | dubbo-common/src/main/java/org/apache/dubbo/config/nested/HistogramConfig.java | {
"start": 924,
"end": 3488
} | class ____ implements Serializable {
private static final long serialVersionUID = 8152538916051803031L;
/**
* Whether histograms are enabled or not. Default is not enabled (false).
*/
private Boolean enabled;
/**
* Buckets in milliseconds for the histograms. Defines the histogram bucket boundaries.
*/
private Integer[] bucketsMs;
/**
* Minimum expected value in milliseconds for the histograms. Values lower than this will be considered outliers.
*/
private Integer minExpectedMs;
/**
* Maximum expected value in milliseconds for the histograms. Values higher than this will be considered outliers.
*/
private Integer maxExpectedMs;
/**
* Whether enabledPercentiles are enabled or not. Default is not enabled (false).
*/
private Boolean enabledPercentiles;
/**
* Array of percentiles to be calculated for the histograms. Each percentile is a double value.
*/
private double[] percentiles;
/**
* Expiry time in minutes for distribution statistics. After this time, the statistics are expired.
*/
private Integer distributionStatisticExpiryMin;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
public Integer[] getBucketsMs() {
return bucketsMs;
}
public void setBucketsMs(Integer[] bucketsMs) {
this.bucketsMs = bucketsMs;
}
public Integer getMinExpectedMs() {
return minExpectedMs;
}
public void setMinExpectedMs(Integer minExpectedMs) {
this.minExpectedMs = minExpectedMs;
}
public Integer getMaxExpectedMs() {
return maxExpectedMs;
}
public void setMaxExpectedMs(Integer maxExpectedMs) {
this.maxExpectedMs = maxExpectedMs;
}
public Boolean getEnabledPercentiles() {
return enabledPercentiles;
}
public void setEnabledPercentiles(Boolean enabledPercentiles) {
this.enabledPercentiles = enabledPercentiles;
}
public double[] getPercentiles() {
return percentiles;
}
public void setPercentiles(double[] percentiles) {
this.percentiles = percentiles;
}
public Integer getDistributionStatisticExpiryMin() {
return distributionStatisticExpiryMin;
}
public void setDistributionStatisticExpiryMin(Integer distributionStatisticExpiryMin) {
this.distributionStatisticExpiryMin = distributionStatisticExpiryMin;
}
}
| HistogramConfig |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-examples/src/main/java/org/apache/hadoop/examples/terasort/Unsigned16.java | {
"start": 1080,
"end": 7526
} | class ____ implements Writable {
private long hi8;
private long lo8;
public Unsigned16() {
hi8 = 0;
lo8 = 0;
}
public Unsigned16(long l) {
hi8 = 0;
lo8 = l;
}
public Unsigned16(Unsigned16 other) {
hi8 = other.hi8;
lo8 = other.lo8;
}
@Override
public boolean equals(Object o) {
if (o instanceof Unsigned16) {
Unsigned16 other = (Unsigned16) o;
return other.hi8 == hi8 && other.lo8 == lo8;
}
return false;
}
@Override
public int hashCode() {
return (int) lo8;
}
/**
* Parse a hex string
* @param s the hex string
*/
public Unsigned16(String s) throws NumberFormatException {
set(s);
}
/**
* Set the number from a hex string
* @param s the number in hexadecimal
* @throws NumberFormatException if the number is invalid
*/
public void set(String s) throws NumberFormatException {
hi8 = 0;
lo8 = 0;
final long lastDigit = 0xfl << 60;
for (int i = 0; i < s.length(); ++i) {
int digit = getHexDigit(s.charAt(i));
if ((lastDigit & hi8) != 0) {
throw new NumberFormatException(s + " overflowed 16 bytes");
}
hi8 <<= 4;
hi8 |= (lo8 & lastDigit) >>> 60;
lo8 <<= 4;
lo8 |= digit;
}
}
/**
* Set the number to a given long.
* @param l the new value, which is treated as an unsigned number
*/
public void set(long l) {
lo8 = l;
hi8 = 0;
}
/**
* Map a hexadecimal character into a digit.
* @param ch the character
* @return the digit from 0 to 15
* @throws NumberFormatException
*/
private static int getHexDigit(char ch) throws NumberFormatException {
if (ch >= '0' && ch <= '9') {
return ch - '0';
}
if (ch >= 'a' && ch <= 'f') {
return ch - 'a' + 10;
}
if (ch >= 'A' && ch <= 'F') {
return ch - 'A' + 10;
}
throw new NumberFormatException(ch + " is not a valid hex digit");
}
private static final Unsigned16 TEN = new Unsigned16(10);
public static Unsigned16 fromDecimal(String s) throws NumberFormatException {
Unsigned16 result = new Unsigned16();
Unsigned16 tmp = new Unsigned16();
for(int i=0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch < '0' || ch > '9') {
throw new NumberFormatException(ch + " not a valid decimal digit");
}
int digit = ch - '0';
result.multiply(TEN);
tmp.set(digit);
result.add(tmp);
}
return result;
}
/**
* Return the number as a hex string.
*/
public String toString() {
if (hi8 == 0) {
return Long.toHexString(lo8);
} else {
StringBuilder result = new StringBuilder();
result.append(Long.toHexString(hi8));
String loString = Long.toHexString(lo8);
for(int i=loString.length(); i < 16; ++i) {
result.append('0');
}
result.append(loString);
return result.toString();
}
}
/**
* Get a given byte from the number.
* @param b the byte to get with 0 meaning the most significant byte
* @return the byte or 0 if b is outside of 0..15
*/
public byte getByte(int b) {
if (b >= 0 && b < 16) {
if (b < 8) {
return (byte) (hi8 >> (56 - 8*b));
} else {
return (byte) (lo8 >> (120 - 8*b));
}
}
return 0;
}
/**
* Get the hexadecimal digit at the given position.
* @param p the digit position to get with 0 meaning the most significant
* @return the character or '0' if p is outside of 0..31
*/
public char getHexDigit(int p) {
byte digit = getByte(p / 2);
if (p % 2 == 0) {
digit >>>= 4;
}
digit &= 0xf;
if (digit < 10) {
return (char) ('0' + digit);
} else {
return (char) ('A' + digit - 10);
}
}
/**
* Get the high 8 bytes as a long.
*/
public long getHigh8() {
return hi8;
}
/**
* Get the low 8 bytes as a long.
*/
public long getLow8() {
return lo8;
}
/**
* Multiple the current number by a 16 byte unsigned integer. Overflow is not
* detected and the result is the low 16 bytes of the result. The numbers
* are divided into 32 and 31 bit chunks so that the product of two chucks
* fits in the unsigned 63 bits of a long.
* @param b the other number
*/
void multiply(Unsigned16 b) {
// divide the left into 4 32 bit chunks
long[] left = new long[4];
left[0] = lo8 & 0xffffffffl;
left[1] = lo8 >>> 32;
left[2] = hi8 & 0xffffffffl;
left[3] = hi8 >>> 32;
// divide the right into 5 31 bit chunks
long[] right = new long[5];
right[0] = b.lo8 & 0x7fffffffl;
right[1] = (b.lo8 >>> 31) & 0x7fffffffl;
right[2] = (b.lo8 >>> 62) + ((b.hi8 & 0x1fffffffl) << 2);
right[3] = (b.hi8 >>> 29) & 0x7fffffffl;
right[4] = (b.hi8 >>> 60);
// clear the cur value
set(0);
Unsigned16 tmp = new Unsigned16();
for(int l=0; l < 4; ++l) {
for (int r=0; r < 5; ++r) {
long prod = left[l] * right[r];
if (prod != 0) {
int off = l*32 + r*31;
tmp.set(prod);
tmp.shiftLeft(off);
add(tmp);
}
}
}
}
/**
* Add the given number into the current number.
* @param b the other number
*/
public void add(Unsigned16 b) {
long sumHi;
long sumLo;
long reshibit, hibit0, hibit1;
sumHi = hi8 + b.hi8;
hibit0 = (lo8 & 0x8000000000000000L);
hibit1 = (b.lo8 & 0x8000000000000000L);
sumLo = lo8 + b.lo8;
reshibit = (sumLo & 0x8000000000000000L);
if ((hibit0 & hibit1) != 0 | ((hibit0 ^ hibit1) != 0 && reshibit == 0))
sumHi++; /* add carry bit */
hi8 = sumHi;
lo8 = sumLo;
}
/**
* Shift the number a given number of bit positions. The number is the low
* order bits of the result.
* @param bits the bit positions to shift by
*/
public void shiftLeft(int bits) {
if (bits != 0) {
if (bits < 64) {
hi8 <<= bits;
hi8 |= (lo8 >>> (64 - bits));
lo8 <<= bits;
} else if (bits < 128) {
hi8 = lo8 << (bits - 64);
lo8 = 0;
} else {
hi8 = 0;
lo8 = 0;
}
}
}
@Override
public void readFields(DataInput in) throws IOException {
hi8 = in.readLong();
lo8 = in.readLong();
}
@Override
public void write(DataOutput out) throws IOException {
out.writeLong(hi8);
out.writeLong(lo8);
}
}
| Unsigned16 |
java | processing__processing4 | core/src/processing/opengl/PJOGL.java | {
"start": 2162,
"end": 15895
} | class ____ extends PGL {
// OpenGL profile to use (2, 3 or 4)
public static int profile = 2;
// User-provided icons to override defaults
protected static String[] icons = null;
// The two windowing toolkits available to use in JOGL:
public static final int AWT = 0; // http://jogamp.org/wiki/index.php/Using_JOGL_in_AWT_SWT_and_Swing
public static final int NEWT = 1; // http://jogamp.org/jogl/doc/NEWT-Overview.html
// ........................................................
// Public members to access the underlying GL objects and context
/** Basic GL functionality, common to all profiles */
public GL gl;
/** GLU interface **/
public GLU glu;
/** The rendering context (holds rendering state info) */
public GLContext context;
// ........................................................
// Protected JOGL-specific objects needed to access the GL profiles
/** The capabilities of the OpenGL rendering surface */
protected GLCapabilitiesImmutable capabilities;
/** The rendering surface */
protected GLDrawable drawable;
/** GLES2 functionality (shaders, etc) */
protected GL2ES2 gl2;
/** GL3 interface */
protected GL2GL3 gl3;
/**
* GL2 desktop functionality (blit framebuffer, map buffer range,
* multi-sampled render buffers)
*/
protected GL2 gl2x;
/** GL3ES3 interface */
protected GL3ES3 gl3es3;
// ........................................................
// Utility arrays to copy projection/modelview matrices to GL
protected float[] projMatrix;
protected float[] mvMatrix;
// ........................................................
// Static initialization for some parameters that need to be different for
// JOGL
static {
MIN_DIRECT_BUFFER_SIZE = 2;
INDEX_TYPE = GL.GL_UNSIGNED_SHORT;
}
private static boolean forceSharedObjectSync = true;
///////////////////////////////////////////////////////////////
// Initialization, finalization
public PJOGL(PGraphicsOpenGL pg) {
super(pg);
glu = new GLU();
}
@Override
public Object getNative() {
return sketch.getSurface().getNative();
}
@Override
protected void setFrameRate(float fps) {}
@Override
protected void initSurface(int antialias) {}
@Override
protected void reinitSurface() {}
@Override
protected void registerListeners() {}
static public void setIcon(String... icons) {
PJOGL.icons = new String[icons.length];
PApplet.arrayCopy(icons, PJOGL.icons);
}
///////////////////////////////////////////////////////////////
// Public methods to get/set renderer's properties
public void setCaps(GLCapabilities caps) {
reqNumSamples = caps.getNumSamples();
capabilities = caps;
}
public GLCapabilitiesImmutable getCaps() {
return capabilities;
}
public boolean needSharedObjectSync() {
return forceSharedObjectSync || gl.getContext().hasRendererQuirk(GLRendererQuirks.NeedSharedObjectSync);
}
public void setFps(float fps) {
if (!setFps || targetFps != fps) {
if (60 < fps) {
// Disables v-sync
gl.setSwapInterval(0);
} else if (30 < fps) {
gl.setSwapInterval(1);
} else {
gl.setSwapInterval(2);
}
targetFps = currentFps = fps;
setFps = true;
}
}
@Override
protected int getDepthBits() {
return capabilities.getDepthBits();
}
@Override
protected int getStencilBits() {
return capabilities.getStencilBits();
}
@Override
protected float getPixelScale() {
PSurface surf = sketch.getSurface();
if (surf == null) {
return graphics.pixelDensity;
} else if (surf instanceof PSurfaceJOGL) {
return ((PSurfaceJOGL)surf).getPixelScale();
} else {
throw new RuntimeException("Renderer cannot find a JOGL surface");
}
}
@Override
protected void getGL(PGL pgl) {
PJOGL pjogl = (PJOGL)pgl;
this.drawable = pjogl.drawable;
this.context = pjogl.context;
this.glContext = pjogl.glContext;
setThread(pjogl.glThread);
this.gl = pjogl.gl;
this.gl2 = pjogl.gl2;
this.gl2x = pjogl.gl2x;
this.gl3 = pjogl.gl3;
this.gl3es3 = pjogl.gl3es3;
}
public void getGL(GLAutoDrawable glDrawable) {
context = glDrawable.getContext();
glContext = context.hashCode();
setThread(Thread.currentThread());
gl = context.getGL();
gl2 = gl.getGL2ES2();
try {
gl2x = gl.getGL2();
} catch (com.jogamp.opengl.GLException e) {
gl2x = null;
}
try {
gl3 = gl.getGL2GL3();
} catch (com.jogamp.opengl.GLException e) {
gl3 = null;
}
try {
gl3es3 = gl.getGL3ES3();
} catch (com.jogamp.opengl.GLException e) {
gl3es3 = null;
}
}
@Override
protected boolean canDraw() { return true; }
@Override
protected void requestFocus() {}
@Override
protected void requestDraw() {}
@Override
protected void swapBuffers() {
PSurfaceJOGL surf = (PSurfaceJOGL)sketch.getSurface();
surf.window.swapBuffers();
}
@Override
protected void initFBOLayer() {
if (0 < sketch.frameCount) {
if (isES()) initFBOLayerES();
else initFBOLayerGL();
}
}
private void initFBOLayerES() {
IntBuffer buf = allocateDirectIntBuffer(fboWidth * fboHeight);
if (hasReadBuffer()) readBuffer(BACK);
readPixelsImpl(0, 0, fboWidth, fboHeight, RGBA, UNSIGNED_BYTE, buf);
bindTexture(TEXTURE_2D, glColorTex.get(frontTex));
texSubImage2D(TEXTURE_2D, 0, 0, 0, fboWidth, fboHeight, RGBA, UNSIGNED_BYTE, buf);
bindTexture(TEXTURE_2D, glColorTex.get(backTex));
texSubImage2D(TEXTURE_2D, 0, 0, 0, fboWidth, fboHeight, RGBA, UNSIGNED_BYTE, buf);
bindTexture(TEXTURE_2D, 0);
bindFramebufferImpl(FRAMEBUFFER, 0);
}
private void initFBOLayerGL() {
// Copy the contents of the front and back screen buffers to the textures
// of the FBO, so they are properly initialized. Note that the front buffer
// of the default framebuffer (the screen) contains the previous frame:
// https://www.opengl.org/wiki/Default_Framebuffer
// so it is copied to the front texture of the FBO layer:
if (pclearColor || 0 < pgeomCount || !sketch.isLooping()) {
if (hasReadBuffer()) readBuffer(FRONT);
} else {
// ...except when the previous frame has not been cleared and nothing was
// rendered while looping. In this case the back buffer, which holds the
// initial state of the previous frame, still contains the most up-to-date
// screen state.
readBuffer(BACK);
}
bindFramebufferImpl(DRAW_FRAMEBUFFER, glColorFbo.get(0));
framebufferTexture2D(FRAMEBUFFER, COLOR_ATTACHMENT0,
TEXTURE_2D, glColorTex.get(frontTex), 0);
if (hasDrawBuffer()) drawBuffer(COLOR_ATTACHMENT0);
blitFramebuffer(0, 0, fboWidth, fboHeight,
0, 0, fboWidth, fboHeight,
COLOR_BUFFER_BIT, NEAREST);
readBuffer(BACK);
bindFramebufferImpl(DRAW_FRAMEBUFFER, glColorFbo.get(0));
framebufferTexture2D(FRAMEBUFFER, COLOR_ATTACHMENT0,
TEXTURE_2D, glColorTex.get(backTex), 0);
drawBuffer(COLOR_ATTACHMENT0);
blitFramebuffer(0, 0, fboWidth, fboHeight,
0, 0, fboWidth, fboHeight,
COLOR_BUFFER_BIT, NEAREST);
bindFramebufferImpl(FRAMEBUFFER, 0);
}
@Override
protected void beginGL() {
PMatrix3D proj = graphics.projection;
PMatrix3D mdl = graphics.modelview;
if (gl2x != null) {
if (projMatrix == null) {
projMatrix = new float[16];
}
gl2x.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
projMatrix[ 0] = proj.m00;
projMatrix[ 1] = proj.m10;
projMatrix[ 2] = proj.m20;
projMatrix[ 3] = proj.m30;
projMatrix[ 4] = proj.m01;
projMatrix[ 5] = proj.m11;
projMatrix[ 6] = proj.m21;
projMatrix[ 7] = proj.m31;
projMatrix[ 8] = proj.m02;
projMatrix[ 9] = proj.m12;
projMatrix[10] = proj.m22;
projMatrix[11] = proj.m32;
projMatrix[12] = proj.m03;
projMatrix[13] = proj.m13;
projMatrix[14] = proj.m23;
projMatrix[15] = proj.m33;
gl2x.glLoadMatrixf(projMatrix, 0);
if (mvMatrix == null) {
mvMatrix = new float[16];
}
gl2x.glMatrixMode(GLMatrixFunc.GL_MODELVIEW);
mvMatrix[ 0] = mdl.m00;
mvMatrix[ 1] = mdl.m10;
mvMatrix[ 2] = mdl.m20;
mvMatrix[ 3] = mdl.m30;
mvMatrix[ 4] = mdl.m01;
mvMatrix[ 5] = mdl.m11;
mvMatrix[ 6] = mdl.m21;
mvMatrix[ 7] = mdl.m31;
mvMatrix[ 8] = mdl.m02;
mvMatrix[ 9] = mdl.m12;
mvMatrix[10] = mdl.m22;
mvMatrix[11] = mdl.m32;
mvMatrix[12] = mdl.m03;
mvMatrix[13] = mdl.m13;
mvMatrix[14] = mdl.m23;
mvMatrix[15] = mdl.m33;
gl2x.glLoadMatrixf(mvMatrix, 0);
}
}
@Override
protected boolean hasFBOs() {
if (context.hasBasicFBOSupport()) return true;
else return super.hasFBOs();
}
@Override
protected boolean hasShaders() {
if (context.hasGLSL()) return true;
else return super.hasShaders();
}
public void init(GLAutoDrawable glDrawable) {
capabilities = glDrawable.getChosenGLCapabilities();
if (!hasFBOs()) {
throw new RuntimeException(MISSING_FBO_ERROR);
}
if (!hasShaders()) {
throw new RuntimeException(MISSING_GLSL_ERROR);
}
}
///////////////////////////////////////////////////////////
// Utility functions
@Override
protected void enableTexturing(int target) {
if (target == TEXTURE_2D) {
texturingTargets[0] = true;
} else if (target == TEXTURE_RECTANGLE) {
texturingTargets[1] = true;
}
}
@Override
protected void disableTexturing(int target) {
if (target == TEXTURE_2D) {
texturingTargets[0] = false;
} else if (target == TEXTURE_RECTANGLE) {
texturingTargets[1] = false;
}
}
/**
* Convenience method to get a legit FontMetrics object. Where possible,
* override this any renderer subclass so that you're not using what's
* returned by getDefaultToolkit() to get your metrics.
*/
@SuppressWarnings("deprecation")
private FontMetrics getFontMetrics(Font font) { // ignore
return Toolkit.getDefaultToolkit().getFontMetrics(font);
}
/**
* Convenience method to jump through some Java2D hoops and get an FRC.
*/
private FontRenderContext getFontRenderContext(Font font) { // ignore
return getFontMetrics(font).getFontRenderContext();
}
/*
@Override
protected int getFontAscent(Object font) {
return getFontMetrics((Font) font).getAscent();
}
@Override
protected int getFontDescent(Object font) {
return getFontMetrics((Font) font).getDescent();
}
*/
@Override
protected int getTextWidth(Object font, char[] buffer, int start, int stop) {
// maybe should use one of the newer/fancier functions for this?
int length = stop - start;
FontMetrics metrics = getFontMetrics((Font) font);
return metrics.charsWidth(buffer, start, length);
}
@Override
protected Object getDerivedFont(Object font, float size) {
return ((Font) font).deriveFont(size);
}
@Override
protected int getGLSLVersion() {
VersionNumber vn = context.getGLSLVersionNumber();
return vn.getMajor() * 100 + vn.getMinor();
}
@Override
protected String getGLSLVersionSuffix() {
VersionNumber vn = context.getGLSLVersionNumber();
if (context.isGLESProfile() && 1 < vn.getMajor()) {
return " es";
} else {
return "";
}
}
@Override
protected String[] loadVertexShader(String filename) {
return loadVertexShader(filename, getGLSLVersion(), getGLSLVersionSuffix());
}
@Override
protected String[] loadFragmentShader(String filename) {
return loadFragmentShader(filename, getGLSLVersion(), getGLSLVersionSuffix());
}
@Override
protected String[] loadVertexShader(URL url) {
return loadVertexShader(url, getGLSLVersion(), getGLSLVersionSuffix());
}
@Override
protected String[] loadFragmentShader(URL url) {
return loadFragmentShader(url, getGLSLVersion(), getGLSLVersionSuffix());
}
@Override
protected String[] loadFragmentShader(String filename, int version, String versionSuffix) {
String[] fragSrc0 = sketch.loadStrings(filename);
return preprocessFragmentSource(fragSrc0, version, versionSuffix);
}
@Override
protected String[] loadVertexShader(String filename, int version, String versionSuffix) {
String[] vertSrc0 = sketch.loadStrings(filename);
return preprocessVertexSource(vertSrc0, version, versionSuffix);
}
@Override
protected String[] loadFragmentShader(URL url, int version, String versionSuffix) {
try {
String[] fragSrc0 = PApplet.loadStrings(url.openStream());
return preprocessFragmentSource(fragSrc0, version, versionSuffix);
} catch (IOException e) {
PGraphics.showException("Cannot load fragment shader " + url.getFile());
}
return null;
}
@Override
protected String[] loadVertexShader(URL url, int version, String versionSuffix) {
try {
String[] vertSrc0 = PApplet.loadStrings(url.openStream());
return preprocessVertexSource(vertSrc0, version, versionSuffix);
} catch (IOException e) {
PGraphics.showException("Cannot load vertex shader " + url.getFile());
}
return null;
}
///////////////////////////////////////////////////////////
// Tessellator
@Override
protected Tessellator createTessellator(TessellatorCallback callback) {
return new Tessellator(callback);
}
protected static | PJOGL |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/view/feed/AtomFeedViewTests.java | {
"start": 1380,
"end": 2297
} | class ____ {
private final AbstractAtomFeedView view = new MyAtomFeedView();
@Test
void render() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
Map<String, String> model = new LinkedHashMap<>();
model.put("2", "This is entry 2");
model.put("1", "This is entry 1");
view.render(model, request, response);
assertThat(response.getContentType()).as("Invalid content-type").isEqualTo("application/atom+xml");
String expected = "<feed xmlns=\"http://www.w3.org/2005/Atom\">" + "<title>Test Feed</title>" +
"<entry><title>2</title><summary>This is entry 2</summary></entry>" +
"<entry><title>1</title><summary>This is entry 1</summary></entry>" + "</feed>";
assertThat(XmlContent.of(response.getContentAsString())).isSimilarToIgnoringWhitespace(expected);
}
private static | AtomFeedViewTests |
java | apache__dubbo | dubbo-common/src/test/java/org/apache/dubbo/rpc/support/ProtocolUtilsTest.java | {
"start": 918,
"end": 2993
} | class ____ {
@Test
void testGetServiceKey() {
final String serviceName = "com.abc.demoService";
final int port = 1001;
assertServiceKey(port, serviceName, "1.0.0", "group");
assertServiceKey(port, serviceName, "1.0.0", "");
assertServiceKey(port, serviceName, "1.0.0", null);
assertServiceKey(port, serviceName, "0.0", "group");
assertServiceKey(port, serviceName, "0_0_0", "group");
assertServiceKey(port, serviceName, "0.0.0", "group");
assertServiceKey(port, serviceName, "", "group");
assertServiceKey(port, serviceName, null, "group");
assertServiceKey(port, serviceName, "", "");
assertServiceKey(port, serviceName, "", null);
assertServiceKey(port, serviceName, null, "");
assertServiceKey(port, serviceName, null, null);
assertServiceKey(port, serviceName, "", " ");
assertServiceKey(port, serviceName, " ", "");
assertServiceKey(port, serviceName, " ", " ");
}
private void assertServiceKey(int port, String serviceName, String serviceVersion, String serviceGroup) {
Assertions.assertEquals(
serviceKeyOldImpl(port, serviceName, serviceVersion, serviceGroup),
ProtocolUtils.serviceKey(port, serviceName, serviceVersion, serviceGroup));
}
/**
* 来自 ProtocolUtils.serviceKey(int, String, String, String) 老版本的实现,用于对比测试!
*/
private static String serviceKeyOldImpl(int port, String serviceName, String serviceVersion, String serviceGroup) {
StringBuilder buf = new StringBuilder();
if (serviceGroup != null && serviceGroup.length() > 0) {
buf.append(serviceGroup);
buf.append('/');
}
buf.append(serviceName);
if (serviceVersion != null && serviceVersion.length() > 0 && !"0.0.0".equals(serviceVersion)) {
buf.append(':');
buf.append(serviceVersion);
}
buf.append(':');
buf.append(port);
return buf.toString();
}
}
| ProtocolUtilsTest |
java | micronaut-projects__micronaut-core | inject-java/src/main/java/io/micronaut/annotation/processing/JavaAnnotationMetadataBuilder.java | {
"start": 11069,
"end": 24138
} | interface ____ abstract methods
// with type level data
// the starting hierarchy is the type and super types of this method
List<Element> hierarchy;
if (inheritTypeAnnotations) {
hierarchy = buildHierarchy(executableElement.getEnclosingElement(), false, declaredOnly);
} else {
hierarchy = new ArrayList<>();
}
hierarchy.addAll(nativeElementsHelper.findOverriddenMethods(executableElement));
hierarchy.add(element);
return hierarchy;
} else if (element instanceof VariableElement variable) {
var hierarchy = new ArrayList<Element>();
Element enclosingElement = variable.getEnclosingElement();
if (enclosingElement instanceof ExecutableElement executableElement) {
int variableIdx = executableElement.getParameters().indexOf(variable);
for (ExecutableElement overridden : nativeElementsHelper.findOverriddenMethods(executableElement)) {
hierarchy.add(overridden.getParameters().get(variableIdx));
}
}
hierarchy.add(variable);
return hierarchy;
} else {
var single = new ArrayList<Element>(1);
single.add(element);
return single;
}
}
@Override
protected Map<? extends Element, ?> readAnnotationRawValues(AnnotationMirror annotationMirror) {
return annotationMirror.getElementValues();
}
@Nullable
@Override
protected Element getAnnotationMember(Element annotationElement, CharSequence member) {
if (annotationElement instanceof TypeElement) {
List<? extends Element> enclosedElements = annotationElement.getEnclosedElements();
for (Element enclosedElement : enclosedElements) {
if (enclosedElement instanceof ExecutableElement && enclosedElement.getSimpleName().toString().equals(member.toString())) {
return enclosedElement;
}
}
}
return null;
}
@Override
protected String getOriginatingClassName(@NonNull Element orginatingElement) {
TypeElement typeElement = getOriginatingTypeElement(orginatingElement);
if (typeElement != null) {
return JavaModelUtils.getClassName(typeElement);
}
return null;
}
private TypeElement getOriginatingTypeElement(Element element) {
if (element == null) {
return null;
}
if (element instanceof TypeElement typeElement) {
return typeElement;
}
return getOriginatingTypeElement(element.getEnclosingElement());
}
@Override
protected <K extends Annotation> Optional<io.micronaut.core.annotation.AnnotationValue<K>> getAnnotationValues(Element originatingElement, Element member, Class<K> annotationType) {
List<? extends AnnotationMirror> annotationMirrors = member.getAnnotationMirrors();
String annotationName = annotationType.getName();
for (AnnotationMirror annotationMirror : annotationMirrors) {
if (annotationMirror.getAnnotationType().toString().endsWith(annotationName)) {
Map<? extends Element, ?> values = readAnnotationRawValues(annotationMirror);
var converted = new LinkedHashMap<CharSequence, Object>();
for (Map.Entry<? extends Element, ?> entry : values.entrySet()) {
Element key = entry.getKey();
Object value = entry.getValue();
readAnnotationRawValues(originatingElement, annotationName, key, key.getSimpleName().toString(), value, converted);
}
return Optional.of(io.micronaut.core.annotation.AnnotationValue.builder(annotationType).members(converted).build());
}
}
return Optional.empty();
}
@Override
protected void readAnnotationRawValues(
Element originatingElement,
String annotationName,
Element member,
String memberName,
Object annotationValue,
Map<CharSequence, Object> annotationValues) {
readAnnotationRawValues(originatingElement, annotationName, member, memberName, annotationValue, annotationValues, new HashMap<>());
}
@Override
protected void readAnnotationRawValues(
Element originatingElement,
String annotationName,
Element member,
String memberName,
Object annotationValue,
Map<CharSequence, Object> annotationValues,
Map<String, Map<CharSequence, Object>> resolvedDefaults) {
if (memberName != null && annotationValue instanceof javax.lang.model.element.AnnotationValue value && !annotationValues.containsKey(memberName)) {
final MetadataAnnotationValueVisitor resolver = new MetadataAnnotationValueVisitor(originatingElement, (ExecutableElement) member, resolvedDefaults);
value.accept(resolver, this);
Object resolvedValue = resolver.resolvedValue;
if (resolvedValue != null) {
if ("<error>".equals(resolvedValue)) {
if (Class.class.getName().equals(this.modelUtils.resolveTypeName(((ExecutableElement) member).getReturnType()))) {
resolvedValue = new AnnotationClassValue<>(
new AnnotationClassValue.UnresolvedClass(new PostponeToNextRoundException(
originatingElement,
originatingElement.getSimpleName().toString() + "@" + annotationName + "(" + memberName + ")"
))
);
annotationValues.put(memberName, resolvedValue);
} else {
throw new PostponeToNextRoundException(originatingElement, memberName);
}
} else {
if (isEvaluatedExpression(resolvedValue)) {
resolvedValue = buildEvaluatedExpressionReference(originatingElement, annotationName, memberName, resolvedValue);
}
validateAnnotationValue(originatingElement, annotationName, member, memberName, resolvedValue);
annotationValues.put(memberName, resolvedValue);
}
}
}
}
@Override
protected boolean isValidationRequired(Element member) {
final List<? extends AnnotationMirror> annotationMirrors = member.getAnnotationMirrors();
return isValidationRequired(annotationMirrors);
}
private boolean isValidationRequired(List<? extends AnnotationMirror> annotationMirrors) {
for (AnnotationMirror annotationMirror : annotationMirrors) {
final String annotationName = getAnnotationTypeName(annotationMirror);
if (annotationName.startsWith("jakarta.validation")) {
return true;
} else if (!AnnotationUtil.INTERNAL_ANNOTATION_NAMES.contains(annotationName)) {
final Element element = getAnnotationMirror(annotationName).orElse(null);
if (element != null) {
final List<? extends AnnotationMirror> childMirrors = element.getAnnotationMirrors()
.stream()
.filter(ann -> !getAnnotationTypeName(ann).equals(annotationName))
.collect(Collectors.toList());
if (isValidationRequired(childMirrors)) {
return true;
}
}
}
}
return false;
}
@Override
protected Object readAnnotationValue(Element originatingElement, Element member, String annotationName, String memberName, Object annotationValue) {
if (memberName != null && annotationValue instanceof javax.lang.model.element.AnnotationValue value) {
final MetadataAnnotationValueVisitor visitor = new MetadataAnnotationValueVisitor(originatingElement, (ExecutableElement) member, new HashMap<>());
value.accept(visitor, this);
return visitor.resolvedValue;
} else if (memberName != null && annotationValue != null && ClassUtils.isJavaLangType(annotationValue.getClass())) {
// only allow basic types
if (isEvaluatedExpression(annotationValue)) {
annotationValue = buildEvaluatedExpressionReference(originatingElement, annotationName, memberName, annotationValue);
}
return annotationValue;
}
return null;
}
@Override
protected Map<? extends Element, ?> readAnnotationDefaultValues(String annotationTypeName, Element element) {
var defaultValues = new LinkedHashMap<Element, AnnotationValue>();
if (element instanceof TypeElement annotationElement) {
final List<? extends Element> allMembers = elementUtils.getAllMembers(annotationElement);
allMembers
.stream()
.filter(member -> member.getEnclosingElement().equals(annotationElement))
.filter(ExecutableElement.class::isInstance)
.map(ExecutableElement.class::cast)
.filter(this::isValidDefaultValue)
.forEach(executableElement -> {
final AnnotationValue defaultValue = executableElement.getDefaultValue();
defaultValues.put(executableElement, defaultValue);
}
);
}
return defaultValues;
}
private boolean isValidDefaultValue(ExecutableElement executableElement) {
AnnotationValue defaultValue = executableElement.getDefaultValue();
if (defaultValue != null) {
Object v;
try {
v = defaultValue.getValue();
} catch (UnsupportedOperationException e) {
// if this is Attribute it can throw UnsupportedOperationException
return false;
}
if (v != null) {
if (v instanceof String string) {
return StringUtils.isNotEmpty(string);
} else {
return true;
}
}
}
return false;
}
@Override
protected String getAnnotationTypeName(AnnotationMirror annotationMirror) {
return JavaModelUtils.getClassName((TypeElement) annotationMirror.getAnnotationType().asElement());
}
@Override
protected String getElementName(Element element) {
if (element instanceof TypeElement typeElement) {
return elementUtils.getBinaryName(typeElement).toString();
}
return element.getSimpleName().toString();
}
/**
* Checks if a method has an annotation.
*
* @param element The method
* @param ann The annotation to look for
* @return Whether if the method has the annotation
*/
@Override
public boolean hasAnnotation(Element element, Class<? extends Annotation> ann) {
return hasAnnotation(element, ann.getName());
}
/**
* Checks if a method has an annotation.
*
* @param element The method
* @param ann The annotation to look for
* @return Whether if the method has the annotation
*/
@Override
public boolean hasAnnotation(Element element, String ann) {
List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
if (CollectionUtils.isNotEmpty(annotationMirrors)) {
for (AnnotationMirror annotationMirror : annotationMirrors) {
final DeclaredType annotationType = annotationMirror.getAnnotationType();
if (annotationType.toString().equals(ann)) {
return true;
}
}
}
return false;
}
@Override
protected boolean hasAnnotations(Element element) {
return CollectionUtils.isNotEmpty(element.getAnnotationMirrors());
}
/**
* Clears any caches from the last compilation round.
*/
public static void clearCaches() {
AbstractAnnotationMetadataBuilder.clearCaches();
}
/**
* Checks if a method has an annotation.
*
* @param method The method
* @param ann The annotation to look for
* @return Whether if the method has the annotation
*/
public static boolean hasAnnotation(ExecutableElement method, Class<? extends Annotation> ann) {
List<? extends AnnotationMirror> annotationMirrors = method.getAnnotationMirrors();
for (AnnotationMirror annotationMirror : annotationMirrors) {
if (annotationMirror.getAnnotationType().toString().equals(ann.getName())) {
return true;
}
}
return false;
}
/**
* Meta annotation value visitor class.
*/
private | or |
java | apache__camel | components/camel-ai/camel-langchain4j-embeddingstore/src/main/java/org/apache/camel/component/langchain4j/embeddingstore/LangChain4jEmbeddingStoreComponent.java | {
"start": 2129,
"end": 3413
} | class ____ extends DefaultComponent {
private static final Logger LOGGER = LoggerFactory.getLogger(LangChain4jEmbeddingStoreComponent.class);
@Metadata
private LangChain4jEmbeddingStoreConfiguration configuration;
public LangChain4jEmbeddingStoreComponent() {
this(null);
}
public LangChain4jEmbeddingStoreComponent(CamelContext context) {
super(context);
this.configuration = new LangChain4jEmbeddingStoreConfiguration();
}
public LangChain4jEmbeddingStoreConfiguration getConfiguration() {
return configuration;
}
/**
* The configuration;
*/
public void setConfiguration(LangChain4jEmbeddingStoreConfiguration configuration) {
this.configuration = configuration;
}
@Override
protected Endpoint createEndpoint(
String uri,
String remaining,
Map<String, Object> parameters)
throws Exception {
LangChain4jEmbeddingStoreConfiguration configuration = this.configuration.copy();
LangChain4jEmbeddingStoreEndpoint endpoint = new LangChain4jEmbeddingStoreEndpoint(uri, this, remaining, configuration);
setProperties(endpoint, parameters);
return endpoint;
}
}
| LangChain4jEmbeddingStoreComponent |
java | grpc__grpc-java | services/src/generated/test/grpc/io/grpc/reflection/testing/AnotherReflectableServiceGrpc.java | {
"start": 5847,
"end": 6791
} | class ____
extends io.grpc.stub.AbstractAsyncStub<AnotherReflectableServiceStub> {
private AnotherReflectableServiceStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected AnotherReflectableServiceStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new AnotherReflectableServiceStub(channel, callOptions);
}
/**
*/
public void method(io.grpc.reflection.testing.Request request,
io.grpc.stub.StreamObserver<io.grpc.reflection.testing.Reply> responseObserver) {
io.grpc.stub.ClientCalls.asyncUnaryCall(
getChannel().newCall(getMethodMethod(), getCallOptions()), request, responseObserver);
}
}
/**
* A stub to allow clients to do synchronous rpc calls to service AnotherReflectableService.
*/
public static final | AnotherReflectableServiceStub |
java | google__dagger | hilt-compiler/main/java/dagger/hilt/processor/internal/Processors.java | {
"start": 5450,
"end": 7333
} | class ____ invalid or missing: %s",
annotation.getName(),
key,
XAnnotations.toStableString(annotation));
return values;
}
public static ImmutableList<XTypeElement> getOptionalAnnotationClassValues(
XAnnotation annotation, String key) {
return getOptionalAnnotationValues(annotation, key).stream()
.filter(XAnnotationValue::hasTypeValue)
.flatMap(
annotationValue -> getTypeFromAnnotationValue(annotation, annotationValue).stream())
.map(XType::getTypeElement)
.collect(toImmutableList());
}
private static ImmutableList<XAnnotationValue> getOptionalAnnotationValues(
XAnnotation annotation, String key) {
return annotation.getAnnotationValues().stream()
.filter(annotationValue -> annotationValue.getName().equals(key))
.collect(toOptional())
.map(
annotationValue ->
(annotationValue.hasListValue()
? ImmutableList.copyOf(annotationValue.asAnnotationValueList())
: ImmutableList.of(annotationValue)))
.orElse(ImmutableList.of());
}
private static ImmutableList<XType> getTypeFromAnnotationValue(
XAnnotation annotation, XAnnotationValue annotationValue) {
validateAnnotationValueType(annotation, annotationValue);
return ImmutableList.of(annotationValue.asType());
}
private static void validateAnnotationValueType(
XAnnotation annotation, XAnnotationValue annotationValue) {
boolean error = false;
try {
if (annotationValue.asType().isError()) {
error = true;
}
} catch (TypeNotPresentException unused) {
// TODO(b/277367118): we may need a way to ignore error types in XProcessing.
error = true;
}
if (error) {
throw new ErrorTypeException(
String.format(
"@%s, '%s' | is |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/Spr16217Tests.java | {
"start": 833,
"end": 1836
} | class ____ {
@Test
public void baseConfigurationIsIncludedWhenFirstSuperclassReferenceIsSkippedInRegisterBeanPhase() {
try (AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(RegisterBeanPhaseImportingConfiguration.class)) {
context.getBean("someBean");
}
}
@Test
void baseConfigurationIsIncludedWhenFirstSuperclassReferenceIsSkippedInParseConfigurationPhase() {
try (AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ParseConfigurationPhaseImportingConfiguration.class)) {
context.getBean("someBean");
}
}
@Test
void baseConfigurationIsIncludedOnceWhenBothConfigurationClassesAreActive() {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
try (context) {
context.setAllowBeanDefinitionOverriding(false);
context.register(UnconditionalImportingConfiguration.class);
context.refresh();
context.getBean("someBean");
}
}
public static | Spr16217Tests |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/api/async/AMRMClientAsync.java | {
"start": 21021,
"end": 22399
} | interface ____ {
/**
* Called when the ResourceManager responds to a heartbeat with completed
* containers. If the response contains both completed containers and
* allocated containers, this will be called before containersAllocated.
*/
void onContainersCompleted(List<ContainerStatus> statuses);
/**
* Called when the ResourceManager responds to a heartbeat with allocated
* containers. If the response containers both completed containers and
* allocated containers, this will be called after containersCompleted.
*/
void onContainersAllocated(List<Container> containers);
/**
* Called when the ResourceManager wants the ApplicationMaster to shutdown
* for being out of sync etc. The ApplicationMaster should not unregister
* with the RM unless the ApplicationMaster wants to be the last attempt.
*/
void onShutdownRequest();
/**
* Called when nodes tracked by the ResourceManager have changed in health,
* availability etc.
*/
void onNodesUpdated(List<NodeReport> updatedNodes);
float getProgress();
/**
* Called when error comes from RM communications as well as from errors in
* the callback itself from the app. Calling
* stop() is the recommended action.
*
* @param e
*/
void onError(Throwable e);
}
}
| CallbackHandler |
java | quarkusio__quarkus | extensions/opentelemetry/deployment/src/test/java/io/quarkus/opentelemetry/deployment/common/SemconvResolver.java | {
"start": 474,
"end": 1613
} | class ____ {
SemconvResolver() {
// empty
}
public static void assertTarget(final SpanData server, final String path, final String query) {
assertEquals(path, server.getAttributes().get(URL_PATH));
assertEquals(query, server.getAttributes().get(URL_QUERY));
}
public static <T> void assertSemanticAttribute(final SpanData spanData, final T expected,
final AttributeKey<T> attributeKey) {
assertEquals(expected, getAttribute(spanData, attributeKey));
}
@SuppressWarnings("unchecked")
private static <T> T getAttribute(final SpanData data, final AttributeKey<T> attributeKey) {
if (attributeKey.getType().equals(LONG)) {
return (T) data.getAttributes().get(attributeKey);
} else if (attributeKey.getType().equals(STRING)) {
return (T) data.getAttributes().get(attributeKey);
} else {
throw new IllegalArgumentException(
"Unsupported attribute: " + attributeKey.getKey() +
" with type: " + attributeKey.getKey().getClass());
}
}
}
| SemconvResolver |
java | google__auto | service/processor/src/main/java/com/google/auto/service/processor/AutoServiceProcessor.java | {
"start": 12025,
"end": 13127
} | class
____ ImmutableSet.of(MoreTypes.asDeclared(typeMirror));
}
@Override
public ImmutableSet<DeclaredType> visitArray(
List<? extends AnnotationValue> values, Void v) {
return values.stream()
.flatMap(value -> value.accept(this, null).stream())
.collect(toImmutableSet());
}
},
null);
}
private void log(String msg) {
if (processingEnv.getOptions().containsKey("debug")) {
processingEnv.getMessager().printMessage(Kind.NOTE, msg);
}
}
private void warning(String msg, Element element, AnnotationMirror annotation) {
processingEnv.getMessager().printMessage(Kind.WARNING, msg, element, annotation);
}
private void error(String msg, Element element, AnnotationMirror annotation) {
processingEnv.getMessager().printMessage(Kind.ERROR, msg, element, annotation);
}
private void fatalError(String msg) {
processingEnv.getMessager().printMessage(Kind.ERROR, "FATAL ERROR: " + msg);
}
}
| return |
java | spring-projects__spring-framework | spring-web/src/main/java/org/springframework/web/method/HandlerMethod.java | {
"start": 12764,
"end": 14447
} | class ____ the given
* method is declared. In some cases the actual controller instance at request-
* processing time may be a JDK dynamic proxy (lazy initialization, prototype
* beans, and others). {@code @Controller}'s that require proxying should prefer
* class-based proxy mechanisms.
*/
protected void assertTargetBean(Method method, Object targetBean, @Nullable Object[] args) {
Class<?> methodDeclaringClass = method.getDeclaringClass();
Class<?> targetBeanClass = targetBean.getClass();
if (!methodDeclaringClass.isAssignableFrom(targetBeanClass)) {
String text = "The mapped handler method class '" + methodDeclaringClass.getName() +
"' is not an instance of the actual controller bean class '" +
targetBeanClass.getName() + "'. If the controller requires proxying " +
"(for example, due to @Transactional), please use class-based proxying.";
throw new IllegalStateException(formatInvokeError(text, args));
}
}
protected String formatInvokeError(String text, @Nullable Object[] args) {
String formattedArgs = IntStream.range(0, args.length)
.mapToObj(i -> {
Object arg = args[i];
return (arg != null ?
"[" + i + "] [type=" +arg.getClass().getName() + "] [value=" + arg + "]" :
"[" + i + "] [null]");
})
.collect(Collectors.joining(",\n", " ", " "));
return text + "\n" +
"Controller [" + getBeanType().getName() + "]\n" +
"Method [" + getBridgedMethod().toGenericString() + "] " +
"with argument values:\n" + formattedArgs;
}
/**
* Checks for the presence of {@code @Constraint} and {@code @Valid}
* annotations on the method and method parameters.
*/
private static | where |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/requests/AlterUserScramCredentialsRequest.java | {
"start": 1302,
"end": 4063
} | class ____ extends AbstractRequest.Builder<AlterUserScramCredentialsRequest> {
private final AlterUserScramCredentialsRequestData data;
public Builder(AlterUserScramCredentialsRequestData data) {
super(ApiKeys.ALTER_USER_SCRAM_CREDENTIALS);
this.data = data;
}
@Override
public AlterUserScramCredentialsRequest build(short version) {
return new AlterUserScramCredentialsRequest(data, version);
}
@Override
public String toString() {
return maskData(data);
}
}
private final AlterUserScramCredentialsRequestData data;
private AlterUserScramCredentialsRequest(AlterUserScramCredentialsRequestData data, short version) {
super(ApiKeys.ALTER_USER_SCRAM_CREDENTIALS, version);
this.data = data;
}
public static AlterUserScramCredentialsRequest parse(Readable readable, short version) {
return new AlterUserScramCredentialsRequest(new AlterUserScramCredentialsRequestData(readable, version), version);
}
@Override
public AlterUserScramCredentialsRequestData data() {
return data;
}
@Override
public AbstractResponse getErrorResponse(int throttleTimeMs, Throwable e) {
ApiError apiError = ApiError.fromThrowable(e);
short errorCode = apiError.error().code();
String errorMessage = apiError.message();
Set<String> users = Stream.concat(
this.data.deletions().stream().map(deletion -> deletion.name()),
this.data.upsertions().stream().map(upsertion -> upsertion.name()))
.collect(Collectors.toSet());
List<AlterUserScramCredentialsResponseData.AlterUserScramCredentialsResult> results =
users.stream().sorted().map(user ->
new AlterUserScramCredentialsResponseData.AlterUserScramCredentialsResult()
.setUser(user)
.setErrorCode(errorCode)
.setErrorMessage(errorMessage))
.collect(Collectors.toList());
return new AlterUserScramCredentialsResponse(new AlterUserScramCredentialsResponseData().setResults(results));
}
private static String maskData(AlterUserScramCredentialsRequestData data) {
AlterUserScramCredentialsRequestData tempData = data.duplicate();
tempData.upsertions().forEach(upsertion -> {
upsertion.setSalt(new byte[0]);
upsertion.setSaltedPassword(new byte[0]);
});
return tempData.toString();
}
// Do not print salt or saltedPassword
@Override
public String toString() {
return maskData(data);
}
}
| Builder |
java | quarkusio__quarkus | extensions/smallrye-fault-tolerance/runtime/src/main/java/io/quarkus/smallrye/faulttolerance/runtime/config/SmallRyeFaultToleranceConfig.java | {
"start": 11672,
"end": 12574
} | interface ____ {
/**
* Whether the {@code @Fallback} strategy is enabled.
*/
@ConfigDocDefault("true")
Optional<Boolean> enabled();
/**
* The exception types that are considered failures and hence should trigger fallback.
*
* @see Fallback#applyOn()
*/
@ConfigDocDefault("Throwable (all exceptions)")
Optional<Class<? extends Throwable>[]> applyOn();
/**
* The exception types that are not considered failures and hence should not trigger fallback.
* Takes priority over {@link #applyOn()}.
*
* @see Fallback#skipOn()
*/
@ConfigDocDefault("<empty set>")
Optional<Class<? extends Throwable>[]> skipOn();
/**
* The | FallbackConfig |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/inference/chunking/NoneChunkingSettingsTests.java | {
"start": 465,
"end": 1089
} | class ____ extends AbstractWireSerializingTestCase<NoneChunkingSettings> {
@Override
protected Writeable.Reader<NoneChunkingSettings> instanceReader() {
return in -> NoneChunkingSettings.INSTANCE;
}
@Override
protected NoneChunkingSettings createTestInstance() {
return NoneChunkingSettings.INSTANCE;
}
@Override
protected boolean shouldBeSame(NoneChunkingSettings newInstance) {
return true;
}
@Override
protected NoneChunkingSettings mutateInstance(NoneChunkingSettings instance) throws IOException {
return null;
}
}
| NoneChunkingSettingsTests |
java | elastic__elasticsearch | x-pack/plugin/searchable-snapshots/src/internalClusterTest/java/org/elasticsearch/xpack/searchablesnapshots/SearchableSnapshotsSettingValidationIntegTests.java | {
"start": 1048,
"end": 3102
} | class ____ extends BaseFrozenSearchableSnapshotsIntegTestCase {
private static final String repoName = "test-repo";
private static final String indexName = "test-index";
private static final String snapshotName = "test-snapshot";
@Before
public void createAndMountSearchableSnapshot() throws Exception {
createRepository(repoName, "fs");
createIndex(indexName);
createFullSnapshot(repoName, snapshotName);
assertAcked(indicesAdmin().prepareDelete(indexName));
final MountSearchableSnapshotRequest req = new MountSearchableSnapshotRequest(
TEST_REQUEST_TIMEOUT,
indexName,
repoName,
snapshotName,
indexName,
Settings.EMPTY,
Strings.EMPTY_ARRAY,
true,
randomFrom(MountSearchableSnapshotRequest.Storage.values())
);
final RestoreSnapshotResponse restoreSnapshotResponse = client().execute(MountSearchableSnapshotAction.INSTANCE, req).get();
assertThat(restoreSnapshotResponse.getRestoreInfo().failedShards(), equalTo(0));
ensureGreen(indexName);
}
public void testCannotRemoveWriteBlock() {
final IllegalArgumentException iae = expectThrows(
IllegalArgumentException.class,
() -> indicesAdmin().prepareUpdateSettings(indexName)
.setSettings(Settings.builder().put(IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.getKey(), false))
.get()
);
assertThat(
iae.getMessage(),
containsString("illegal value can't update [" + IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.getKey() + "] from [true] to [false]")
);
assertNotNull(iae.getCause());
assertThat(iae.getCause().getMessage(), containsString("Cannot remove write block from searchable snapshot index"));
updateIndexSettings(Settings.builder().put(IndexMetadata.INDEX_BLOCKS_WRITE_SETTING.getKey(), true), indexName);
}
}
| SearchableSnapshotsSettingValidationIntegTests |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFlatMapCompletable.java | {
"start": 1305,
"end": 1951
} | class ____<T> extends AbstractObservableWithUpstream<T, T> {
final Function<? super T, ? extends CompletableSource> mapper;
final boolean delayErrors;
public ObservableFlatMapCompletable(ObservableSource<T> source,
Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors) {
super(source);
this.mapper = mapper;
this.delayErrors = delayErrors;
}
@Override
protected void subscribeActual(Observer<? super T> observer) {
source.subscribe(new FlatMapCompletableMainObserver<>(observer, mapper, delayErrors));
}
static final | ObservableFlatMapCompletable |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-client/src/main/java/org/apache/hadoop/yarn/client/cli/NodeAttributesCLI.java | {
"start": 8361,
"end": 8419
} | class ____ command handler.
*/
public static abstract | for |
java | apache__camel | components/camel-sql/src/test/java/org/apache/camel/component/sql/SqlEndpointMisconfigureDataSourceTest.java | {
"start": 1502,
"end": 3230
} | class ____ extends CamelTestSupport {
private EmbeddedDatabase db;
@Test
public void testFail() {
context.getRegistry().bind("myDataSource", db);
RouteBuilder rb = new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.to("sql:foo?dataSource=myDataSource")
.to("mock:result");
}
};
FailedToCreateRouteException e = assertThrows(FailedToCreateRouteException.class, () -> context.addRoutes(rb),
"Should throw exception");
PropertyBindingException pbe = (PropertyBindingException) e.getCause().getCause();
assertEquals("dataSource", pbe.getPropertyName());
assertEquals("myDataSource", pbe.getValue());
}
@Test
public void testOk() throws Exception {
context.getRegistry().bind("myDataSource", db);
context.addRoutes(new RouteBuilder() {
@Override
public void configure() {
from("direct:start")
.to("sql:foo?dataSource=#myDataSource")
.to("mock:result");
}
});
assertDoesNotThrow(() -> context.start());
}
@Override
public void doPreSetup() throws Exception {
db = new EmbeddedDatabaseBuilder()
.setName(getClass().getSimpleName())
.setType(EmbeddedDatabaseType.H2)
.addScript("sql/createAndPopulateDatabase.sql").build();
}
@Override
public void doPostTearDown() throws Exception {
if (db != null) {
db.shutdown();
}
}
}
| SqlEndpointMisconfigureDataSourceTest |
java | google__truth | core/src/main/java/com/google/common/truth/Expect.java | {
"start": 3798,
"end": 3888
} | class ____ extends StandardSubjectBuilder implements TestRule {
private static final | Expect |
java | apache__maven | its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng2124PomInterpolationWithParentValuesTest.java | {
"start": 1099,
"end": 1940
} | class ____ extends AbstractMavenIntegrationTestCase {
/**
* Test that ${parent.artifactId} resolves correctly. [MNG-2124]
*
* @throws Exception in case of failure
*/
@Test
public void testitMNG2124() throws Exception {
File testDir = extractResources("/mng-2124");
File child = new File(testDir, "parent/child");
Verifier verifier = newVerifier(child.getAbsolutePath());
verifier.setAutoclean(false);
verifier.deleteDirectory("target");
verifier.addCliArgument("initialize");
verifier.execute();
verifier.verifyErrorFreeLog();
Properties props = verifier.loadProperties("target/parent.properties");
assertEquals("parent, child", props.getProperty("project.description"));
}
}
| MavenITmng2124PomInterpolationWithParentValuesTest |
java | apache__kafka | clients/src/main/java/org/apache/kafka/common/errors/ElectionNotNeededException.java | {
"start": 847,
"end": 1115
} | class ____ extends InvalidMetadataException {
public ElectionNotNeededException(String message) {
super(message);
}
public ElectionNotNeededException(String message, Throwable cause) {
super(message, cause);
}
}
| ElectionNotNeededException |
java | square__moshi | examples/src/main/java/com/squareup/moshi/recipes/MultipleFormats.java | {
"start": 1868,
"end": 2508
} | class ____ {
@ToJson
void toJson(JsonWriter writer, Card value, @CardString JsonAdapter<Card> stringAdapter)
throws IOException {
stringAdapter.toJson(writer, value);
}
@FromJson
Card fromJson(
JsonReader reader,
@CardString JsonAdapter<Card> stringAdapter,
JsonAdapter<Card> defaultAdapter)
throws IOException {
if (reader.peek() == JsonReader.Token.STRING) {
return stringAdapter.fromJson(reader);
} else {
return defaultAdapter.fromJson(reader);
}
}
}
/** Handles cards as strings only. */
public final | MultipleFormatsCardAdapter |
java | resilience4j__resilience4j | resilience4j-ratelimiter/src/main/java/io/github/resilience4j/ratelimiter/RequestNotPermitted.java | {
"start": 813,
"end": 2013
} | class ____ extends RuntimeException {
private final transient String causingRateLimiter;
private RequestNotPermitted(RateLimiter rateLimiter, String message, boolean writableStackTrace) {
super(message, null, false, writableStackTrace);
this.causingRateLimiter = rateLimiter.getName();
}
/**
* Static method to construct a {@link RequestNotPermitted} with a RateLimiter.
*
* @param rateLimiter the RateLimiter.
*/
public static RequestNotPermitted createRequestNotPermitted(RateLimiter rateLimiter) {
boolean writableStackTraceEnabled = rateLimiter.getRateLimiterConfig()
.isWritableStackTraceEnabled();
String message = String
.format("RateLimiter '%s' does not permit further calls", rateLimiter.getName());
return new RequestNotPermitted(rateLimiter, message, writableStackTraceEnabled);
}
/**
* Returns the name of {@link RateLimiter} that caused this exception.
*
* @return the name of {@link RateLimiter} that caused this exception.
*/
public String getCausingRateLimiterName() {
return this.causingRateLimiter;
}
}
| RequestNotPermitted |
java | google__error-prone | core/src/test/java/com/google/errorprone/dataflow/nullnesspropagation/NullnessInferenceTest.java | {
"start": 18762,
"end": 19129
} | class ____ {
void test(
MyInnerClass<? extends @Nullable Object> nullable,
MyInnerClass<? extends @NonNull Object> nonnull) {
// BUG: Diagnostic contains: Optional[Nullable]
inspectInferredExpression(nullable.get());
// BUG: Diagnostic contains: Optional[Non-null]
inspectInferredExpression(nonnull.get());
}
| BoundedAtGenericTypeUseTest |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/pool/DruidDataSourceTest_enable.java | {
"start": 293,
"end": 1635
} | class ____ extends TestCase {
private DruidDataSource dataSource;
protected void setUp() throws Exception {
dataSource = new DruidDataSource();
dataSource.setUrl("jdbc:mock:xxx");
dataSource.setTestOnBorrow(false);
dataSource.setMaxWait(1000);
}
protected void tearDown() throws Exception {
dataSource.close();
}
public void test_disable() throws Exception {
{
Connection conn = dataSource.getConnection();
conn.close();
}
assertTrue(dataSource.isEnable());
dataSource.setEnable(false);
assertFalse(dataSource.isEnable());
dataSource.shrink();
Exception error = null;
try {
Connection conn = dataSource.getConnection();
conn.close();
} catch (DataSourceDisableException e) {
error = e;
}
assertNotNull(error);
}
public void test_disable_() throws Exception {
dataSource.setEnable(false);
assertFalse(dataSource.isEnable());
Exception error = null;
try {
Connection conn = dataSource.getConnection();
conn.close();
} catch (DataSourceDisableException e) {
error = e;
}
assertNotNull(error);
}
}
| DruidDataSourceTest_enable |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/RoundRobinLoadBalanceTest.java | {
"start": 1148,
"end": 2687
} | class ____ extends ContextTestSupport {
protected MockEndpoint x;
protected MockEndpoint y;
protected MockEndpoint z;
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
x = getMockEndpoint("mock:x");
y = getMockEndpoint("mock:y");
z = getMockEndpoint("mock:z");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
public void configure() {
// START SNIPPET: example
from("direct:start").loadBalance().roundRobin().to("mock:x", "mock:y", "mock:z");
// END SNIPPET: example
}
};
}
@Test
public void testRoundRobin() throws Exception {
String body = "<one/>";
x.expectedBodiesReceived(body);
expectsMessageCount(0, y, z);
sendMessage("bar", body);
assertMockEndpointsSatisfied();
x.reset();
body = "<two/>";
y.expectedBodiesReceived(body);
expectsMessageCount(0, x, z);
sendMessage("bar", body);
assertMockEndpointsSatisfied();
y.reset();
body = "<three/>";
z.expectedBodiesReceived(body);
expectsMessageCount(0, x, y);
sendMessage("bar", body);
assertMockEndpointsSatisfied();
}
protected void sendMessage(final Object headerValue, final Object body) {
template.sendBodyAndHeader("direct:start", body, "foo", headerValue);
}
}
| RoundRobinLoadBalanceTest |
java | elastic__elasticsearch | x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/elastic/ccm/CCMServiceTests.java | {
"start": 550,
"end": 977
} | class ____ extends ESTestCase {
public static CCMService createMockCCMService(boolean enabled) {
var mockService = mock(CCMService.class);
doAnswer(invocation -> {
ActionListener<Boolean> listener = invocation.getArgument(0);
listener.onResponse(enabled);
return Void.TYPE;
}).when(mockService).isEnabled(any());
return mockService;
}
}
| CCMServiceTests |
java | quarkusio__quarkus | independent-projects/tools/devtools-common/src/main/java/io/quarkus/platform/catalog/processor/ExtendedKeywords.java | {
"start": 413,
"end": 2725
} | class ____ {
private ExtendedKeywords() {
}
private static final Pattern TOKENIZER_PATTERN = Pattern.compile("\\w+");
private static final HashSet<String> STOP_WORDS = new HashSet<>(Arrays.asList("the", "and", "you", "that", "was", "for",
"are", "with", "his", "they", "one",
"have", "this", "from", "had", "not", "but", "what", "can", "out", "other", "were", "all", "there", "when",
"your", "how", "each", "she", "which", "their", "will", "way", "about", "many", "then", "them", "would", "enable",
"these", "her", "him", "has", "over", "than", "who", "may", "down", "been", "more", "implementing", "non",
"quarkus"));
public static Set<String> extendsKeywords(String artifactId, String name, String shortName, List<String> categories,
String description, List<String> keywords) {
final List<String> result = new ArrayList<>();
result.addAll(expandValue(artifactId, true));
result.addAll(expandValue(name, false));
result.addAll(expandValue(shortName, true));
categories.forEach(it -> result.addAll(expandValue(it, true)));
result.addAll(keywords);
if (!StringUtils.isEmpty(description)) {
final Matcher matcher = TOKENIZER_PATTERN.matcher(description);
while (matcher.find()) {
final String token = matcher.group().toLowerCase(Locale.US);
if (isNotStopWord(token)) {
result.add(token);
}
}
}
return result.stream()
.filter(Objects::nonNull)
.map(s -> s.toLowerCase(Locale.US))
.filter(ExtendedKeywords::isNotStopWord)
.collect(Collectors.toSet());
}
private static boolean isNotStopWord(String token) {
return token.length() >= 3 && !STOP_WORDS.contains(token);
}
private static List<String> expandValue(String value, boolean keepOriginal) {
if (value == null) {
return Collections.emptyList();
}
String r = value.replaceAll("\\s", "-");
final List<String> l = new ArrayList<>(Arrays.asList(r.split("-")));
if (keepOriginal) {
l.add(r);
}
return l;
}
}
| ExtendedKeywords |
java | apache__flink | flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/casting/CastRulesTest.java | {
"start": 94352,
"end": 95115
} | class ____ {
public long a;
public Long b;
public String c;
public String[] d;
public MyStructuredType(long a, Long b, String c, String[] d) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
@Override
public String toString() {
return "My fancy string representation{"
+ "a="
+ a
+ ", b="
+ b
+ ", c='"
+ c
+ '\''
+ ", d="
+ Arrays.toString(d)
+ '}';
}
}
@SuppressWarnings({"rawtypes"})
private static | MyStructuredType |
java | apache__flink | flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/adaptive/allocator/TestingSlotAllocator.java | {
"start": 1416,
"end": 4526
} | class ____ implements SlotAllocator {
private final Function<Iterable<JobInformation.VertexInformation>, ResourceCounter>
calculateRequiredSlotsFunction;
private final Function<JobSchedulingPlan, Optional<ReservedSlots>> tryReserveResourcesFunction;
private final BiFunction<
JobInformation, Collection<? extends SlotInfo>, Optional<VertexParallelism>>
determineParallelismFunction;
private final TriFunction<
JobInformation,
Collection<? extends SlotInfo>,
JobAllocationsInformation,
Optional<JobSchedulingPlan>>
determineParallelismAndCalculateAssignmentFunction;
private TestingSlotAllocator(
Function<Iterable<JobInformation.VertexInformation>, ResourceCounter>
calculateRequiredSlotsFunction,
Function<JobSchedulingPlan, Optional<ReservedSlots>> tryReserveResourcesFunction,
final BiFunction<
JobInformation,
Collection<? extends SlotInfo>,
Optional<VertexParallelism>>
determineParallelismFunction,
final TriFunction<
JobInformation,
Collection<? extends SlotInfo>,
JobAllocationsInformation,
Optional<JobSchedulingPlan>>
determineParallelismAndCalculateAssignmentFunction) {
this.calculateRequiredSlotsFunction = calculateRequiredSlotsFunction;
this.tryReserveResourcesFunction = tryReserveResourcesFunction;
this.determineParallelismFunction = determineParallelismFunction;
this.determineParallelismAndCalculateAssignmentFunction =
determineParallelismAndCalculateAssignmentFunction;
}
@Override
public ResourceCounter calculateRequiredSlots(
Iterable<JobInformation.VertexInformation> vertices) {
return calculateRequiredSlotsFunction.apply(vertices);
}
@Override
public Optional<VertexParallelism> determineParallelism(
JobInformation jobInformation, Collection<? extends SlotInfo> slots) {
return determineParallelismFunction.apply(jobInformation, slots);
}
@Override
public Optional<JobSchedulingPlan> determineParallelismAndCalculateAssignment(
JobInformation jobInformation,
Collection<PhysicalSlot> slots,
JobAllocationsInformation jobAllocationsInformation) {
return determineParallelismAndCalculateAssignmentFunction.apply(
jobInformation, slots, jobAllocationsInformation);
}
@Override
public Optional<ReservedSlots> tryReserveResources(JobSchedulingPlan jobSchedulingPlan) {
return tryReserveResourcesFunction.apply(jobSchedulingPlan);
}
public static Builder newBuilder() {
return new Builder();
}
/** Builder for the {@link TestingSlotAllocator}. */
public static final | TestingSlotAllocator |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/flowable/FlowableEventStream.java | {
"start": 881,
"end": 1957
} | class ____ {
private FlowableEventStream() {
throw new IllegalStateException("No instances!");
}
public static Flowable<Event> getEventStream(final String type, final int numInstances) {
return Flowable.<Event>generate(new EventConsumer(type, numInstances))
.subscribeOn(Schedulers.newThread());
}
public static Event randomEvent(String type, int numInstances) {
Map<String, Object> values = new LinkedHashMap<>();
values.put("count200", randomIntFrom0to(4000));
values.put("count4xx", randomIntFrom0to(300));
values.put("count5xx", randomIntFrom0to(500));
return new Event(type, "instance_" + randomIntFrom0to(numInstances), values);
}
private static int randomIntFrom0to(int max) {
// XORShift instead of Math.random http://javamex.com/tutorials/random_numbers/xorshift.shtml
long x = System.nanoTime();
x ^= (x << 21);
x ^= (x >>> 35);
x ^= (x << 4);
return Math.abs((int) x % max);
}
static final | FlowableEventStream |
java | apache__maven | its/core-it-suite/src/test/resources/mng-3536/plugin/src/main/java/plugin/Mojo3563.java | {
"start": 1289,
"end": 3237
} | class ____ extends AbstractMojo {
/**
* @parameter default-value="${project}"
*/
private MavenProject project;
/**
* @parameter
* @required
*/
private File foo;
public void execute() throws MojoExecutionException, MojoFailureException {
Model model = project.getModel();
String property = model.getProperties().getProperty("test");
if (property == null) {
throw new MojoExecutionException("Could not find property.");
}
File testFile = new File(property.substring(property.indexOf(":") + 1));
if (!testFile.exists()) {
throw new MojoExecutionException(
"Test file does not exist: File = " + testFile.getAbsolutePath() + "Property = " + property);
}
getLog().info("Property = " + property);
File f = new File(project.getBuild().getOutputDirectory(), "foo.txt");
getLog().info("Creating test file using project.getBuild().getDirectory(): " + f);
String testValue = "" + System.currentTimeMillis();
FileWriter w = null;
try {
f.getParentFile().mkdirs();
w = new FileWriter(f);
w.write(testValue);
} catch (IOException e) {
throw new MojoExecutionException("Failed to write test file.", e);
} finally {
IOUtil.close(w);
}
getLog().info("Attempting to read test file using path from plugin parameter: " + foo);
BufferedReader r = null;
try {
r = new BufferedReader(new FileReader(foo));
if (!testValue.equals(r.readLine())) {
throw new MojoExecutionException("Test file: " + foo + " has wrong contents.");
}
} catch (IOException e) {
throw new MojoExecutionException("Failed to read test file.", e);
} finally {
IOUtil.close(r);
}
}
}
| Mojo3563 |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/CamelEvent.java | {
"start": 11603,
"end": 11787
} | interface ____ extends CamelEvent {
Object getService();
@Override
default Object getSource() {
return getService();
}
}
| ServiceEvent |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/util/datetime/FixedDateFormat.java | {
"start": 1495,
"end": 1676
} | class ____ {
/**
* Enumeration over the supported date/time format patterns.
* <p>
* Package protected for unit tests.
* </p>
*/
public | FixedDateFormat |
java | quarkusio__quarkus | extensions/jackson/runtime/src/main/java/io/quarkus/jackson/runtime/JacksonSupport.java | {
"start": 137,
"end": 245
} | interface ____ {
Optional<PropertyNamingStrategies.NamingBase> configuredNamingStrategy();
}
| JacksonSupport |
java | quarkusio__quarkus | tcks/microprofile-graphql/src/main/java/io/quarkus/tck/graphql/GraphQLArchiveProcessor.java | {
"start": 379,
"end": 1024
} | class ____ implements ApplicationArchiveProcessor {
private static final Logger LOG = Logger.getLogger(GraphQLArchiveProcessor.class.getName());
@Override
public void process(Archive<?> applicationArchive, TestClass testClass) {
if (applicationArchive instanceof WebArchive) {
LOG.info("\n ================================================================================"
+ "\n Testing [" + testClass.getName() + "]"
+ "\n ================================================================================"
+ "\n");
}
}
}
| GraphQLArchiveProcessor |
java | quarkusio__quarkus | extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/reactive/ReactiveMongoDatabase.java | {
"start": 8054,
"end": 8459
} | class ____ decode each document into
* @param <T> the target document type of the iterable
* @return stream of collection descriptor
*/
<T> Multi<T> listCollections(ClientSession clientSession, Class<T> clazz);
/**
* Finds all the collections in this database.
*
* @param clientSession the client session with which to associate this operation
* @param clazz the | to |
java | apache__flink | flink-test-utils-parent/flink-test-utils/src/main/java/org/apache/flink/test/util/AbstractTestBaseJUnit4.java | {
"start": 1271,
"end": 2228
} | class ____ unit tests that run multiple tests and want to reuse the same Flink cluster. This
* saves a significant amount of time, since the startup and shutdown of the Flink clusters
* (including actor systems, etc) usually dominates the execution of the actual tests.
*
* <p>To write a unit test against this test base, simply extend it and add one or more regular test
* methods and retrieve the StreamExecutionEnvironment from the context:
*
* <pre>
* {@literal @}Test
* public void someTest() {
* ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();
* // test code
* env.execute();
* }
*
* {@literal @}Test
* public void anotherTest() {
* StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
* // test code
* env.execute();
* }
*
* </pre>
*
* @deprecated Use {@link AbstractTestBase} instead.
*/
@Deprecated
public abstract | for |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/task/reduce/InMemoryWriter.java | {
"start": 1384,
"end": 2813
} | class ____<K, V> extends Writer<K, V> {
private DataOutputStream out;
public InMemoryWriter(BoundedByteArrayOutputStream arrayStream) {
super(null);
this.out =
new DataOutputStream(new IFileOutputStream(arrayStream));
}
public void append(K key, V value) throws IOException {
throw new UnsupportedOperationException
("InMemoryWriter.append(K key, V value");
}
public void append(DataInputBuffer key, DataInputBuffer value)
throws IOException {
int keyLength = key.getLength() - key.getPosition();
if (keyLength < 0) {
throw new IOException("Negative key-length not allowed: " + keyLength +
" for " + key);
}
int valueLength = value.getLength() - value.getPosition();
if (valueLength < 0) {
throw new IOException("Negative value-length not allowed: " +
valueLength + " for " + value);
}
WritableUtils.writeVInt(out, keyLength);
WritableUtils.writeVInt(out, valueLength);
out.write(key.getData(), key.getPosition(), keyLength);
out.write(value.getData(), value.getPosition(), valueLength);
}
public void close() throws IOException {
// Write EOF_MARKER for key/value length
WritableUtils.writeVInt(out, IFile.EOF_MARKER);
WritableUtils.writeVInt(out, IFile.EOF_MARKER);
// Close the stream
out.close();
out = null;
}
}
| InMemoryWriter |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/index/store/StoreTests.java | {
"start": 4887,
"end": 6647
} | class ____ extends ESTestCase {
private static final IndexSettings INDEX_SETTINGS = IndexSettingsModule.newIndexSettings(
"index",
Settings.builder().put(IndexMetadata.SETTING_VERSION_CREATED, IndexVersion.current()).build()
);
private static final Version MIN_SUPPORTED_LUCENE_VERSION = IndexVersions.MINIMUM_COMPATIBLE.luceneVersion();
public void testRefCount() {
final ShardId shardId = new ShardId("index", "_na_", 1);
IndexSettings indexSettings = INDEX_SETTINGS;
Store store = new Store(shardId, indexSettings, StoreTests.newDirectory(random()), new DummyShardLock(shardId));
int incs = randomIntBetween(1, 100);
for (int i = 0; i < incs; i++) {
if (randomBoolean()) {
store.incRef();
} else {
assertTrue(store.tryIncRef());
}
store.ensureOpen();
}
for (int i = 0; i < incs; i++) {
store.decRef();
store.ensureOpen();
}
store.incRef();
store.close();
for (int i = 0; i < incs; i++) {
if (randomBoolean()) {
store.incRef();
} else {
assertTrue(store.tryIncRef());
}
store.ensureOpen();
}
for (int i = 0; i < incs; i++) {
store.decRef();
store.ensureOpen();
}
store.decRef();
assertThat(store.refCount(), Matchers.equalTo(0));
assertFalse(store.tryIncRef());
expectThrows(IllegalStateException.class, store::incRef);
expectThrows(IllegalStateException.class, store::ensureOpen);
}
public void testNewChecksums() throws IOException {
| StoreTests |
java | spring-projects__spring-boot | module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/remote/client/HttpHeaderInterceptor.java | {
"start": 1234,
"end": 2033
} | class ____ implements ClientHttpRequestInterceptor {
private final String name;
private final String value;
/**
* Creates a new {@link HttpHeaderInterceptor} instance.
* @param name the header name to populate. Cannot be null or empty.
* @param value the header value to populate. Cannot be null or empty.
*/
public HttpHeaderInterceptor(String name, String value) {
Assert.hasLength(name, "'name' must not be empty");
Assert.hasLength(value, "'value' must not be empty");
this.name = name;
this.value = value;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
throws IOException {
request.getHeaders().add(this.name, this.value);
return execution.execute(request, body);
}
}
| HttpHeaderInterceptor |
java | netty__netty | codec-http/src/main/java/io/netty/handler/codec/http/HttpClientCodec.java | {
"start": 11738,
"end": 12687
} | class ____ extends HttpRequestEncoder {
boolean upgraded;
@Override
protected void encode(
ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
if (upgraded) {
// HttpObjectEncoder overrides .write and does not release msg, so we don't need to retain it here
out.add(msg);
return;
}
if (msg instanceof HttpRequest) {
queue.offer(((HttpRequest) msg).method());
}
super.encode(ctx, msg, out);
if (failOnMissingResponse && !done) {
// check if the request is chunked if so do not increment
if (msg instanceof LastHttpContent) {
// increment as its the last chunk
requestResponseCounter.incrementAndGet();
}
}
}
}
private final | Encoder |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/ql/TreatKeywordTest.java | {
"start": 10909,
"end": 11407
} | class ____ {
@Id
public Integer id;
public String name;
@ManyToOne( fetch = FetchType.LAZY )
public JoinedEntity other;
public JoinedEntity() {
}
public JoinedEntity(Integer id, String name) {
this.id = id;
this.name = name;
}
public JoinedEntity(Integer id, String name, JoinedEntity other) {
this.id = id;
this.name = name;
this.other = other;
}
}
@Entity( name = "JoinedEntitySubclass" )
@Table( name = "JoinedEntitySubclass" )
public static | JoinedEntity |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/boot/BootLogging.java | {
"start": 1218,
"end": 7048
} | interface ____ extends BasicLogger {
String NAME = SubSystemLogging.BASE + ".boot";
BootLogging BOOT_LOGGER = Logger.getMessageLogger( MethodHandles.lookup(), BootLogging.class, NAME );
@LogMessage(level = WARN)
@Message(id = 160101, value = "Duplicate generator name: '%s'")
void duplicateGeneratorName(String name);
@LogMessage(level = DEBUG)
@Message(id = 160111, value = "Package not found or no package-info.java: %s")
void packageNotFound(String packageName);
@LogMessage(level = WARN)
@Message(id = 160112, value = "LinkageError while attempting to load package: %s")
void linkageError(String packageName, @Cause LinkageError e);
@LogMessage(level = TRACE)
@Message(id = 160121, value = "Trying via [new URL(\"%s\")]")
void tryingURL(String name);
@LogMessage(level = TRACE)
@Message(id = 160122, value = "Trying via [ClassLoader.getResourceAsStream(\"%s\")]")
void tryingClassLoader(String name);
@LogMessage(level = WARN)
@Message(id = 160130, value = "Ignoring unique constraints specified on table generator [%s]")
void ignoringTableGeneratorConstraints(String name);
@LogMessage(level = WARN)
@Message(
id = 160131,
value = """
@Convert annotation applied to Map attribute [%s] did not explicitly specify\
'attributeName="key" or 'attributeName="value"' as required by spec;\
attempting to infer whether converter applies to key or value"""
)
void nonCompliantMapConversion(String collectionRole);
@LogMessage(level = WARN)
@Message(
id = 160133,
value = """
'%1$s.%2$s' uses both @NotFound and FetchType.LAZY;\
@ManyToOne and @OneToOne associations mapped with @NotFound are forced to EAGER fetching""")
void ignoreNotFoundWithFetchTypeLazy(String entity, String association);
// --- New typed TRACE/DEBUG messages for boot internals ---
@LogMessage(level = TRACE)
@Message(id = 160140, value = "Binding formula: %s")
void bindingFormula(String formula);
@LogMessage(level = TRACE)
@Message(id = 160141, value = "Binding column: %s")
void bindingColumn(String column);
@LogMessage(level = TRACE)
@Message(id = 160142, value = "Column mapping overridden for property: %s")
void columnMappingOverridden(String propertyName);
@LogMessage(level = TRACE)
@Message(id = 160143, value = "Could not perform @ColumnDefault lookup as 'PropertyData' did not give access to XProperty")
void couldNotPerformColumnDefaultLookup();
@LogMessage(level = TRACE)
@Message(id = 160144, value = "Could not perform @GeneratedColumn lookup as 'PropertyData' did not give access to XProperty")
void couldNotPerformGeneratedColumnLookup();
@LogMessage(level = TRACE)
@Message(id = 160145, value = "Could not perform @Check lookup as 'PropertyData' did not give access to XProperty")
void couldNotPerformCheckLookup();
@LogMessage(level = TRACE)
@Message(id = 160146, value = "Binding embeddable with path: %s")
void bindingEmbeddable(String path);
@LogMessage(level = TRACE)
@Message(id = 160147, value = "Binding filter definition: %s")
void bindingFilterDefinition(String name);
@LogMessage(level = TRACE)
@Message(id = 160148, value = "Second pass for collection: %s")
void secondPassForCollection(String role);
@LogMessage(level = TRACE)
@Message(id = 160149, value = "Binding collection role: %s")
void bindingCollectionRole(String role);
@LogMessage(level = TRACE)
@Message(id = 160150, value = "Binding one-to-many association through foreign key: %s")
void bindingOneToManyThroughForeignKey(String role);
@LogMessage(level = TRACE)
@Message(id = 160151, value = "Binding one-to-many association through association table: %s")
void bindingOneToManyThroughAssociationTable(String role);
@LogMessage(level = TRACE)
@Message(id = 160152, value = "Binding many-to-many association through association table: %s")
void bindingManyToManyThroughAssociationTable(String role);
@LogMessage(level = TRACE)
@Message(id = 160153, value = "Binding many-to-any: %s")
void bindingManyToAny(String role);
@LogMessage(level = TRACE)
@Message(id = 160154, value = "Binding element collection to collection table: %s")
void bindingElementCollectionToCollectionTable(String role);
@LogMessage(level = TRACE)
@Message(id = 160155, value = "Import: %s -> %s")
void importEntry(String importName, String className);
@LogMessage(level = TRACE)
@Message(id = 160156, value = "Processing association property references")
void processingAssociationPropertyReferences();
@LogMessage(level = TRACE)
@Message(id = 160157, value = "Mapping class: %s -> %s")
void mappingClassToTable(String entityName, String tableName);
@LogMessage(level = TRACE)
@Message(id = 160158, value = "Mapping joined-subclass: %s -> %s")
void mappingJoinedSubclassToTable(String entityName, String tableName);
@LogMessage(level = TRACE)
@Message(id = 160159, value = "Mapping union-subclass: %s -> %s")
void mappingUnionSubclassToTable(String entityName, String tableName);
@LogMessage(level = TRACE)
@Message(id = 160160, value = "Mapped property: %s -> [%s]")
void mappedProperty(String propertyName, String columns);
@LogMessage(level = TRACE)
@Message(id = 160161, value = "Binding dynamic component [%s]")
void bindingDynamicComponent(String role);
@LogMessage(level = TRACE)
@Message(id = 160162, value = "Binding virtual component [%s] to owner class [%s]")
void bindingVirtualComponentToOwner(String role, String ownerClassName);
@LogMessage(level = TRACE)
@Message(id = 160163, value = "Binding virtual component [%s] as dynamic")
void bindingVirtualComponentAsDynamic(String role);
@LogMessage(level = TRACE)
@Message(id = 160164, value = "Binding component [%s]")
void bindingComponent(String role);
@LogMessage(level = TRACE)
@Message(id = 160165, value = "Attempting to determine component | BootLogging |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/net/TestStaticMapping.java | {
"start": 1500,
"end": 1760
} | class ____ a null configuration
* @return a new instance
*/
private StaticMapping newInstance() {
StaticMapping.resetMap();
return new StaticMapping();
}
/**
* Reset the map then create a new instance of the {@link StaticMapping}
* | with |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/scheduler/event/AppAddedSchedulerEvent.java | {
"start": 1227,
"end": 4205
} | class ____ extends SchedulerEvent {
private final ApplicationId applicationId;
private final String queue;
private final String user;
private final ReservationId reservationID;
private final boolean isAppRecovering;
private final Priority appPriority;
private final ApplicationPlacementContext placementContext;
private boolean unmanagedAM = false;
public AppAddedSchedulerEvent(ApplicationId applicationId, String queue,
String user) {
this(applicationId, queue, user, false, null, Priority.newInstance(0),
null);
}
public AppAddedSchedulerEvent(ApplicationId applicationId, String queue,
String user, ApplicationPlacementContext placementContext) {
this(applicationId, queue, user, false, null, Priority.newInstance(0),
placementContext);
}
public AppAddedSchedulerEvent(ApplicationId applicationId, String queue,
String user, ReservationId reservationID, Priority appPriority) {
this(applicationId, queue, user, false, reservationID, appPriority, null);
}
public AppAddedSchedulerEvent(String user,
ApplicationSubmissionContext submissionContext, boolean isAppRecovering,
Priority appPriority) {
this(submissionContext.getApplicationId(), submissionContext.getQueue(),
user, isAppRecovering, submissionContext.getReservationID(),
appPriority, null);
this.unmanagedAM = submissionContext.getUnmanagedAM();
}
public AppAddedSchedulerEvent(String user,
ApplicationSubmissionContext submissionContext, boolean isAppRecovering,
Priority appPriority, ApplicationPlacementContext placementContext) {
this(submissionContext.getApplicationId(), submissionContext.getQueue(),
user, isAppRecovering, submissionContext.getReservationID(),
appPriority, placementContext);
this.unmanagedAM = submissionContext.getUnmanagedAM();
}
public AppAddedSchedulerEvent(ApplicationId applicationId, String queue,
String user, boolean isAppRecovering, ReservationId reservationID,
Priority appPriority, ApplicationPlacementContext placementContext) {
super(SchedulerEventType.APP_ADDED);
this.applicationId = applicationId;
this.queue = queue;
this.user = user;
this.reservationID = reservationID;
this.isAppRecovering = isAppRecovering;
this.appPriority = appPriority;
this.placementContext = placementContext;
}
public ApplicationId getApplicationId() {
return applicationId;
}
public String getQueue() {
return queue;
}
public String getUser() {
return user;
}
public boolean getIsAppRecovering() {
return isAppRecovering;
}
public ReservationId getReservationID() {
return reservationID;
}
public Priority getApplicatonPriority() {
return appPriority;
}
public ApplicationPlacementContext getPlacementContext() {
return placementContext;
}
public boolean isUnmanagedAM() {
return unmanagedAM;
}
}
| AppAddedSchedulerEvent |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/oracle/OracleIsASetTest.java | {
"start": 882,
"end": 1502
} | class ____ extends TestCase {
public void test_is_a_set() throws Exception {
String sql = "SELECT customer_id, cust_address_ntab FROM customers_demo WHERE cust_address_ntab IS A SET;";
OracleStatementParser parser = new OracleStatementParser(sql);
SQLSelectStatement stmt = (SQLSelectStatement) parser.parseStatementList().get(0);
String text = TestUtils.outputOracle(stmt);
assertEquals("SELECT customer_id, cust_address_ntab\n" + "FROM customers_demo\n"
+ "WHERE cust_address_ntab IS A SET;", text);
System.out.println(text);
}
}
| OracleIsASetTest |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/component/file/stress/FileProducerAppendManyMessagesFastManualTest.java | {
"start": 1351,
"end": 3691
} | class ____ extends ContextTestSupport {
@Override
@BeforeEach
public void setUp() throws Exception {
super.setUp();
// create a big file
try (OutputStream fos = new BufferedOutputStream(Files.newOutputStream(testFile("big/data.txt")))) {
for (int i = 0; i < 1000; i++) {
String s = "Hello World this is a long line with number " + i + LS;
fos.write(s.getBytes());
}
}
}
@Test
public void testBigFile() throws Exception {
MockEndpoint mock = getMockEndpoint("mock:done");
mock.expectedMessageCount(1);
mock.setResultWaitTime(2 * 60000);
assertMockEndpointsSatisfied();
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from(fileUri("big?initialDelay=1000")).process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
// store a output stream we use for writing
FileOutputStream fos = new FileOutputStream(testFile("out/also-big.txt").toFile(), true);
exchange.setProperty("myStream", fos);
}
}).split(body().tokenize(LS)).streaming().to("log:processing?groupSize=1000").process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
OutputStream fos = exchange.getProperty("myStream", OutputStream.class);
byte[] data = exchange.getIn().getBody(byte[].class);
fos.write(data);
fos.write(LS.getBytes());
}
}).end().process(new Processor() {
@Override
public void process(Exchange exchange) throws Exception {
OutputStream fos = exchange.getProperty("myStream", OutputStream.class);
fos.close();
exchange.removeProperty("myStream");
}
}).to("mock:done");
}
};
}
}
| FileProducerAppendManyMessagesFastManualTest |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/ValueAnnotationsDeserTest.java | {
"start": 6387,
"end": 6652
} | class ____
{
Object[] _data;
@JsonDeserialize(contentAs=Long.class)
public void setData(Object[] o)
{ // should have proper type, but no need to coerce here
_data = o;
}
}
final static | ArrayContentHolder |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/recursive/comparison/properties/RecursiveComparisonAssert_isEqualTo_ignoringTransientFields_Test.java | {
"start": 941,
"end": 1907
} | class ____
extends WithComparingPropertiesIntrospectionStrategyBaseTest {
@Test
void should_fail_since_ignoringTransientFields_does_not_make_sense_for_properties() {
// GIVEN
var actual = new WithTransientFields("Jack transient", "Jack");
var expected = new WithTransientFields("John transient", "Jeff");
// WHEN
var illegalArgumentException = catchIllegalArgumentException(() -> assertThat(actual).usingRecursiveComparison(recursiveComparisonConfiguration)
.ignoringTransientFields()
.isEqualTo(expected));
// THEN
then(illegalArgumentException).hasMessage("ignoringTransientFields is not supported since we are comparing properties");
}
@SuppressWarnings("ClassCanBeRecord")
static | RecursiveComparisonAssert_isEqualTo_ignoringTransientFields_Test |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/imports/nested/TargetInOtherPackageMapper.java | {
"start": 346,
"end": 433
} | interface ____ {
TargetInOtherPackage map(Source source);
}
| TargetInOtherPackageMapper |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/jpa/compliance/AnnotationConverterAndEmbeddableTest.java | {
"start": 2228,
"end": 2906
} | class ____ {
protected Integer id;
protected String name;
protected Address address;
public Person() {
}
public Person(Integer id, String name, Address address) {
this.id = id;
this.name = name;
this.address = address;
}
@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;
}
@Embedded
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
@Embeddable
@Access(AccessType.PROPERTY)
public static | Person |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/protocol/GetRouterRegistrationRequest.java | {
"start": 1206,
"end": 1722
} | class ____ {
public static GetRouterRegistrationRequest newInstance() {
return StateStoreSerializer.newRecord(GetRouterRegistrationRequest.class);
}
public static GetRouterRegistrationRequest newInstance(String routerId) {
GetRouterRegistrationRequest request = newInstance();
request.setRouterId(routerId);
return request;
}
@Public
@Unstable
public abstract String getRouterId();
@Public
@Unstable
public abstract void setRouterId(String routerId);
} | GetRouterRegistrationRequest |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/util/LambdaUtils.java | {
"start": 1206,
"end": 1907
} | class ____ {
private LambdaUtils() {
}
/**
* Utility method to evaluate a callable and fill in the future
* with the result or the exception raised.
* Once this method returns, the future will have been evaluated to
* either a return value or an exception.
* @param <T> type of future
* @param result future for the result.
* @param call callable to invoke.
* @return the future passed in
*/
public static <T> CompletableFuture<T> eval(
final CompletableFuture<T> result,
final Callable<T> call) {
try {
result.complete(call.call());
} catch (Throwable tx) {
result.completeExceptionally(tx);
}
return result;
}
}
| LambdaUtils |
java | quarkusio__quarkus | test-framework/common/src/main/java/io/quarkus/test/common/GroovyClassValue.java | {
"start": 633,
"end": 804
} | class ____ {
private GroovyClassValue() {
}
public static void disable() {
System.setProperty("groovy.use.classvalue", "false");
}
}
| GroovyClassValue |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/query/hql/instantiation/DynamicInstantiationWithJoinAndGroupByAndParameterTest.java | {
"start": 2502,
"end": 3163
} | class ____ {
@Id
@GeneratedValue
private Long id;
private String firstname;
private String lastname;
public UserEntity() {
}
public UserEntity(String firstname, String lastname) {
this.firstname = firstname;
this.lastname = lastname;
}
public Long getId() {
return id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}
@Entity(name = "Action")
@Table(name = "Action")
public static | UserEntity |
java | spring-projects__spring-boot | documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/web/security/springwebflux/MyWebFluxSecurityConfiguration.java | {
"start": 1157,
"end": 1543
} | class ____ {
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.authorizeExchange((exchange) -> {
exchange.matchers(PathRequest.toStaticResources().atCommonLocations()).permitAll();
exchange.pathMatchers("/foo", "/bar").authenticated();
});
http.formLogin(withDefaults());
return http.build();
}
}
| MyWebFluxSecurityConfiguration |
java | apache__hadoop | hadoop-tools/hadoop-sls/src/main/java/org/apache/hadoop/yarn/sls/synthetic/SynthTraceJobProducer.java | {
"start": 16692,
"end": 21184
} | enum ____{
LOGNORM,
NORM
}
public Sample(Double val) throws JsonMappingException{
this(val, null);
}
public Sample(Double val, Double std) throws JsonMappingException{
this(val, std, null, null, null);
}
@JsonCreator
public Sample(@JsonProperty("val") Double val,
@JsonProperty("std") Double std, @JsonProperty("dist") String dist,
@JsonProperty("discrete") List<String> discrete,
@JsonProperty("weights") List<Double> weights)
throws JsonMappingException{
// Different Modes
// - Constant: val must be specified, all else null. Sampling will
// return val.
// - Distribution: val, std specified, dist optional (defaults to
// LogNormal). Sampling will sample from the appropriate distribution
// - Discrete: discrete must be set to a list of strings or numbers,
// weights optional (defaults to uniform)
if(val!=null){
if(std==null){
// Constant
if (dist != null || discrete != null || weights != null) {
throw JsonMappingException
.from((JsonParser) null, "Instantiation of " + Sample.class + " failed");
}
mode = Mode.CONST;
this.val = val;
this.std = 0;
this.dist = null;
this.discrete = null;
this.weights = null;
} else {
// Distribution
if (discrete != null || weights != null) {
throw JsonMappingException
.from((JsonParser) null, "Instantiation of " + Sample.class + " failed");
}
mode = Mode.DIST;
this.val = val;
this.std = std;
this.dist = dist!=null ? Dist.valueOf(dist) : DEFAULT_DIST;
this.discrete = null;
this.weights = null;
}
} else {
// Discrete
if (discrete == null) {
throw JsonMappingException
.from((JsonParser) null, "Instantiation of " + Sample.class + " failed");
}
mode = Mode.DISC;
this.val = 0;
this.std = 0;
this.dist = null;
this.discrete = discrete;
if(weights == null){
weights = new ArrayList<>(Collections.nCopies(
discrete.size(), 1.0));
}
if (weights.size() != discrete.size()) {
throw JsonMappingException
.from((JsonParser) null, "Instantiation of " + Sample.class + " failed");
}
this.weights = weights;
}
}
public void init(JDKRandomGenerator random){
if(this.rand != null){
throw new YarnRuntimeException("init called twice");
}
this.rand = random;
if(mode == Mode.DIST){
switch(this.dist){
case LOGNORM:
this.dist_instance = SynthUtils.getLogNormalDist(rand, val, std);
return;
case NORM:
this.dist_instance = SynthUtils.getNormalDist(rand, val, std);
return;
default:
throw new YarnRuntimeException("Unknown distribution " + dist.name());
}
}
}
public int getInt(){
return Math.toIntExact(getLong());
}
public long getLong(){
return Math.round(getDouble());
}
public double getDouble(){
return Double.parseDouble(getString());
}
public String getString(){
if(this.rand == null){
throw new YarnRuntimeException("getValue called without init");
}
switch(mode){
case CONST:
return Double.toString(val);
case DIST:
return Double.toString(dist_instance.sample());
case DISC:
return this.discrete.get(SynthUtils.getWeighted(this.weights, rand));
default:
throw new YarnRuntimeException("Unknown sampling mode " + mode.name());
}
}
@Override
public String toString(){
switch(mode){
case CONST:
return "value: " + val;
case DIST:
return "value: " + this.val + " std: " + this.std + " dist: "
+ this.dist.name();
case DISC:
return "discrete: " + this.discrete + ", weights: " + this.weights;
default:
throw new YarnRuntimeException("Unknown sampling mode " + mode.name());
}
}
}
/**
* This is used to define time-varying probability of a job start-time (e.g.,
* to simulate daily patterns).
*/
@SuppressWarnings({ "membername", "checkstyle:visibilitymodifier" })
public static | Dist |
java | google__error-prone | core/src/test/java/com/google/errorprone/testdata/MultipleTopLevelClassesWithNoErrors.java | {
"start": 1124,
"end": 1240
} | class ____ {
int foo;
int bar;
public Foo3(int foo, int bar) {
this.foo = foo;
this.bar = bar;
}
}
| Foo3 |
java | apache__camel | core/camel-api/src/main/java/org/apache/camel/spi/RouteController.java | {
"start": 1177,
"end": 9064
} | interface ____ extends CamelContextAware, StaticService {
/**
* Gets the logging level used for logging route activity (such as starting and stopping routes). The default
* logging level is DEBUG.
*/
LoggingLevel getLoggingLevel();
/**
* Sets the logging level used for logging route activity (such as starting and stopping routes). The default
* logging level is DEBUG.
*/
void setLoggingLevel(LoggingLevel loggingLevel);
/**
* Whether this route controller is a regular or supervising controller.
*/
boolean isSupervising();
/**
* Enables supervising {@link RouteController}.
*/
SupervisingRouteController supervising();
/**
* Adapts this {@link org.apache.camel.spi.RouteController} to the specialized type.
* <p/>
* For example to adapt to <tt>SupervisingRouteController</tt>.
*
* @param type the type to adapt to
* @return this {@link org.apache.camel.CamelContext} adapted to the given type
*/
<T extends RouteController> T adapt(Class<T> type);
/**
* Return the list of routes controlled by this controller.
*
* @return the list of controlled routes
*/
Collection<Route> getControlledRoutes();
/**
* Starts all the routes which currently is not started.
*
* @throws Exception is thrown if a route could not be started for whatever reason
*/
void startAllRoutes() throws Exception;
/**
* Stops all the routes
*
* @throws Exception is thrown if a route could not be stopped for whatever reason
*/
void stopAllRoutes() throws Exception;
/**
* Stops and removes all the routes
*
* @throws Exception is thrown if a route could not be stopped or removed for whatever reason
*/
void removeAllRoutes() throws Exception;
/**
* Indicates whether the route controller is doing initial starting of the routes.
*/
boolean isStartingRoutes();
/**
* Indicates if the route controller has routes that are currently unhealthy such as they have not yet been
* successfully started, and if being supervised then the route can either be pending restarts or failed all restart
* attempts and are exhausted.
*/
boolean hasUnhealthyRoutes();
/**
* Reloads all the routes
*
* @throws Exception is thrown if a route could not be reloaded for whatever reason
*/
void reloadAllRoutes() throws Exception;
/**
* Indicates whether current thread is reloading route(s).
* <p/>
* This can be useful to know by {@link LifecycleStrategy} or the likes, in case they need to react differently.
*
* @return <tt>true</tt> if current thread is reloading route(s), or <tt>false</tt> if not.
*/
boolean isReloadingRoutes();
/**
* Returns the current status of the given route
*
* @param routeId the route id
* @return the status for the route
*/
ServiceStatus getRouteStatus(String routeId);
/**
* Starts the given route if it has been previously stopped
*
* @param routeId the route id
* @throws Exception is thrown if the route could not be started for whatever reason
*/
void startRoute(String routeId) throws Exception;
/**
* Stops the given route using {@link org.apache.camel.spi.ShutdownStrategy}.
*
* @param routeId the route id
* @throws Exception is thrown if the route could not be stopped for whatever reason
* @see #suspendRoute(String)
*/
void stopRoute(String routeId) throws Exception;
/**
* Stops and marks the given route as failed (health check is DOWN) due to a caused exception.
*
* @param routeId the route id
* @param cause the exception that is causing this route to be stopped and marked as failed
* @throws Exception is thrown if the route could not be stopped for whatever reason
* @see #suspendRoute(String)
*/
void stopRoute(String routeId, Throwable cause) throws Exception;
/**
* Stops the given route using {@link org.apache.camel.spi.ShutdownStrategy} with a specified timeout.
*
* @param routeId the route id
* @param timeout timeout
* @param timeUnit the unit to use
* @throws Exception is thrown if the route could not be stopped for whatever reason
* @see #suspendRoute(String, long, java.util.concurrent.TimeUnit)
*/
void stopRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception;
/**
* Stops the given route using {@link org.apache.camel.spi.ShutdownStrategy} with a specified timeout and optional
* abortAfterTimeout mode.
*
* @param routeId the route id
* @param timeout timeout
* @param timeUnit the unit to use
* @param abortAfterTimeout should abort shutdown after timeout
* @return <tt>true</tt> if the route is stopped before the timeout
* @throws Exception is thrown if the route could not be stopped for whatever reason
* @see #suspendRoute(String, long, java.util.concurrent.TimeUnit)
*/
boolean stopRoute(String routeId, long timeout, TimeUnit timeUnit, boolean abortAfterTimeout) throws Exception;
/**
* Suspends the given route using {@link org.apache.camel.spi.ShutdownStrategy}.
* <p/>
* Suspending a route is more gently than stopping, as the route consumers will be suspended (if they support)
* otherwise the consumers will be stopped.
* <p/>
* By suspending the route services will be kept running (if possible) and therefore its faster to resume the route.
* <p/>
* If the route does <b>not</b> support suspension the route will be stopped instead
*
* @param routeId the route id
* @throws Exception is thrown if the route could not be suspended for whatever reason
*/
void suspendRoute(String routeId) throws Exception;
/**
* Suspends the given route using {@link org.apache.camel.spi.ShutdownStrategy} with a specified timeout.
* <p/>
* Suspending a route is more gently than stopping, as the route consumers will be suspended (if they support)
* otherwise the consumers will be stopped.
* <p/>
* By suspending the route services will be kept running (if possible) and therefore its faster to resume the route.
* <p/>
* If the route does <b>not</b> support suspension the route will be stopped instead
*
* @param routeId the route id
* @param timeout timeout
* @param timeUnit the unit to use
* @throws Exception is thrown if the route could not be suspended for whatever reason
*/
void suspendRoute(String routeId, long timeout, TimeUnit timeUnit) throws Exception;
/**
* Resumes the given route if it has been previously suspended
* <p/>
* If the route does <b>not</b> support suspension the route will be started instead
*
* @param routeId the route id
* @throws Exception is thrown if the route could not be resumed for whatever reason
*/
void resumeRoute(String routeId) throws Exception;
/**
* Starts all the routes in the given group
*
* @param routeGroup the route group
* @throws Exception is thrown if any of the routes could not be started for whatever reason
*/
void startRouteGroup(String routeGroup) throws Exception;
/**
* Stops all the routes in the given group
*
* @param routeGroup the route group
* @throws Exception is thrown if any of the routes could not be stopped for whatever reason
*/
void stopRouteGroup(String routeGroup) throws Exception;
}
| RouteController |
java | apache__flink | flink-state-backends/flink-statebackend-forst/src/test/java/org/apache/flink/state/forst/ForStStateExecutorTest.java | {
"start": 1824,
"end": 17217
} | class ____ extends ForStDBOperationTestBase {
@Test
@SuppressWarnings("unchecked")
void testExecuteValueStateRequest() throws Exception {
ForStStateExecutor forStStateExecutor =
new ForStStateExecutor(false, false, 3, 1, db, new WriteOptions());
ForStValueState<Integer, VoidNamespace, String> state1 =
buildForStValueState("value-state-1");
ForStValueState<Integer, VoidNamespace, String> state2 =
buildForStValueState("value-state-2");
AsyncRequestContainer asyncRequestContainer = forStStateExecutor.createRequestContainer();
assertTrue(asyncRequestContainer.isEmpty());
// 1. Update value state: keyRange [0, keyNum)
int keyNum = 1000;
for (int i = 0; i < keyNum; i++) {
ForStValueState<Integer, VoidNamespace, String> state = (i % 2 == 0 ? state1 : state2);
asyncRequestContainer.offer(
buildStateRequest(state, StateRequestType.VALUE_UPDATE, i, "test-" + i, i * 2));
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
List<StateRequest<?, ?, ?, ?>> checkList = new ArrayList<>();
asyncRequestContainer = forStStateExecutor.createRequestContainer();
// 2. Get value state: keyRange [0, keyNum)
// Update value state: keyRange [keyNum, keyNum + 100]
for (int i = 0; i < keyNum; i++) {
ForStValueState<Integer, VoidNamespace, String> state = (i % 2 == 0 ? state1 : state2);
StateRequest<?, ?, ?, ?> getRequest =
buildStateRequest(state, StateRequestType.VALUE_GET, i, null, i * 2);
asyncRequestContainer.offer(getRequest);
checkList.add(getRequest);
}
for (int i = keyNum; i < keyNum + 100; i++) {
ForStValueState<Integer, VoidNamespace, String> state = (i % 2 == 0 ? state1 : state2);
asyncRequestContainer.offer(
buildStateRequest(state, StateRequestType.VALUE_UPDATE, i, "test-" + i, i * 2));
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
// 3. Check value state Get result : [0, keyNum)
for (StateRequest<?, ?, ?, ?> getRequest : checkList) {
assertThat(getRequest.getRequestType()).isEqualTo(StateRequestType.VALUE_GET);
int key = (Integer) getRequest.getRecordContext().getKey();
assertThat(getRequest.getRecordContext().getRecord()).isEqualTo(key * 2);
assertThat(((TestAsyncFuture<String>) getRequest.getFuture()).getCompletedResult())
.isEqualTo("test-" + key);
}
// 4. Clear value state: keyRange [keyNum - 100, keyNum)
// Update state with null-value : keyRange [keyNum, keyNum + 100]
asyncRequestContainer = forStStateExecutor.createRequestContainer();
for (int i = keyNum - 100; i < keyNum; i++) {
ForStValueState<Integer, VoidNamespace, String> state = (i % 2 == 0 ? state1 : state2);
asyncRequestContainer.offer(
buildStateRequest(state, StateRequestType.CLEAR, i, null, i * 2));
}
for (int i = keyNum; i < keyNum + 100; i++) {
ForStValueState<Integer, VoidNamespace, String> state = (i % 2 == 0 ? state1 : state2);
asyncRequestContainer.offer(
buildStateRequest(state, StateRequestType.VALUE_UPDATE, i, null, i * 2));
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
// 5. Check that the deleted value is null : keyRange [keyNum - 100, keyNum + 100)
asyncRequestContainer = forStStateExecutor.createRequestContainer();
checkList.clear();
for (int i = keyNum - 100; i < keyNum + 100; i++) {
ForStValueState<Integer, VoidNamespace, String> state = (i % 2 == 0 ? state1 : state2);
StateRequest<?, ?, ?, ?> getRequest =
buildStateRequest(state, StateRequestType.VALUE_GET, i, null, i * 2);
asyncRequestContainer.offer(getRequest);
checkList.add(getRequest);
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
for (StateRequest<?, ?, ?, ?> getRequest : checkList) {
assertThat(getRequest.getRequestType()).isEqualTo(StateRequestType.VALUE_GET);
assertThat(((TestAsyncFuture<String>) getRequest.getFuture()).getCompletedResult())
.isEqualTo(null);
}
forStStateExecutor.shutdown();
}
@Test
void testExecuteMapStateRequest() throws Exception {
ForStStateExecutor forStStateExecutor =
new ForStStateExecutor(true, false, 3, 1, db, new WriteOptions());
ForStMapState<Integer, VoidNamespace, String, String> state =
buildForStMapState("map-state");
AsyncRequestContainer asyncRequestContainer = forStStateExecutor.createRequestContainer();
assertTrue(asyncRequestContainer.isEmpty());
// 1. prepare put data: keyRange [0, 100)
for (int i = 0; i < 100; i++) {
asyncRequestContainer.offer(
buildMapRequest(
state,
StateRequestType.MAP_PUT,
i,
Tuple2.of("uk-" + i, "uv-" + i),
i * 2));
}
for (int i = 50; i < 100; i++) {
HashMap<String, String> map = new HashMap<>(100);
for (int j = 0; j < 50; j++) {
map.put("ukk-" + j, "uvv-" + j);
}
asyncRequestContainer.offer(
buildMapRequest(state, StateRequestType.MAP_PUT_ALL, i, map, i * 2));
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
asyncRequestContainer = forStStateExecutor.createRequestContainer();
List<StateRequest<?, ?, ?, ?>> checkList = new ArrayList<>();
// 2. check the number of user key under primary key is correct
for (int i = 0; i < 100; i++) {
StateRequest<?, ?, ?, ?> iterRequest =
buildStateRequest(state, StateRequestType.MAP_ITER_KEY, i, null, i * 2);
asyncRequestContainer.offer(iterRequest);
checkList.add(iterRequest);
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
for (int i = 0; i < 50; i++) { // 1 user key per primary key
StateIterator<String> iter =
(StateIterator<String>)
((TestAsyncFuture) checkList.get(i).getFuture()).getCompletedResult();
AtomicInteger count = new AtomicInteger(0);
iter.onNext(
k -> {
count.incrementAndGet();
});
assertThat(count.get()).isEqualTo(1);
assertThat(iter.isEmpty()).isFalse();
}
for (int i = 50; i < 100; i++) { // 51 user keys per primary key
StateIterator<String> iter =
(StateIterator<String>)
((TestAsyncFuture) checkList.get(i).getFuture()).getCompletedResult();
AtomicInteger count = new AtomicInteger(0);
iter.onNext(
k -> {
count.incrementAndGet();
});
assertThat(count.get()).isEqualTo(51);
assertThat(iter.isEmpty()).isFalse();
}
asyncRequestContainer = forStStateExecutor.createRequestContainer();
// 3. delete primary key [75,100)
for (int i = 75; i < 100; i++) {
asyncRequestContainer.offer(
buildMapRequest(state, StateRequestType.CLEAR, i, null, i * 2));
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
asyncRequestContainer = forStStateExecutor.createRequestContainer();
checkList.clear();
// 4. check primary key [75,100) is deleted
for (int i = 0; i < 100; i++) {
StateRequest<?, ?, ?, ?> iterRequest =
buildStateRequest(state, StateRequestType.MAP_IS_EMPTY, i, null, i * 2);
asyncRequestContainer.offer(iterRequest);
checkList.add(iterRequest);
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
for (int i = 0; i < 75; i++) { // not empty
boolean empty =
(Boolean) ((TestAsyncFuture) checkList.get(i).getFuture()).getCompletedResult();
assertThat(empty).isFalse();
}
for (int i = 75; i < 100; i++) { // empty
boolean empty =
(Boolean) ((TestAsyncFuture) checkList.get(i).getFuture()).getCompletedResult();
assertThat(empty).isTrue();
}
forStStateExecutor.shutdown();
}
@Test
@SuppressWarnings("unchecked")
public void testExecuteAggregatingStateRequest() throws Exception {
ForStStateExecutor forStStateExecutor =
new ForStStateExecutor(false, false, 4, 1, db, new WriteOptions());
ForStAggregatingState<String, ?, Integer, Integer, Integer> state =
buildForStSumAggregateState("agg-state-1");
AsyncRequestContainer asyncRequestContainer = forStStateExecutor.createRequestContainer();
assertTrue(asyncRequestContainer.isEmpty());
// 1. init aggregateValue for every 1000 key
int keyNum = 1000;
for (int i = 0; i < keyNum; i++) {
asyncRequestContainer.offer(
buildStateRequest(
state, StateRequestType.AGGREGATING_ADD, "" + i, i, "record" + i));
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
// 2. get all value and verify
List<StateRequest<String, ?, Integer, Integer>> requests = new ArrayList<>();
asyncRequestContainer = forStStateExecutor.createRequestContainer();
for (int i = 0; i < keyNum; i++) {
StateRequest<String, ?, Integer, Integer> r =
(StateRequest<String, ?, Integer, Integer>)
buildStateRequest(
state,
StateRequestType.AGGREGATING_GET,
"" + i,
null,
"record" + i);
requests.add(r);
asyncRequestContainer.offer(r);
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
for (StateRequest<String, ?, Integer, Integer> request : requests) {
assertThat(request.getRequestType()).isEqualTo(StateRequestType.AGGREGATING_GET);
String key = request.getRecordContext().getKey();
assertThat(request.getRecordContext().getRecord()).isEqualTo("record" + key);
assertThat(((TestAsyncFuture<Integer>) request.getFuture()).getCompletedResult())
.isEqualTo(Integer.parseInt(key));
}
// 3. add more value for the aggregate state
asyncRequestContainer = forStStateExecutor.createRequestContainer();
int addCnt = 10;
for (int i = 0; i < keyNum; i++) {
for (int j = 0; j < addCnt; j++) {
StateRequest<String, ?, Integer, Integer> r =
(StateRequest<String, ?, Integer, Integer>)
buildStateRequest(
state, StateRequestType.AGGREGATING_ADD, "" + i, 1, i * 2);
requests.add(r);
asyncRequestContainer.offer(r);
}
}
// clear first 100 state
for (int i = 0; i < 100; i++) {
StateRequest<String, ?, Integer, Integer> r =
(StateRequest<String, ?, Integer, Integer>)
buildStateRequest(
state, StateRequestType.CLEAR, "" + i, null, "record" + i);
requests.add(r);
asyncRequestContainer.offer(r);
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
// 4. read and verify the updated aggregate state
requests = new ArrayList<>();
asyncRequestContainer = forStStateExecutor.createRequestContainer();
for (int i = 0; i < keyNum; i++) {
StateRequest<String, ?, Integer, Integer> r =
(StateRequest<String, ?, Integer, Integer>)
buildStateRequest(
state,
StateRequestType.AGGREGATING_GET,
"" + i,
null,
"record" + i);
requests.add(r);
asyncRequestContainer.offer(r);
}
forStStateExecutor.executeBatchRequests(asyncRequestContainer).get();
for (int i = 0; i < 100; i++) {
StateRequest<String, ?, Integer, Integer> request = requests.get(i);
assertThat(request.getRequestType()).isEqualTo(StateRequestType.AGGREGATING_GET);
assertThat(((TestAsyncFuture<Integer>) request.getFuture()).getCompletedResult())
.isEqualTo(null);
}
for (int i = 100; i < keyNum; i++) {
StateRequest<String, ?, Integer, Integer> request = requests.get(i);
assertThat(request.getRequestType()).isEqualTo(StateRequestType.AGGREGATING_GET);
String key = request.getRecordContext().getKey();
assertThat(request.getRecordContext().getRecord()).isEqualTo("record" + key);
assertThat(((TestAsyncFuture<Integer>) request.getFuture()).getCompletedResult())
.isEqualTo(1);
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
private <K, N, V, R> StateRequest<?, ?, ?, ?> buildStateRequest(
AbstractKeyedState<K, N, V> innerTable,
StateRequestType requestType,
K key,
V value,
R record) {
int keyGroup = KeyGroupRangeAssignment.assignToKeyGroup(key, 128);
RecordContext<K> recordContext =
new RecordContext<>(record, key, t -> {}, keyGroup, new Epoch(0), 0);
TestAsyncFuture stateFuture = new TestAsyncFuture<>();
return new StateRequest<>(
innerTable, requestType, false, value, stateFuture, recordContext);
}
@SuppressWarnings({"rawtypes", "unchecked"})
private <K, N, UK, UV, R> StateRequest<?, ?, ?, ?> buildMapRequest(
ForStMapState<K, N, UK, UV> innerTable,
StateRequestType requestType,
K key,
Object value,
R record) {
int keyGroup = KeyGroupRangeAssignment.assignToKeyGroup(key, 128);
RecordContext<K> recordContext =
new RecordContext<>(record, key, t -> {}, keyGroup, new Epoch(0), 0);
TestAsyncFuture stateFuture = new TestAsyncFuture<>();
return new StateRequest<>(
innerTable, requestType, false, value, stateFuture, recordContext);
}
}
| ForStStateExecutorTest |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/parser/creator/JSONCreatorTest8.java | {
"start": 658,
"end": 1003
} | class ____ {
private int id;
private String name;
@JSONCreator
public Entity(@JSONField(name = "id") int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| Entity |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/util/TestYarnVersionInfo.java | {
"start": 1160,
"end": 2231
} | class ____ {
/**
* Test the yarn version info routines.
* @throws IOException
*/
@Test
void versionInfoGenerated() throws IOException {
// can't easily know what the correct values are going to be so just
// make sure they aren't Unknown
assertNotEquals("Unknown", YarnVersionInfo.getVersion(), "getVersion returned Unknown");
assertNotEquals("Unknown", YarnVersionInfo.getUser(), "getUser returned Unknown");
assertNotEquals("Unknown", YarnVersionInfo.getSrcChecksum(), "getSrcChecksum returned Unknown");
// these could be Unknown if the VersionInfo generated from code not in svn or git
// so just check that they return something
assertNotNull(YarnVersionInfo.getUrl(), "getUrl returned null");
assertNotNull(YarnVersionInfo.getRevision(), "getRevision returned null");
assertNotNull(YarnVersionInfo.getBranch(), "getBranch returned null");
assertTrue(YarnVersionInfo.getBuildVersion().contains("source checksum"),
"getBuildVersion check doesn't contain: source checksum");
}
}
| TestYarnVersionInfo |
java | spring-projects__spring-security | config/src/test/java/org/springframework/security/config/annotation/web/configurers/NamespaceHttpJeeTests.java | {
"start": 2488,
"end": 4174
} | class ____ {
public final SpringTestContext spring = new SpringTestContext(this);
@Autowired
MockMvc mvc;
@Test
public void requestWhenJeeUserThenBehaviorDiffersFromNamespaceForRoleNames() throws Exception {
this.spring.register(JeeMappableRolesConfig.class, BaseController.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("joe");
this.mvc.perform(get("/roles").principal(user).with((request) -> {
request.addUserRole("ROLE_admin");
request.addUserRole("ROLE_user");
request.addUserRole("ROLE_unmapped");
return request;
})).andExpect(status().isOk()).andExpect(content().string("ROLE_admin,ROLE_user"));
}
@Test
public void requestWhenCustomAuthenticatedUserDetailsServiceThenBehaviorMatchesNamespace() throws Exception {
this.spring.register(JeeUserServiceRefConfig.class, BaseController.class).autowire();
Principal user = mock(Principal.class);
given(user.getName()).willReturn("joe");
User result = new User(user.getName(), "N/A", true, true, true, true,
AuthorityUtils.createAuthorityList("ROLE_user"));
given(bean(AuthenticationUserDetailsService.class).loadUserDetails(any())).willReturn(result);
this.mvc.perform(get("/roles").principal(user))
.andExpect(status().isOk())
.andExpect(content().string("ROLE_user"));
verifyBean(AuthenticationUserDetailsService.class).loadUserDetails(any());
}
private <T> T bean(Class<T> beanClass) {
return this.spring.getContext().getBean(beanClass);
}
private <T> T verifyBean(Class<T> beanClass) {
return verify(this.spring.getContext().getBean(beanClass));
}
@Configuration
@EnableWebSecurity
public static | NamespaceHttpJeeTests |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/basic/ColumnTransformerTest.java | {
"start": 1871,
"end": 2751
} | class ____ {
@Id
private Long id;
@CompositeType(MonetaryAmountUserType.class)
@AttributeOverrides({
@AttributeOverride(name = "amount", column = @Column(name = "money")),
@AttributeOverride(name = "currency", column = @Column(name = "currency"))
})
@ColumnTransformer(
forColumn = "money",
read = "money / 100",
write = "? * 100"
)
private MonetaryAmount wallet;
//Getters and setters omitted for brevity
//end::mapping-column-read-and-write-composite-type-example[]
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public MonetaryAmount getWallet() {
return wallet;
}
public void setWallet(MonetaryAmount wallet) {
this.wallet = wallet;
}
//tag::mapping-column-read-and-write-composite-type-example[]
}
//end::mapping-column-read-and-write-composite-type-example[]
}
| Savings |
java | apache__hadoop | hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/FileIoProvider.java | {
"start": 3114,
"end": 4116
} | class ____ {
public static final Logger LOG = LoggerFactory.getLogger(
FileIoProvider.class);
private final ProfilingFileIoEvents profilingEventHook;
private final FaultInjectorFileIoEvents faultInjectorEventHook;
private final DataNode datanode;
private static final int LEN_INT = 4;
/**
* @param conf Configuration object. May be null. When null,
* the event handlers are no-ops.
* @param datanode datanode that owns this FileIoProvider. Used for
* IO error based volume checker callback
*/
public FileIoProvider(@Nullable Configuration conf,
final DataNode datanode) {
profilingEventHook = new ProfilingFileIoEvents(conf);
faultInjectorEventHook = new FaultInjectorFileIoEvents(conf);
this.datanode = datanode;
}
/**
* Lists the types of file system operations. Passed to the
* IO hooks so implementations can choose behavior based on
* specific operations.
*/
public | FileIoProvider |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/observable/ObservableFromIterableTest.java | {
"start": 1447,
"end": 10922
} | class ____ extends RxJavaTest {
@Test
public void listIterable() {
Observable<String> o = Observable.fromIterable(Arrays.<String> asList("one", "two", "three"));
Observer<String> observer = TestHelper.mockObserver();
o.subscribe(observer);
verify(observer, times(1)).onNext("one");
verify(observer, times(1)).onNext("two");
verify(observer, times(1)).onNext("three");
verify(observer, Mockito.never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
/**
* This tests the path that can not optimize based on size so must use setProducer.
*/
@Test
public void rawIterable() {
Iterable<String> it = new Iterable<String>() {
@Override
public Iterator<String> iterator() {
return new Iterator<String>() {
int i;
@Override
public boolean hasNext() {
return i < 3;
}
@Override
public String next() {
return String.valueOf(++i);
}
@Override
public void remove() {
}
};
}
};
Observable<String> o = Observable.fromIterable(it);
Observer<String> observer = TestHelper.mockObserver();
o.subscribe(observer);
verify(observer, times(1)).onNext("1");
verify(observer, times(1)).onNext("2");
verify(observer, times(1)).onNext("3");
verify(observer, Mockito.never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void observableFromIterable() {
Observable<String> o = Observable.fromIterable(Arrays.<String> asList("one", "two", "three"));
Observer<String> observer = TestHelper.mockObserver();
o.subscribe(observer);
verify(observer, times(1)).onNext("one");
verify(observer, times(1)).onNext("two");
verify(observer, times(1)).onNext("three");
verify(observer, Mockito.never()).onError(any(Throwable.class));
verify(observer, times(1)).onComplete();
}
@Test
public void noBackpressure() {
Observable<Integer> o = Observable.fromIterable(Arrays.asList(1, 2, 3, 4, 5));
TestObserverEx<Integer> to = new TestObserverEx<>();
o.subscribe(to);
to.assertValues(1, 2, 3, 4, 5);
to.assertTerminated();
}
@Test
public void subscribeMultipleTimes() {
Observable<Integer> o = Observable.fromIterable(Arrays.asList(1, 2, 3));
for (int i = 0; i < 10; i++) {
TestObserver<Integer> to = new TestObserver<>();
o.subscribe(to);
to.assertValues(1, 2, 3);
to.assertNoErrors();
to.assertComplete();
}
}
@Test
public void doesNotCallIteratorHasNextMoreThanRequiredWithBackpressure() {
final AtomicBoolean called = new AtomicBoolean(false);
Iterable<Integer> iterable = new Iterable<Integer>() {
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int count = 1;
@Override
public void remove() {
// ignore
}
@Override
public boolean hasNext() {
if (count > 1) {
called.set(true);
return false;
}
return true;
}
@Override
public Integer next() {
return count++;
}
};
}
};
Observable.fromIterable(iterable).take(1).subscribe();
assertFalse(called.get());
}
@Test
public void doesNotCallIteratorHasNextMoreThanRequiredFastPath() {
final AtomicBoolean called = new AtomicBoolean(false);
Iterable<Integer> iterable = new Iterable<Integer>() {
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
@Override
public void remove() {
// ignore
}
int count = 1;
@Override
public boolean hasNext() {
if (count > 1) {
called.set(true);
return false;
}
return true;
}
@Override
public Integer next() {
return count++;
}
};
}
};
Observable.fromIterable(iterable).subscribe(new DefaultObserver<Integer>() {
@Override
public void onComplete() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(Integer t) {
// unsubscribe on first emission
cancel();
}
});
assertFalse(called.get());
}
@Test
public void fusionWithConcatMap() {
TestObserver<Integer> to = new TestObserver<>();
Observable.fromIterable(Arrays.asList(1, 2, 3, 4)).concatMap(
new Function<Integer, ObservableSource<Integer>>() {
@Override
public ObservableSource<Integer> apply(Integer v) {
return Observable.range(v, 2);
}
}).subscribe(to);
to.assertValues(1, 2, 2, 3, 3, 4, 4, 5);
to.assertNoErrors();
to.assertComplete();
}
@Test
public void iteratorThrows() {
Observable.fromIterable(new CrashingIterable(1, 100, 100))
.to(TestHelper.<Integer>testConsumer())
.assertFailureAndMessage(TestException.class, "iterator()");
}
@Test
public void hasNext2Throws() {
Observable.fromIterable(new CrashingIterable(100, 2, 100))
.to(TestHelper.<Integer>testConsumer())
.assertFailureAndMessage(TestException.class, "hasNext()", 0);
}
@Test
public void hasNextCancels() {
final TestObserver<Integer> to = new TestObserver<>();
Observable.fromIterable(new Iterable<Integer>() {
@Override
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
int count;
@Override
public boolean hasNext() {
if (++count == 2) {
to.dispose();
}
return true;
}
@Override
public Integer next() {
return 1;
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
})
.subscribe(to);
to.assertValue(1)
.assertNoErrors()
.assertNotComplete();
}
@Test
public void fusionRejected() {
TestObserverEx<Integer> to = new TestObserverEx<>(QueueFuseable.ASYNC);
Observable.fromIterable(Arrays.asList(1, 2, 3))
.subscribe(to);
to.assertFusionMode(QueueFuseable.NONE)
.assertResult(1, 2, 3);
}
@Test
public void fusionClear() {
Observable.fromIterable(Arrays.asList(1, 2, 3))
.subscribe(new Observer<Integer>() {
@Override
public void onSubscribe(Disposable d) {
@SuppressWarnings("unchecked")
QueueDisposable<Integer> qd = (QueueDisposable<Integer>)d;
qd.requestFusion(QueueFuseable.ANY);
try {
assertEquals(1, qd.poll().intValue());
} catch (Throwable ex) {
fail(ex.toString());
}
qd.clear();
try {
assertNull(qd.poll());
} catch (Throwable ex) {
fail(ex.toString());
}
}
@Override
public void onNext(Integer value) {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
@Test
public void disposeAfterHasNext() {
TestObserver<Integer> to = new TestObserver<>();
Observable.fromIterable(() -> new Iterator<Integer>() {
int count;
@Override
public boolean hasNext() {
if (count++ == 2) {
to.dispose();
return false;
}
return true;
}
@Override
public Integer next() {
return 1;
}
})
.subscribeWith(to)
.assertValuesOnly(1, 1);
}
}
| ObservableFromIterableTest |
java | reactor__reactor-core | reactor-core/src/test/java/reactor/core/publisher/FluxMapSignalTest.java | {
"start": 1140,
"end": 7027
} | class ____ extends FluxOperatorTest<String, String> {
@Test
public void allNull() {
assertThatExceptionOfType(IllegalArgumentException.class).isThrownBy(() -> {
Flux.never().flatMap(null, null, null);
});
}
@Override
protected Scenario<String, String> defaultScenarioOptions(Scenario<String, String> defaultOptions) {
return defaultOptions.shouldAssertPostTerminateState(false);
}
@Override
protected List<Scenario<String, String>> scenarios_operatorSuccess() {
return Arrays.asList(
scenario(f -> f.flatMap(Flux::just, Flux::error, Flux::empty)),
scenario(f -> f.flatMap(Flux::just, Flux::error, null)),
scenario(f -> f.flatMap(Flux::just, null, null))
);
}
@Override
protected List<Scenario<String, String>> scenarios_operatorError() {
return Arrays.asList(
scenario(f -> f.flatMap(d -> null, null, null))
,
scenario(f -> f.flatMap(null, null, () -> null))
);
}
@Test
public void completeOnlyBackpressured() {
AssertSubscriber<Integer> ts = AssertSubscriber.create(0L);
new FluxMapSignal<>(Flux.empty(), null, null, () -> 1)
.subscribe(ts);
ts.assertNoValues()
.assertNoError()
.assertNotComplete();
ts.request(1);
ts.assertValues(1)
.assertNoError()
.assertComplete();
}
@Test
public void errorOnlyBackpressured() {
AssertSubscriber<Integer> ts = AssertSubscriber.create(0L);
new FluxMapSignal<>(Flux.error(new RuntimeException()), null, e -> 1, null)
.subscribe(ts);
ts.assertNoValues()
.assertNoError()
.assertNotComplete();
ts.request(1);
ts.assertValues(1)
.assertNoError()
.assertComplete();
}
@Test
public void flatMapSignal() {
StepVerifier.create(Flux.just(1, 2, 3)
.flatMap(d -> Flux.just(d * 2),
e -> Flux.just(99),
() -> Flux.just(10)))
.expectNext(2, 4, 6, 10)
.verifyComplete();
}
@Test
public void flatMapSignalError() {
StepVerifier.create(Flux.just(1, 2, 3).concatWith(Flux.error(new Exception("test")))
.flatMap(d -> Flux.just(d * 2),
e -> Flux.just(99),
() -> Flux.just(10)))
.expectNext(2, 4, 6, 99)
.verifyComplete();
}
@Test
public void flatMapSignal2() {
StepVerifier.create(Mono.just(1)
.flatMapMany(d -> Flux.just(d * 2),
e -> Flux.just(99),
() -> Flux.just(10)).doOnComplete(() -> {
System.out.println("test");
})
.log())
.expectNext(2, 10)
.verifyComplete();
}
@Test
void mapOnNextRejectsNull() {
FluxMapTest.NullFunction<String, Mono<Integer>> mapper = new FluxMapTest.NullFunction<>();
Flux.just("test")
.flatMap(mapper, null, null)
.as(StepVerifier::create)
.verifyErrorSatisfies(err -> assertThat(err)
.isInstanceOf(NullPointerException.class)
.hasMessage("The mapper [reactor.core.publisher.FluxMapTest$NullFunction] returned a null value.")
);
}
@Test
void mapOnErrorRejectsNull() {
final IllegalStateException originalException = new IllegalStateException("expected");
FluxMapTest.NullFunction<Throwable, Mono<Integer>> mapper = new FluxMapTest.NullFunction<>();
Flux.error(originalException)
.flatMap(null, mapper, null)
.as(StepVerifier::create)
.verifyErrorSatisfies(err -> assertThat(err)
.isInstanceOf(NullPointerException.class)
.hasMessage("The mapper [reactor.core.publisher.FluxMapTest$NullFunction] returned a null value.")
.hasSuppressedException(originalException)
);
}
@Test
void mapOnCompleteRejectsNull() {
FluxMapTest.NullSupplier<Mono<Integer>> mapper = new FluxMapTest.NullSupplier<>();
Flux.just("test")
.flatMap(null, null, mapper)
.as(StepVerifier::create)
.verifyErrorSatisfies(err -> assertThat(err)
.isInstanceOf(NullPointerException.class)
.hasMessage("The mapper [reactor.core.publisher.FluxMapTest$NullSupplier] returned a null value.")
);
}
@Test
public void scanOperator(){
Flux<Integer> parent = Flux.just(1);
FluxMapSignal<Integer, Integer> test = new FluxMapSignal<>(parent, v -> v, e -> 1, () -> 10);
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
}
@Test
public void scanSubscriber() {
CoreSubscriber<Integer> actual = new LambdaSubscriber<>(null, e -> {}, null, null);
FluxMapSignal<Object, Integer> main = new FluxMapSignal<>(Flux.empty(), null, null, () -> 1);
FluxMapSignal.FluxMapSignalSubscriber<Object, Integer> test =
new FluxMapSignal.FluxMapSignalSubscriber<>(actual, main.mapperNext,
main.mapperError, main.mapperComplete);
Subscription parent = Operators.emptySubscription();
test.onSubscribe(parent);
assertThat(test.scan(Scannable.Attr.PARENT)).isSameAs(parent);
assertThat(test.scan(Scannable.Attr.ACTUAL)).isSameAs(actual);
test.requested = 35;
assertThat(test.scan(Scannable.Attr.REQUESTED_FROM_DOWNSTREAM)).isEqualTo(35);
assertThat(test.scan(Scannable.Attr.BUFFERED)).isEqualTo(0); // RS: TODO non-zero size
assertThat(test.scan(Scannable.Attr.RUN_STYLE)).isSameAs(Scannable.Attr.RunStyle.SYNC);
assertThat(test.scan(Scannable.Attr.TERMINATED)).isFalse();
test.onError(new IllegalStateException("boom"));
assertThat(test.scan(Scannable.Attr.TERMINATED)).isTrue();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isFalse();
test.cancel();
assertThat(test.scan(Scannable.Attr.CANCELLED)).isTrue();
}
}
| FluxMapSignalTest |
java | quarkusio__quarkus | extensions/resteasy-classic/resteasy/deployment/src/test/java/io/quarkus/resteasy/test/security/RemoteUserHttpAccessLogTest.java | {
"start": 1076,
"end": 3131
} | class ____ {
@RegisterExtension
public static QuarkusUnitTest unitTest = new QuarkusUnitTest()
.withApplicationRoot(jar -> jar
.addClasses(RolesAllowedResource.class, SecurityOverrideFilter.class)
.addClasses(TestIdentityController.class, TestIdentityProvider.class)
.add(new StringAsset("quarkus.http.access-log.enabled=true\n" +
"quarkus.http.access-log.pattern=%h %t " + REMOTE_USER_SHORT), "application.properties"))
.setLogRecordPredicate(logRecord -> logRecord.getLevel().equals(Level.INFO)
&& logRecord.getLoggerName().equals("io.quarkus.http.access-log"))
.assertLogRecords(logRecords -> {
var accessLogRecords = logRecords
.stream()
.map(LogRecord::getMessage)
.collect(Collectors.toList());
assertTrue(accessLogRecords.stream().anyMatch(msg -> msg.endsWith("admin")));
assertFalse(accessLogRecords.stream().anyMatch(msg -> msg.endsWith("user")));
assertTrue(accessLogRecords.stream().anyMatch(msg -> msg.endsWith("Charlie")));
});
@BeforeAll
public static void setupUsers() {
TestIdentityController.resetRoles()
.add("admin", "admin", "admin")
.add("user", "user", "user");
}
@Test
public void testAuthRemoteUserLogged() {
RestAssured
.given()
.auth().preemptive().basic("admin", "admin")
.get("/roles")
.then()
.statusCode(200)
.body(Matchers.is("default"));
RestAssured
.given()
.auth().preemptive().basic("user", "user")
.get("/roles")
.then()
.statusCode(200)
.body(Matchers.is("default"));
}
@Provider
@PreMatching
public static | RemoteUserHttpAccessLogTest |
java | quarkusio__quarkus | extensions/tls-registry/deployment/src/test/java/io/quarkus/tls/JKSKeyStoreWithMissingAliasPasswordTest.java | {
"start": 1043,
"end": 1936
} | class ____ {
private static final String configuration = """
quarkus.tls.key-store.jks.path=target/certs/test-alias-jks-keystore.jks
quarkus.tls.key-store.jks.password=password
quarkus.tls.key-store.jks.alias=missing
quarkus.tls.key-store.jks.alias-password=alias-password
""";
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer(
() -> ShrinkWrap.create(JavaArchive.class)
.add(new StringAsset(configuration), "application.properties"))
.assertException(t -> {
assertThat(t).hasMessageContaining("<default>", "password");
});
@Test
void test() throws KeyStoreException, CertificateParsingException {
fail("This test should not be called");
}
}
| JKSKeyStoreWithMissingAliasPasswordTest |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/common/validation/SourceDestValidatorTests.java | {
"start": 3986,
"end": 7909
} | class ____ extends ESTestCase {
private static final String SOURCE_1 = "source-1";
private static final String SOURCE_1_ALIAS = "source-1-alias";
private static final String SOURCE_2 = "source-2";
private static final String DEST_ALIAS = "dest-alias";
private static final String ALIASED_DEST = "aliased-dest";
private static final String ALIAS_READ_WRITE_DEST = "alias-read-write-dest";
private static final String REMOTE_BASIC = "remote-basic";
private static final String REMOTE_PLATINUM = "remote-platinum";
private static final ClusterState CLUSTER_STATE;
private static final String DUMMY_NODE_ROLE = "dummy";
private static final SourceDestValidator.SourceDestValidation REMOTE_SOURCE_VALIDATION =
new RemoteSourceEnabledAndRemoteLicenseValidation(DUMMY_NODE_ROLE);
private static final List<SourceDestValidator.SourceDestValidation> TEST_VALIDATIONS = Arrays.asList(
SOURCE_MISSING_VALIDATION,
DESTINATION_IN_SOURCE_VALIDATION,
DESTINATION_SINGLE_INDEX_VALIDATION,
DESTINATION_PIPELINE_MISSING_VALIDATION,
REMOTE_SOURCE_VALIDATION
);
private TestThreadPool clientThreadPool;
private Client clientWithBasicLicense;
private Client clientWithExpiredBasicLicense;
private Client clientWithPlatinumLicense;
private Client clientWithTrialLicense;
private RemoteClusterLicenseChecker remoteClusterLicenseCheckerBasic;
private LicensedFeature platinumFeature;
private final ThreadPool threadPool = new TestThreadPool(getClass().getName());
private final TransportService transportService = MockTransportService.createNewService(
Settings.EMPTY,
VersionInformation.CURRENT,
TransportVersion.current(),
threadPool
);
private final RemoteClusterService remoteClusterService = transportService.getRemoteClusterService();
private final IngestService ingestService = mock(IngestService.class);
private final IndexNameExpressionResolver indexNameExpressionResolver = TestIndexNameExpressionResolver.newInstance(
threadPool.getThreadContext()
);
private final SourceDestValidator simpleNonRemoteValidator = new SourceDestValidator(
indexNameExpressionResolver,
remoteClusterService,
null,
ingestService,
"node_id",
"license"
);
static {
IndexMetadata source1 = IndexMetadata.builder(SOURCE_1)
.settings(indexSettings(IndexVersion.current(), 1, 0).put(SETTING_CREATION_DATE, System.currentTimeMillis()))
.putAlias(AliasMetadata.builder(SOURCE_1_ALIAS).build())
.putAlias(AliasMetadata.builder(ALIAS_READ_WRITE_DEST).writeIndex(false).build())
.build();
IndexMetadata source2 = IndexMetadata.builder(SOURCE_2)
.settings(indexSettings(IndexVersion.current(), 1, 0).put(SETTING_CREATION_DATE, System.currentTimeMillis()))
.putAlias(AliasMetadata.builder(DEST_ALIAS).build())
.putAlias(AliasMetadata.builder(ALIAS_READ_WRITE_DEST).writeIndex(false).build())
.build();
IndexMetadata aliasedDest = IndexMetadata.builder(ALIASED_DEST)
.settings(indexSettings(IndexVersion.current(), 1, 0).put(SETTING_CREATION_DATE, System.currentTimeMillis()))
.putAlias(AliasMetadata.builder(DEST_ALIAS).build())
.putAlias(AliasMetadata.builder(ALIAS_READ_WRITE_DEST).build())
.build();
ClusterState.Builder state = ClusterState.builder(new ClusterName("test"));
state.metadata(
Metadata.builder()
.put(IndexMetadata.builder(source1).build(), false)
.put(IndexMetadata.builder(source2).build(), false)
.put(IndexMetadata.builder(aliasedDest).build(), false)
);
CLUSTER_STATE = state.build();
}
private | SourceDestValidatorTests |
java | apache__hadoop | hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/util/functional/TestTaskPool.java | {
"start": 1801,
"end": 4172
} | class ____ extends HadoopTestBase {
private static final Logger LOG =
LoggerFactory.getLogger(TestTaskPool.class);
public static final int ITEM_COUNT = 16;
private static final int FAILPOINT = 8;
private int numThreads;
/**
* Thread pool for task execution.
*/
private ExecutorService threadPool;
/**
* Task submitter bonded to the thread pool, or
* null for the 0-thread case.
*/
private TaskPool.Submitter submitter;
private final CounterTask failingTask
= new CounterTask("failing committer", FAILPOINT, Item::commit);
private final FailureCounter failures
= new FailureCounter("failures", 0, null);
private final CounterTask reverter
= new CounterTask("reverter", 0, Item::revert);
private final CounterTask aborter
= new CounterTask("aborter", 0, Item::abort);
/**
* Test array for parameterized test runs: how many threads and
* to use. Threading makes some of the assertions brittle; there are
* more checks on single thread than parallel ops.
* @return a list of parameter tuples.
*/
public static Collection<Object[]> params() {
return Arrays.asList(new Object[][]{
{0},
{1},
{3},
{8},
{16},
});
}
private List<Item> items;
/**
* Construct the parameterized test.
* @param pNumThreads number of threads
*/
public void initTestTaskPool(int pNumThreads) {
this.numThreads = pNumThreads;
}
/**
* In a parallel test run there is more than one thread doing the execution.
* @return true if the threadpool size is >1
*/
public boolean isParallel() {
return numThreads > 1;
}
@BeforeEach
public void setup() {
items = IntStream.rangeClosed(1, ITEM_COUNT)
.mapToObj(i -> new Item(i,
String.format("With %d threads", numThreads)))
.collect(Collectors.toList());
if (numThreads > 0) {
threadPool = Executors.newFixedThreadPool(numThreads,
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat(getMethodName() + "-pool-%d")
.build());
submitter = new PoolSubmitter();
} else {
submitter = null;
}
}
@AfterEach
public void teardown() {
if (threadPool != null) {
threadPool.shutdown();
threadPool = null;
}
}
private | TestTaskPool |
java | spring-projects__spring-boot | module/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/security/AuthorizationAuditListener.java | {
"start": 1238,
"end": 2401
} | class ____ extends AbstractAuthorizationAuditListener {
/**
* Authorization failure event type.
*/
public static final String AUTHORIZATION_FAILURE = "AUTHORIZATION_FAILURE";
@Override
public void onApplicationEvent(AuthorizationEvent event) {
if (event instanceof AuthorizationDeniedEvent<?> authorizationDeniedEvent) {
onAuthorizationDeniedEvent(authorizationDeniedEvent);
}
}
private void onAuthorizationDeniedEvent(AuthorizationDeniedEvent<?> event) {
String name = getName(event.getAuthentication());
Map<String, @Nullable Object> data = new LinkedHashMap<>();
Object details = getDetails(event.getAuthentication());
if (details != null) {
data.put("details", details);
}
publish(new AuditEvent(name, AUTHORIZATION_FAILURE, data));
}
private String getName(Supplier<Authentication> authentication) {
try {
return authentication.get().getName();
}
catch (Exception ex) {
return "<unknown>";
}
}
private @Nullable Object getDetails(Supplier<Authentication> authentication) {
try {
return authentication.get().getDetails();
}
catch (Exception ex) {
return null;
}
}
}
| AuthorizationAuditListener |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-services/hadoop-yarn-services-core/src/main/java/org/apache/hadoop/yarn/service/provider/tarball/TarballProviderFactory.java | {
"start": 1071,
"end": 1271
} | class ____ extends ProviderFactory {
private static final ProviderFactory FACTORY = new
TarballProviderFactory();
private TarballProviderFactory() {
}
private static | TarballProviderFactory |
java | FasterXML__jackson-databind | src/main/java/tools/jackson/databind/ser/Serializers.java | {
"start": 9517,
"end": 10574
} | class ____ implements Serializers
{
// Default implementations are fine:
/*
/******************************************************************
/* Additional helper methods for implementations
/******************************************************************
*/
/**
* Helper method for determining effective combination of formatting settings
* from combination of Class annotations and config overrides for type and
* possible per-property overrides (in this order of precedence from lowest
* to highest).
*/
protected JsonFormat.Value calculateEffectiveFormat(BeanDescription.Supplier beanDescRef,
Class<?> baseType, JsonFormat.Value formatOverrides)
{
JsonFormat.Value fromType = beanDescRef.findExpectedFormat(baseType);
if (formatOverrides == null) {
return fromType;
}
return JsonFormat.Value.merge(fromType, formatOverrides);
}
}
}
| Base |
java | spring-projects__spring-security | core/src/test/java/org/springframework/security/authorization/ReactiveAuthorizationAdvisorProxyFactoryTests.java | {
"start": 7463,
"end": 7619
} | interface ____ {
Mono<String> secret();
}
record Repository(@PreAuthorize("hasRole('ADMIN')") Mono<String> secret) implements HasSecret {
}
}
| HasSecret |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/inheritance/TreatedLeftPluralJoinInheritanceTest.java | {
"start": 9638,
"end": 10024
} | class ____ {
@Id
@GeneratedValue
private Long id;
@ManyToOne
private ParentEntity parentEntity;
public ParentEntity getParentEntity() {
return parentEntity;
}
public void setParentEntity(ParentEntity parentEntity) {
this.parentEntity = parentEntity;
}
}
@SuppressWarnings("unused")
@Entity( name = "TablePerClassSubEntity" )
public static | TablePerClassEntity |
java | assertj__assertj-core | assertj-core/src/main/java/org/assertj/core/api/ComparatorFactory.java | {
"start": 2144,
"end": 4399
} | class ____ java 8
return new Comparator<Float>() {
@Override
public int compare(Float float1, Float float2) {
Floats floats = Floats.instance();
if (floats.isNanOrInfinite(precision)) {
throw new IllegalArgumentException("Precision should not be Nan or Infinity!");
}
// handle NAN or Infinity cases with Java Float behavior (and not BigDecimal that are used afterwards)
if (floats.isNanOrInfinite(float1) || floats.isNanOrInfinite(float2)) {
return Float.compare(float1, float2);
}
// if floats are close enough they are considered equal, otherwise we compare as BigDecimal which does exact computation.
return isWithinPrecision(float1, float2, precision) ? 0 : asBigDecimal(float1).compareTo(asBigDecimal(float2));
}
@Override
public String toString() {
return "float comparator at precision " + precision + " (values are considered equal if diff == precision)";
}
};
}
/**
* Convert to a precise BigDecimal object using an intermediate String.
*
* @param <T> type of expected and precision, which should be the subclass of java.lang.Number and java.lang.Comparable
* @param number the Number to convert
* @return the built BigDecimal
*/
private static <T extends Number> BigDecimal asBigDecimal(T number) {
return new BigDecimal(String.valueOf(number));
}
/**
* Returns true if the abs(expected - precision) is <= precision, false otherwise.
* @param actual the actual value
* @param expected the expected value
* @param precision the acceptable precision
*
* @param <T> type of number to compare including the precision
* @return whether true if the abs(expected - precision) is <= precision, false otherwise.
*/
private static <T extends Number> boolean isWithinPrecision(T actual, T expected, T precision) {
BigDecimal expectedBigDecimal = asBigDecimal(expected);
BigDecimal actualBigDecimal = asBigDecimal(actual);
BigDecimal absDifference = expectedBigDecimal.subtract(actualBigDecimal).abs();
BigDecimal precisionAsBigDecimal = asBigDecimal(precision);
return absDifference.compareTo(precisionAsBigDecimal) <= 0;
}
}
| in |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/TryFailRefactoringTest.java | {
"start": 4055,
"end": 4768
} | class ____ {
@Test
public void test() throws Exception {
Path p = Paths.get("NOSUCH");
try {
Files.readAllBytes(p);
fail();
} catch (IOException e) {
}
}
}
""")
.addOutputLines(
"out/ExceptionTest.java",
"""
import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.nio.file.*;
import org.junit.Test;
| ExceptionTest |
java | apache__hadoop | hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/AggregatedLogFormat.java | {
"start": 14589,
"end": 15614
} | class ____ {
/**
* The time used with logRetentionMillis, to determine ages of
* log files and if files need to be uploaded.
*/
private final long logInitedTimeMillis;
/**
* The numbers of milli seconds since a log file is created to determine
* if we should upload it. -1 if disabled.
* see YarnConfiguration.LOG_AGGREGATION_RETAIN_SECONDS for details.
*/
private final long logRetentionMillis;
public LogRetentionContext(long logInitedTimeMillis, long
logRetentionMillis) {
this.logInitedTimeMillis = logInitedTimeMillis;
this.logRetentionMillis = logRetentionMillis;
}
public boolean isDisabled() {
return logInitedTimeMillis < 0 || logRetentionMillis < 0;
}
public boolean shouldRetainLog() {
return isDisabled() ||
System.currentTimeMillis() - logInitedTimeMillis < logRetentionMillis;
}
}
/**
* The writer that writes out the aggregated logs.
*/
@Private
public static | LogRetentionContext |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/sql/results/ResultsShapeTests.java | {
"start": 1402,
"end": 10028
} | class ____ {
@Test
public void testSimpleEntitySelection(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final List<?> orders = session.createQuery( "select o from Order o" ).list();
// only 2 orders
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
}
@Test
public void testTypedEntitySelection(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final List<Order> orders = session.createQuery( "select o from Order o", Order.class ).list();
// only 2 orders
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
}
@Test
public void testArrayTypedEntitySelection(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final List<Object[]> orders = session.createQuery( "select o from Order o", Object[].class ).list();
// only 2 orders
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Object[].class );
assertThat( orders.get( 1 ) ).isInstanceOf( Object[].class );
} );
}
@Test
public void testTupleTypedEntitySelection(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final List<Tuple> orders = session.createQuery( "select o from Order o", Tuple.class ).list();
// only 2 orders
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Tuple.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Tuple.class );
} );
}
@Test
public void testDuplicatedTypedEntitySelection(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final String hql = "select o from LineItem i join i.order o";
final List<Order> orders = session.createQuery( hql, Order.class ).list();
// because we select the entity and specify it as the result type, the results are de-duped
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
}
@Test
public void testDuplicatedArrayTypedEntitySelection(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final String hql = "select o from LineItem i join i.order o";
final List<Object[]> orders = session.createQuery( hql, Object[].class ).list();
// because we select the entity again, but here specify the full array as the result type - the results are not de-duped
assertThat( orders ).hasSize( 3 );
assertThat( orders.get( 0 ) ).isInstanceOf( Object[].class );
assertThat( orders.get( 1 ) ).isInstanceOf( Object[].class );
} );
}
@Test
public void testDuplicatedTupleTypedEntitySelection(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final String hql = "select o from LineItem i join i.order o";
final List<Tuple> orders = session.createQuery( hql, Tuple.class ).list();
// Tuple is a special case or Object[] - not de-duped
assertThat( orders ).hasSize( 3 );
assertThat( orders.get( 0 ) ).isInstanceOf( Tuple.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Tuple.class );
} );
}
@Test
public void testTupleTransformedEntitySelection(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final String hql = "select o from Order o";
final List<Order> orders = session.createQuery( hql, Order.class )
.setTupleTransformer( (tuple, aliases) -> (Order) tuple[ 0 ] )
.list();
// only 2 orders
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
scope.inTransaction( (session) -> {
final String hql = "select o from Order o";
final List<Order> orders = session.createQuery( hql )
.setTupleTransformer( (tuple, aliases) -> tuple[ 0 ] )
.list();
// only 2 orders
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
}
@Test
public void testDuplicatedTupleTransformedEntitySelection(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final String hql = "select o from LineItem i join i.order o";
final List<Order> orders = session.createQuery( hql, Order.class )
.setTupleTransformer( (tuple, aliases) -> (Order) tuple[ 0 ] )
.list();
// only 2 orders
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
scope.inTransaction( (session) -> {
final String hql = "select o from LineItem i join i.order o";
final List<Order> orders = session.createQuery( hql )
.setTupleTransformer( (tuple, aliases) -> tuple[ 0 ] )
.list();
// only 2 orders
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
}
private final TypedTupleTransformer<Order> ORDER_TUPLE_TRANSFORMER = new TypedTupleTransformer<>() {
@Override
public Class<Order> getTransformedType() {
return Order.class;
}
@Override
public Order transformTuple(Object[] tuple, String[] aliases) {
return (Order) tuple[0];
}
};
@Test
public void testTypedTupleTransformedEntitySelection(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final String hql = "select o from Order o";
final List<Order> orders = session.createQuery( hql, Order.class )
.setTupleTransformer( ORDER_TUPLE_TRANSFORMER )
.list();
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
scope.inTransaction( (session) -> {
final String hql = "select o from Order o";
final List<Order> orders = session.createQuery( hql )
.setTupleTransformer( ORDER_TUPLE_TRANSFORMER )
.list();
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
}
@Test
public void testDuplicatedTypedTupleTransformedEntitySelection(SessionFactoryScope scope) {
final String hql = "select o from LineItem i join i.order o";
scope.inTransaction( (session) -> {
final List<Order> orders = session.createQuery( hql, Order.class )
.setTupleTransformer( (tuple, aliases) -> (Order) tuple[0] )
.list();
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
scope.inTransaction( (session) -> {
final List<Order> orders = session.createQuery( hql )
.setTupleTransformer( (tuple, aliases) -> tuple[ 0 ] )
.list();
assertThat( orders ).hasSize( 2 );
assertThat( orders.get( 0 ) ).isInstanceOf( Order.class );
assertThat( orders.get( 1 ) ).isInstanceOf( Order.class );
} );
}
@BeforeEach
public void prepareTestData(SessionFactoryScope scope) {
scope.inTransaction( (session) -> {
final Vendor acme = new Vendor( 1, "Acme, Inc.", null );
session.persist( acme );
final Product widget = new Product( 1, SafeRandomUUIDGenerator.safeRandomUUID(), acme );
session.persist( widget );
final SalesAssociate associate = new SalesAssociate( 1, new Name( "John", "Doe" ) );
session.persist( associate );
final MonetaryAmount oneDollar = Monetary.getDefaultAmountFactory()
.setNumber( 1 )
.setCurrency( "USD" )
.create();
final CardPayment payment1 = new CardPayment( 1, 123, oneDollar );
session.persist( payment1 );
final Order order1 = new Order( 1, payment1, associate );
session.persist( order1 );
final LineItem lineItem11 = new LineItem( 11, widget, 1, oneDollar, order1 );
session.persist( lineItem11 );
final LineItem lineItem12 = new LineItem( 12, widget, 1, oneDollar, order1 );
session.persist( lineItem12 );
final CardPayment payment2 = new CardPayment( 2, 321, oneDollar );
session.persist( payment2 );
final Order order2 = new Order( 2, payment2, associate );
session.persist( order2 );
final LineItem lineItem2 = new LineItem( 2, widget, 1, oneDollar, order2 );
session.persist( lineItem2 );
} );
}
@AfterEach
public void dropTestData(SessionFactoryScope scope) {
scope.getSessionFactory().getSchemaManager().truncate();
}
}
| ResultsShapeTests |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.