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 | junit-team__junit5 | junit-platform-launcher/src/testFixtures/java/org/junit/platform/launcher/core/LauncherFactoryForTestingPurposesOnly.java | {
"start": 478,
"end": 1211
} | class ____ {
public static Launcher createLauncher(TestEngine... engines) {
return LauncherFactory.create(createLauncherConfigBuilderWithDisabledServiceLoading() //
.addTestEngines(engines) //
.build());
}
public static LauncherConfig.Builder createLauncherConfigBuilderWithDisabledServiceLoading() {
return LauncherConfig.builder() //
.enableTestEngineAutoRegistration(false) //
.enableLauncherDiscoveryListenerAutoRegistration(false) //
.enableTestExecutionListenerAutoRegistration(false) //
.enablePostDiscoveryFilterAutoRegistration(false) //
.enableLauncherSessionListenerAutoRegistration(false);
}
private LauncherFactoryForTestingPurposesOnly() {
}
}
| LauncherFactoryForTestingPurposesOnly |
java | spring-projects__spring-security | aspects/src/test/java/org/springframework/security/authorization/method/aspectj/PreAuthorizeAspectTests.java | {
"start": 5094,
"end": 5179
} | class ____ {
@PreAuthorize("denyAll")
void denyAllMethod() {
}
}
| NestedObject |
java | apache__camel | test-infra/camel-test-infra-jdbc/src/test/java/org/apache/camel/test/infra/jdbc/services/JDBCServiceFactory.java | {
"start": 947,
"end": 1313
} | class ____ {
private JDBCServiceFactory() {
}
public static SimpleTestServiceBuilder<JDBCService> builder() {
return new SimpleTestServiceBuilder<>("jdbc");
}
public static JDBCService createService() {
return builder()
.addRemoteMapping(JDBCRemoteService::new)
.build();
}
}
| JDBCServiceFactory |
java | quarkusio__quarkus | extensions/oidc-client/deployment/src/test/java/io/quarkus/oidc/client/OidcClientCredentialsJwtPrivateKeyStoreTestCase.java | {
"start": 391,
"end": 1448
} | class ____ {
private static Class<?>[] testClasses = {
OidcClientResource.class,
ProtectedResource.class
};
@RegisterExtension
static final QuarkusUnitTest test = new QuarkusUnitTest()
.withApplicationRoot((jar) -> jar
.addClasses(testClasses)
.addAsResource("application-oidc-client-credentials-jwt-private-key-store.properties",
"application.properties")
.addAsResource("exportedCertificate.pem")
.addAsResource("exportedPrivateKey.pem")
.addAsResource("keystore.jks"));
@Test
public void testClientCredentialsToken() {
String token = RestAssured.when().get("/client/token").body().asString();
RestAssured.given().auth().oauth2(token)
.when().get("/protected")
.then()
.statusCode(200)
.body(equalTo("service-account-quarkus-app"));
}
}
| OidcClientCredentialsJwtPrivateKeyStoreTestCase |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/RoutePropertyTest.java | {
"start": 1086,
"end": 1702
} | class ____ extends SpringTestSupport {
@Override
protected AbstractXmlApplicationContext createApplicationContext() {
return new ClassPathXmlApplicationContext("org/apache/camel/spring/RoutePropertyTest.xml");
}
@Test
void testRouteProperties() throws Exception {
assertCollectionSize(context.getRouteDefinitions(), 1);
assertCollectionSize(context.getRoutes(), 1);
Map<String, Object> map = context.getRoutes().get(0).getProperties();
Assertions.assertEquals("1", map.get("a"));
Assertions.assertEquals("2", map.get("b"));
}
}
| RoutePropertyTest |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/multipart/MultipartOutputResource.java | {
"start": 524,
"end": 5840
} | class ____ {
public static final String RESPONSE_NAME = "a name";
public static final String RESPONSE_FILENAME = "a filename";
public static final String RESPONSE_SURNAME = "a surname";
public static final Status RESPONSE_STATUS = Status.WORKING;
public static final List<String> RESPONSE_VALUES = List.of("one", "two");
public static final boolean RESPONSE_ACTIVE = true;
private static final long ONE_GIGA = 1024l * 1024l * 1024l * 1l;
private final File TXT_FILE = new File("./src/test/resources/lorem.txt");
private final File XML_FILE = new File("./src/test/resources/test.xml");
@GET
@Path("/simple")
@Produces(MediaType.MULTIPART_FORM_DATA)
public MultipartOutputResponse simple() {
MultipartOutputResponse response = new MultipartOutputResponse();
response.setName(RESPONSE_NAME);
response.setSurname(RESPONSE_SURNAME);
response.setStatus(RESPONSE_STATUS);
response.setValues(RESPONSE_VALUES);
response.active = RESPONSE_ACTIVE;
return response;
}
@GET
@Path("/rest-response")
@Produces(MediaType.MULTIPART_FORM_DATA)
public RestResponse<MultipartOutputResponse> restResponse() {
MultipartOutputResponse response = new MultipartOutputResponse();
response.setName(RESPONSE_NAME);
response.setSurname(RESPONSE_SURNAME);
response.setStatus(RESPONSE_STATUS);
response.setValues(RESPONSE_VALUES);
response.active = RESPONSE_ACTIVE;
return RestResponse.ResponseBuilder.ok(response).header("foo", "bar").build();
}
@GET
@Path("/with-form-data")
@Produces(MediaType.MULTIPART_FORM_DATA)
public RestResponse<MultipartFormDataOutput> withFormDataOutput() {
QuarkusMultivaluedHashMap<String, Object> headers = new QuarkusMultivaluedHashMap<>();
headers.putSingle("extra-header", "extra-value");
MultipartFormDataOutput form = new MultipartFormDataOutput();
form.addFormData("name", RESPONSE_NAME, MediaType.TEXT_PLAIN_TYPE);
form.addFormData("part-with-filename", RESPONSE_FILENAME, MediaType.TEXT_PLAIN_TYPE, "file.txt");
form.addFormData("part-with-filename", RESPONSE_FILENAME, MediaType.TEXT_PLAIN_TYPE, "file2.txt", headers);
form.addFormData("custom-surname", RESPONSE_SURNAME, MediaType.TEXT_PLAIN_TYPE);
form.addFormData("custom-status", RESPONSE_STATUS, MediaType.TEXT_PLAIN_TYPE)
.getHeaders().putAll(headers);
form.addFormData("values", RESPONSE_VALUES, MediaType.TEXT_PLAIN_TYPE);
form.addFormData("active", RESPONSE_ACTIVE, MediaType.TEXT_PLAIN_TYPE, headers);
return RestResponse.ResponseBuilder.ok(form).header("foo", "bar").build();
}
@GET
@Path("/string")
@Produces(MediaType.MULTIPART_FORM_DATA)
public String usingString() {
return RESPONSE_NAME;
}
@GET
@Path("/with-file")
@Produces(MediaType.MULTIPART_FORM_DATA)
public MultipartOutputFileResponse file() {
MultipartOutputFileResponse response = new MultipartOutputFileResponse();
response.name = RESPONSE_NAME;
response.file = TXT_FILE;
return response;
}
@GET
@Path("/with-multiple-file")
@Produces(MediaType.MULTIPART_FORM_DATA)
public MultipartOutputMultipleFileResponse multipleFile() {
MultipartOutputMultipleFileResponse response = new MultipartOutputMultipleFileResponse();
response.name = RESPONSE_NAME;
response.files = List.of(TXT_FILE, XML_FILE);
return response;
}
@GET
@Path("/with-single-file-download")
@Produces(MediaType.MULTIPART_FORM_DATA)
public MultipartOutputSingleFileDownloadResponse singleDownloadFile() {
MultipartOutputSingleFileDownloadResponse response = new MultipartOutputSingleFileDownloadResponse();
response.file = new PathFileDownload("one", XML_FILE);
return response;
}
@GET
@Path("/with-multiple-file-download")
@Produces(MediaType.MULTIPART_FORM_DATA)
public MultipartOutputMultipleFileDownloadResponse multipleDownloadFile() {
MultipartOutputMultipleFileDownloadResponse response = new MultipartOutputMultipleFileDownloadResponse();
response.name = RESPONSE_NAME;
response.files = List.of(new PathFileDownload(TXT_FILE), new PathFileDownload(XML_FILE));
return response;
}
@GET
@Path("/with-large-file")
@Produces(MediaType.MULTIPART_FORM_DATA)
public MultipartOutputFileResponse largeFile() throws IOException {
File largeFile = File.createTempFile("rr-large-file", ".tmp");
largeFile.deleteOnExit();
RandomAccessFile f = new RandomAccessFile(largeFile, "rw");
f.setLength(ONE_GIGA);
MultipartOutputFileResponse response = new MultipartOutputFileResponse();
response.name = RESPONSE_NAME;
response.file = largeFile;
return response;
}
@GET
@Path("/with-null-fields")
@Produces(MediaType.MULTIPART_FORM_DATA)
public MultipartOutputFileResponse nullFields() {
MultipartOutputFileResponse response = new MultipartOutputFileResponse();
response.name = null;
response.file = null;
return response;
}
}
| MultipartOutputResource |
java | spring-projects__spring-framework | spring-core/src/main/java/org/springframework/util/MethodInvoker.java | {
"start": 2369,
"end": 4515
} | class ____ sufficient.
* @see #setTargetClass
* @see #setTargetMethod
*/
public void setTargetObject(@Nullable Object targetObject) {
this.targetObject = targetObject;
if (targetObject != null) {
this.targetClass = targetObject.getClass();
}
}
/**
* Return the target object on which to call the target method.
*/
public @Nullable Object getTargetObject() {
return this.targetObject;
}
/**
* Set the name of the method to be invoked.
* Refers to either a static method or a non-static method,
* depending on a target object being set.
* @see #setTargetClass
* @see #setTargetObject
*/
public void setTargetMethod(@Nullable String targetMethod) {
this.targetMethod = targetMethod;
}
/**
* Return the name of the method to be invoked.
*/
public @Nullable String getTargetMethod() {
return this.targetMethod;
}
/**
* Set a fully qualified static method name to invoke,
* for example, "example.MyExampleClass.myExampleMethod". This is a
* convenient alternative to specifying targetClass and targetMethod.
* @see #setTargetClass
* @see #setTargetMethod
*/
public void setStaticMethod(String staticMethod) {
this.staticMethod = staticMethod;
}
/**
* Set arguments for the method invocation. If this property is not set,
* or the Object array is of length 0, a method with no arguments is assumed.
*/
public void setArguments(@Nullable Object @Nullable ... arguments) {
this.arguments = arguments;
}
/**
* Return the arguments for the method invocation.
*/
public @Nullable Object[] getArguments() {
return (this.arguments != null ? this.arguments : EMPTY_ARGUMENTS);
}
/**
* Prepare the specified method.
* The method can be invoked any number of times afterwards.
* @see #getPreparedMethod
* @see #invoke
*/
public void prepare() throws ClassNotFoundException, NoSuchMethodException {
if (this.staticMethod != null) {
int lastDotIndex = this.staticMethod.lastIndexOf('.');
if (lastDotIndex == -1 || lastDotIndex == this.staticMethod.length() - 1) {
throw new IllegalArgumentException(
"staticMethod must be a fully qualified | is |
java | alibaba__druid | core/src/test/java/com/alibaba/druid/bvt/sql/cobar/LiteralHexadecimalTest.java | {
"start": 926,
"end": 2315
} | class ____ extends TestCase {
public void test_0() throws Exception {
String sql = "x'E982B1E7A195275C73'";
SQLHexExpr hex = (SQLHexExpr) new MySqlExprParser(sql).expr();
assertEquals("邱硕'\\s", new String(hex.toBytes(), "utf-8"));
}
public void test_1() throws Exception {
String sql = "x'0D0A'";
SQLHexExpr hex = (SQLHexExpr) new MySqlExprParser(sql).expr();
assertEquals("\r\n", new String(hex.toBytes(), "utf-8"));
}
public void test_2() throws Exception {
String sql = "X'4D7953514C'";
SQLHexExpr hex = (SQLHexExpr) new MySqlExprParser(sql).expr();
assertEquals("MySQL", new String(hex.toBytes(), "utf-8"));
}
public void test_3() throws Exception {
String sql = "0x5061756c";
SQLHexExpr hex = (SQLHexExpr) new MySqlExprParser(sql).expr();
assertEquals("Paul", new String(hex.toBytes(), "utf-8"));
}
public void test_4() throws Exception {
String sql = "0x41";
SQLHexExpr hex = (SQLHexExpr) new MySqlExprParser(sql).expr();
assertEquals("A", new String(hex.toBytes(), "utf-8"));
}
public void test_5() throws Exception {
String sql = "0x636174";
SQLHexExpr hex = (SQLHexExpr) new MySqlExprParser(sql).expr();
assertEquals("cat", new String(hex.toBytes(), "utf-8"));
}
}
| LiteralHexadecimalTest |
java | quarkusio__quarkus | independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/injection/erroneous/interceptorBean/InterceptorBeanInjectionInitializerTest.java | {
"start": 464,
"end": 912
} | class ____ {
@RegisterExtension
ArcTestContainer container = ArcTestContainer.builder().beanClasses(InterceptorBeanInjectionInitializerTest.class,
MyBean.class).shouldFail().build();
@Test
public void testExceptionThrown() {
Throwable error = container.getFailure();
assertThat(error).isInstanceOf(DefinitionException.class);
}
@ApplicationScoped
static | InterceptorBeanInjectionInitializerTest |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/io/FileBench.java | {
"start": 8764,
"end": 9355
} | enum ____ {
zip(GzipCodec.class, ".gz"), pln(null, "");
Class<? extends CompressionCodec> inf;
String ext;
CCodec(Class<? extends CompressionCodec> inf, String ext) {
this.inf = inf;
this.ext = ext;
}
public void configure(JobConf job) {
if (inf != null) {
job.setBoolean("mapred.output.compress", true);
job.setClass("mapred.output.compression.codec", inf,
CompressionCodec.class);
} else {
job.setBoolean("mapred.output.compress", false);
}
}
public String getExt() { return ext; }
}
| CCodec |
java | spring-projects__spring-framework | spring-webflux/src/test/java/org/springframework/web/reactive/function/server/RequestPredicatesTests.java | {
"start": 1570,
"end": 17578
} | class ____ {
@Test
void all() {
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com").build();
MockServerWebExchange mockExchange = MockServerWebExchange.from(mockRequest);
RequestPredicate predicate = RequestPredicates.all();
ServerRequest request = new DefaultServerRequest(mockExchange, Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
}
@Test
void method() {
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com").build();
HttpMethod httpMethod = HttpMethod.GET;
RequestPredicate predicate = RequestPredicates.method(httpMethod);
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.post("https://example.com").build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@Test
void methodCorsPreFlight() {
RequestPredicate predicate = RequestPredicates.method(HttpMethod.PUT);
MockServerHttpRequest mockRequest = MockServerHttpRequest.options("https://example.com")
.header("Origin", "https://example.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PUT")
.build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.options("https://example.com")
.header("Origin", "https://example.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "POST")
.build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@Test
void methods() {
RequestPredicate predicate = RequestPredicates.methods(HttpMethod.GET, HttpMethod.HEAD);
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com").build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.head("https://example.com").build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.post("https://example.com").build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@Test
void allMethods() {
RequestPredicate predicate = RequestPredicates.GET("/p*");
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com/path").build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
predicate = RequestPredicates.HEAD("/p*");
mockRequest = MockServerHttpRequest.head("https://example.com/path").build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
predicate = RequestPredicates.POST("/p*");
mockRequest = MockServerHttpRequest.post("https://example.com/path").build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
predicate = RequestPredicates.PUT("/p*");
mockRequest = MockServerHttpRequest.put("https://example.com/path").build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
predicate = RequestPredicates.PATCH("/p*");
mockRequest = MockServerHttpRequest.patch("https://example.com/path").build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
predicate = RequestPredicates.DELETE("/p*");
mockRequest = MockServerHttpRequest.delete("https://example.com/path").build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
predicate = RequestPredicates.OPTIONS("/p*");
mockRequest = MockServerHttpRequest.options("https://example.com/path").build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
}
@Test
void path() {
URI uri = URI.create("https://localhost/path");
RequestPredicate predicate = RequestPredicates.path("/p*");
MockServerHttpRequest mockRequest = MockServerHttpRequest.get(uri.toString()).build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.head("https://example.com").build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@Test
void pathNoLeadingSlash() {
RequestPredicate predicate = RequestPredicates.path("p*");
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com/path").build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
}
@Test
void pathEncoded() {
URI uri = URI.create("https://localhost/foo%20bar");
RequestPredicate predicate = RequestPredicates.path("/foo bar");
MockServerHttpRequest mockRequest = MockServerHttpRequest.method(HttpMethod.GET, uri).build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
}
@Test
void pathPredicates() {
PathPatternParser parser = new PathPatternParser();
parser.setCaseSensitive(false);
Function<String, RequestPredicate> pathPredicates = RequestPredicates.pathPredicates(parser);
RequestPredicate predicate = pathPredicates.apply("/P*");
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com/path").build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
}
@Test
void pathWithContext() {
RequestPredicate predicate = RequestPredicates.path("/p*");
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://localhost/context/path")
.contextPath("/context").build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
}
@Test
void headers() {
String name = "MyHeader";
String value = "MyValue";
RequestPredicate predicate =
RequestPredicates.headers(
headers -> headers.header(name).equals(Collections.singletonList(value)));
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com")
.header(name, value)
.build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.get("https://example.com")
.header(name, "bar")
.build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@Test
void headersCors() {
RequestPredicate predicate = RequestPredicates.headers(headers -> false);
MockServerHttpRequest mockRequest = MockServerHttpRequest.options("https://example.com")
.header("Origin", "https://example.com")
.header(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD, "PUT")
.build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
}
@Test
void singleContentType() {
RequestPredicate predicate = RequestPredicates.contentType(MediaType.APPLICATION_JSON);
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.get("https://example.com")
.header(HttpHeaders.CONTENT_TYPE, "foo/bar")
.build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@Test
void multipleContentTypes() {
RequestPredicate predicate = RequestPredicates.contentType(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com")
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.get("https://example.com")
.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_PLAIN_VALUE)
.build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.get("https://example.com")
.header(HttpHeaders.CONTENT_TYPE, "foo/bar")
.build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@Test
void singleAccept() {
RequestPredicate predicate = RequestPredicates.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com")
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.get("https://example.com")
.header(HttpHeaders.ACCEPT, "foo/bar")
.build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@Test
void multipleAccepts() {
RequestPredicate predicate = RequestPredicates.accept(MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN);
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com")
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE)
.build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.get("https://example.com")
.header(HttpHeaders.ACCEPT, MediaType.TEXT_PLAIN_VALUE)
.build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
mockRequest = MockServerHttpRequest.get("https://example.com")
.header(HttpHeaders.ACCEPT, "foo/bar")
.build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@SuppressWarnings("removal")
@Test
void pathExtension() {
RequestPredicate predicate = RequestPredicates.pathExtension("txt");
URI uri = URI.create("https://localhost/file.txt");
MockServerHttpRequest mockRequest = MockServerHttpRequest.method(HttpMethod.GET, uri).build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
uri = URI.create("https://localhost/FILE.TXT");
mockRequest = MockServerHttpRequest.method(HttpMethod.GET, uri).build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
predicate = RequestPredicates.pathExtension("bar");
assertThat(predicate.test(request)).isFalse();
uri = URI.create("https://localhost/file.foo");
mockRequest = MockServerHttpRequest.method(HttpMethod.GET, uri).build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@SuppressWarnings("removal")
@Test
void pathExtensionPredicate() {
List<String> extensions = List.of("foo", "bar");
RequestPredicate predicate = RequestPredicates.pathExtension(extensions::contains);
URI uri = URI.create("https://localhost/file.foo");
MockServerHttpRequest mockRequest = MockServerHttpRequest.method(HttpMethod.GET, uri).build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
uri = URI.create("https://localhost/file.bar");
mockRequest = MockServerHttpRequest.method(HttpMethod.GET, uri).build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isTrue();
uri = URI.create("https://localhost/file");
mockRequest = MockServerHttpRequest.method(HttpMethod.GET, uri).build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
uri = URI.create("https://localhost/file.baz");
mockRequest = MockServerHttpRequest.method(HttpMethod.GET, uri).build();
request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
assertThat(predicate.test(request)).isFalse();
}
@Test
void queryParam() {
MockServerHttpRequest mockRequest = MockServerHttpRequest.get("https://example.com")
.queryParam("foo", "bar").build();
ServerRequest request = new DefaultServerRequest(MockServerWebExchange.from(mockRequest), Collections.emptyList());
RequestPredicate predicate = RequestPredicates.queryParam("foo", s -> s.equals("bar"));
assertThat(predicate.test(request)).isTrue();
predicate = RequestPredicates.queryParam("foo", s -> s.equals("baz"));
assertThat(predicate.test(request)).isFalse();
}
@Test
void version() {
assertThat(RequestPredicates.version("1.1").test(serverRequest("1.1"))).isTrue();
assertThat(RequestPredicates.version("1.1+").test(serverRequest("1.5"))).isTrue();
assertThat(RequestPredicates.version("1.1").test(serverRequest("1.5"))).isFalse();
}
private static DefaultServerRequest serverRequest(String version) {
ApiVersionStrategy versionStrategy = apiVersionStrategy();
Comparable<?> parsedVersion = versionStrategy.parseVersion(version);
MockServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("https://localhost"));
exchange.getAttributes().put(HandlerMapping.API_VERSION_ATTRIBUTE, parsedVersion);
return new DefaultServerRequest(exchange, Collections.emptyList(), versionStrategy);
}
private static DefaultApiVersionStrategy apiVersionStrategy() {
return new DefaultApiVersionStrategy(
List.of(exchange -> null), new SemanticApiVersionParser(), true, null, false, null, null);
}
}
| RequestPredicatesTests |
java | quarkusio__quarkus | extensions/undertow/runtime/src/main/java/io/quarkus/undertow/runtime/QuarkusUndertowAccount.java | {
"start": 318,
"end": 926
} | class ____ implements Account {
private final SecurityIdentity securityIdentity;
public QuarkusUndertowAccount(SecurityIdentity securityIdentity) {
this.securityIdentity = securityIdentity;
}
@Override
public Principal getPrincipal() {
return securityIdentity.getPrincipal();
}
@Override
public Set<String> getRoles() {
Set<String> roles = new HashSet<>();
roles.addAll(securityIdentity.getRoles());
return roles;
}
public SecurityIdentity getSecurityIdentity() {
return securityIdentity;
}
}
| QuarkusUndertowAccount |
java | apache__flink | flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/dataview/NullAwareMapIterator.java | {
"start": 2282,
"end": 2490
} | interface ____<K, V> extends Map.Entry<K, V> {
@Override
default K getKey() {
// the key is always null
return null;
}
void remove();
}
}
| NullMapEntry |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/modifiedflags/HasChangedBidirectionalTest.java | {
"start": 5152,
"end": 5848
} | class ____ {
@Id
private Integer id;
private String data;
@OneToMany(mappedBy = "ticket")
private List<Comment> comments = new ArrayList<>();
Ticket() {
}
public Ticket(Integer id, String data) {
this.id = id;
this.data = data;
}
public Integer getId() {
return id;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public List<Comment> getComments() {
return comments;
}
public void addComment(Comment comment) {
comment.setTicket( this );
comments.add( comment );
}
}
@Entity(name = "Comment")
@Table(name = "COMMENTS")
@Audited(withModifiedFlag = true)
public static | Ticket |
java | apache__spark | sql/core/src/test/java/test/org/apache/spark/sql/connector/catalog/functions/JavaLongAdd.java | {
"start": 1468,
"end": 2481
} | class ____ implements UnboundFunction {
private final ScalarFunction<Long> impl;
public JavaLongAdd(ScalarFunction<Long> impl) {
this.impl = impl;
}
@Override
public String name() {
return "long_add";
}
@Override
public BoundFunction bind(StructType inputType) {
if (inputType.fields().length != 2) {
throw new UnsupportedOperationException("Expect two arguments");
}
for (StructField field : inputType.fields()) {
checkInputType(field.dataType());
}
return impl;
}
// also allow integer and interval type for testing purpose
private static void checkInputType(DataType type) {
if (!(type instanceof IntegerType || type instanceof LongType ||
type instanceof DayTimeIntervalType)) {
throw new UnsupportedOperationException(
"Expect one of [IntegerType|LongType|DateTimeIntervalType] but found " + type);
}
}
@Override
public String description() {
return "long_add";
}
public abstract static | JavaLongAdd |
java | apache__flink | flink-formats/flink-json/src/main/java/org/apache/flink/formats/json/JsonToRowDataConverters.java | {
"start": 3119,
"end": 3205
} | class ____ to convert from {@link JsonNode} to {@link RowData}. * */
@Internal
public | used |
java | quarkusio__quarkus | core/deployment/src/main/java/io/quarkus/deployment/builditem/ExtensionSslNativeSupportBuildItem.java | {
"start": 596,
"end": 977
} | class ____ extends MultiBuildItem {
private String extension;
public ExtensionSslNativeSupportBuildItem(Feature feature) {
this(feature.getName());
}
public ExtensionSslNativeSupportBuildItem(String extension) {
this.extension = extension;
}
public String getExtension() {
return extension;
}
}
| ExtensionSslNativeSupportBuildItem |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest-jackson/deployment/src/test/java/io/quarkus/resteasy/reactive/jackson/deployment/test/CustomSerializerTest.java | {
"start": 2337,
"end": 2509
} | class ____ {
@GET
public CustomData getCustom() {
return new CustomData("test-data", FIXED_TIME);
}
}
static | CustomJacksonEndpoint |
java | alibaba__druid | core/src/main/java/com/alibaba/druid/wall/WallCheckResult.java | {
"start": 780,
"end": 3401
} | class ____ {
private final List<SQLStatement> statementList;
private final Map<String, WallSqlTableStat> tableStats;
private final List<Violation> violations;
private final Map<String, WallSqlFunctionStat> functionStats;
private final boolean syntaxError;
private final WallSqlStat sqlStat;
private String sql;
private List<WallUpdateCheckItem> updateCheckItems;
public WallCheckResult() {
this(null);
}
public WallCheckResult(WallSqlStat sqlStat, List<SQLStatement> stmtList) {
if (sqlStat != null) {
tableStats = sqlStat.getTableStats();
violations = sqlStat.getViolations();
functionStats = sqlStat.getFunctionStats();
statementList = stmtList;
syntaxError = sqlStat.isSyntaxError();
} else {
tableStats = Collections.emptyMap();
violations = Collections.emptyList();
functionStats = Collections.emptyMap();
statementList = stmtList;
syntaxError = false;
}
this.sqlStat = sqlStat;
}
public WallCheckResult(WallSqlStat sqlStat) {
this(sqlStat, Collections.<SQLStatement>emptyList());
}
public WallCheckResult(WallSqlStat sqlStat, List<Violation> violations, Map<String, WallSqlTableStat> tableStats,
Map<String, WallSqlFunctionStat> functionStats, List<SQLStatement> statementList,
boolean syntaxError) {
this.sqlStat = sqlStat;
this.tableStats = tableStats;
this.violations = violations;
this.functionStats = functionStats;
this.statementList = statementList;
this.syntaxError = syntaxError;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public List<Violation> getViolations() {
return violations;
}
public List<SQLStatement> getStatementList() {
return statementList;
}
public Map<String, WallSqlTableStat> getTableStats() {
return tableStats;
}
public Map<String, WallSqlFunctionStat> getFunctionStats() {
return functionStats;
}
public boolean isSyntaxError() {
return syntaxError;
}
public WallSqlStat getSqlStat() {
return sqlStat;
}
public List<WallUpdateCheckItem> getUpdateCheckItems() {
return updateCheckItems;
}
public void setUpdateCheckItems(List<WallUpdateCheckItem> updateCheckItems) {
this.updateCheckItems = updateCheckItems;
}
}
| WallCheckResult |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/scheduling/concurrent/ConcurrentTaskExecutorTests.java | {
"start": 1284,
"end": 3213
} | class ____ extends AbstractSchedulingTaskExecutorTests {
private final ThreadPoolExecutor concurrentExecutor =
new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>());
@Override
protected AsyncTaskExecutor buildExecutor() {
concurrentExecutor.setThreadFactory(new CustomizableThreadFactory(this.threadNamePrefix));
return new ConcurrentTaskExecutor(concurrentExecutor);
}
@AfterEach
@Override
void shutdownExecutor() {
for (Runnable task : concurrentExecutor.shutdownNow()) {
if (task instanceof Future) {
((Future<?>) task).cancel(true);
}
}
}
@Test
void zeroArgCtorResultsInDefaultTaskExecutorBeingUsed() {
@SuppressWarnings("deprecation")
ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor();
assertThatCode(() -> executor.execute(new NoOpRunnable())).doesNotThrowAnyException();
}
@Test
void passingNullExecutorToCtorResultsInDefaultTaskExecutorBeingUsed() {
ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor(null);
assertThatCode(() -> executor.execute(new NoOpRunnable())).hasMessage("Executor not configured");
}
@Test
void earlySetConcurrentExecutorCallRespectsConfiguredTaskDecorator() {
@SuppressWarnings("deprecation")
ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor();
executor.setConcurrentExecutor(new DecoratedExecutor());
executor.setTaskDecorator(new RunnableDecorator());
assertThatCode(() -> executor.execute(new NoOpRunnable())).doesNotThrowAnyException();
}
@Test
void lateSetConcurrentExecutorCallRespectsConfiguredTaskDecorator() {
@SuppressWarnings("deprecation")
ConcurrentTaskExecutor executor = new ConcurrentTaskExecutor();
executor.setTaskDecorator(new RunnableDecorator());
executor.setConcurrentExecutor(new DecoratedExecutor());
assertThatCode(() -> executor.execute(new NoOpRunnable())).doesNotThrowAnyException();
}
private static | ConcurrentTaskExecutorTests |
java | quarkusio__quarkus | extensions/qute/deployment/src/test/java/io/quarkus/qute/deployment/VariantTemplateTest.java | {
"start": 1423,
"end": 1491
} | class ____ {
@Inject
Template foo;
}
}
| SimpleBean |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_846/UpdateTest.java | {
"start": 390,
"end": 479
} | class ____ {
@ProcessorTest
public void shouldProduceMapper() {
}
}
| UpdateTest |
java | elastic__elasticsearch | x-pack/plugin/searchable-snapshots/src/main/java/org/elasticsearch/xpack/searchablesnapshots/action/cache/TransportSearchableSnapshotCacheStoresAction.java | {
"start": 5898,
"end": 6503
} | class ____ extends BaseNodesResponse<NodeCacheFilesMetadata> {
public NodesCacheFilesMetadata(ClusterName clusterName, List<NodeCacheFilesMetadata> nodes, List<FailedNodeException> failures) {
super(clusterName, nodes, failures);
}
@Override
protected List<NodeCacheFilesMetadata> readNodesFrom(StreamInput in) {
return TransportAction.localOnly();
}
@Override
protected void writeNodesTo(StreamOutput out, List<NodeCacheFilesMetadata> nodes) {
TransportAction.localOnly();
}
}
}
| NodesCacheFilesMetadata |
java | quarkusio__quarkus | extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/AnnotationBasedAuthMechanismSelectionTest.java | {
"start": 18236,
"end": 18931
} | class ____ auth mechanism is going to be used
return super.overriddenParentClassEndpoint();
}
@GET
@HttpAuthenticationMechanism("custom")
@Path("same-mech")
public String authPolicyIsUsingSameMechAsAnnotation() {
// policy uses custom mechanism and annotation selects custom mechanism as well
return "same-mech";
}
@GET
@HttpAuthenticationMechanism("custom")
@Path("diff-mech")
public String authPolicyIsUsingDiffMechAsAnnotation() {
// policy uses basic mechanism and annotation selects custom mechanism
return "diff-mech";
}
}
public | http |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/UpdateIndexMigrationVersionAction.java | {
"start": 5709,
"end": 9570
} | class ____ implements ClusterStateTaskListener {
private final ActionListener<Void> listener;
private final int indexMigrationVersion;
private final String indexName;
private final ProjectId projectId;
UpdateIndexMigrationVersionTask(
ActionListener<Void> listener,
int indexMigrationVersion,
String indexName,
ProjectId projectId
) {
this.listener = listener;
this.indexMigrationVersion = indexMigrationVersion;
this.indexName = indexName;
this.projectId = projectId;
}
ClusterState execute(ClusterState currentState) {
final Metadata metadata = currentState.metadata();
if (metadata.hasProject(projectId) == false) {
// project has been deleted? nothing to do
logger.warn(
"Cannot update security index [{}] in project [{}] to migration-version [{}]"
+ " because it does not exist in cluster state",
indexName,
projectId,
indexMigrationVersion
);
return currentState;
}
final var project = metadata.getProject(projectId);
IndexMetadata.Builder indexMetadataBuilder = IndexMetadata.builder(project.indices().get(indexName));
indexMetadataBuilder.putCustom(
MIGRATION_VERSION_CUSTOM_KEY,
Map.of(MIGRATION_VERSION_CUSTOM_DATA_KEY, Integer.toString(indexMigrationVersion))
);
indexMetadataBuilder.version(indexMetadataBuilder.version() + 1);
final ImmutableOpenMap.Builder<String, IndexMetadata> builder = ImmutableOpenMap.builder(project.indices());
builder.put(indexName, indexMetadataBuilder.build());
return ClusterState.builder(currentState)
.putProjectMetadata(ProjectMetadata.builder(project).indices(builder.build()).build())
.build();
}
@Override
public void onFailure(Exception e) {
listener.onFailure(e);
}
}
@Override
protected void masterOperation(
Task task,
Request request,
ClusterState state,
ActionListener<UpdateIndexMigrationVersionResponse> listener
) throws Exception {
final ProjectId projectId = projectResolver.getProjectId();
updateIndexMigrationVersionTaskQueue.submitTask(
"Updating cluster state with a new index migration version",
new UpdateIndexMigrationVersionTask(ActionListener.wrap(response -> {
logger.info(
"Updated project=[{}] index=[{}] to migration-version=[{}]",
projectId,
request.getIndexName(),
request.getIndexMigrationVersion()
);
listener.onResponse(new UpdateIndexMigrationVersionResponse());
}, listener::onFailure), request.getIndexMigrationVersion(), request.getIndexName(), projectId),
null
);
}
@Override
protected ClusterBlockException checkBlock(Request request, ClusterState state) {
return state.blocks()
.indicesBlockedException(
projectResolver.getProjectId(),
ClusterBlockLevel.METADATA_WRITE,
new String[] { request.getIndexName() }
);
}
}
}
| UpdateIndexMigrationVersionTask |
java | spring-projects__spring-framework | spring-web/src/test/java/org/springframework/web/bind/support/WebRequestDataBinderIntegrationTests.java | {
"start": 5147,
"end": 5612
} | class ____ {
private Part firstPart;
private Part secondPart;
public Part getFirstPart() {
return firstPart;
}
@SuppressWarnings("unused")
public void setFirstPart(Part firstPart) {
this.firstPart = firstPart;
}
public Part getSecondPart() {
return secondPart;
}
@SuppressWarnings("unused")
public void setSecondPart(Part secondPart) {
this.secondPart = secondPart;
}
}
@SuppressWarnings("serial")
private static | PartsBean |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/AllocatedSlotReport.java | {
"start": 1270,
"end": 2184
} | class ____ implements Serializable {
private static final long serialVersionUID = 1L;
private final JobID jobId;
/** The allocated slots in slot pool. */
private final Collection<AllocatedSlotInfo> allocatedSlotInfos;
public AllocatedSlotReport(JobID jobId, Collection<AllocatedSlotInfo> allocatedSlotInfos) {
this.jobId = checkNotNull(jobId);
this.allocatedSlotInfos = checkNotNull(allocatedSlotInfos);
}
public JobID getJobId() {
return jobId;
}
public Collection<AllocatedSlotInfo> getAllocatedSlotInfos() {
return Collections.unmodifiableCollection(allocatedSlotInfos);
}
@Override
public String toString() {
return "AllocatedSlotReport{"
+ "jobId="
+ jobId
+ ", allocatedSlotInfos="
+ allocatedSlotInfos
+ '}';
}
}
| AllocatedSlotReport |
java | apache__camel | components/camel-mongodb/src/test/java/org/apache/camel/component/mongodb/integration/MongoDbConversionsIT.java | {
"start": 6023,
"end": 6998
} | class ____ {
public int number = 123;
public String text = "hello";
public String[] array = { "daVinci", "copernico", "einstein" };
public String _id = "testInsertPojo";
}
@Test
public void shouldConvertJsonStringListToBSONList() {
String jsonListArray = "[{\"key\":\"value1\"}, {\"key\":\"value2\"}]";
List<Bson> bsonList = MongoDbBasicConverters.fromStringToList(jsonListArray);
assertNotNull(bsonList);
assertEquals(2, bsonList.size());
String jsonEmptyArray = "[]";
bsonList = MongoDbBasicConverters.fromStringToList(jsonEmptyArray);
assertNotNull(bsonList);
assertEquals(0, bsonList.size());
}
@Test
public void shouldNotConvertJsonStringListToBSONList() {
String jsonSingleValue = "{\"key\":\"value1\"}";
List<Bson> bsonList = MongoDbBasicConverters.fromStringToList(jsonSingleValue);
assertNull(bsonList);
}
}
| MyPojoTest |
java | apache__flink | flink-core/src/main/java/org/apache/flink/api/common/typeutils/base/array/LongPrimitiveArrayComparator.java | {
"start": 1090,
"end": 2155
} | class ____ extends PrimitiveArrayComparator<long[], LongComparator> {
public LongPrimitiveArrayComparator(boolean ascending) {
super(ascending, new LongComparator(ascending));
}
@Override
public int hash(long[] record) {
int result = 0;
for (long field : record) {
result += (int) (field ^ (field >>> 32));
}
return result;
}
@Override
public int compare(long[] first, long[] second) {
for (int x = 0; x < min(first.length, second.length); x++) {
int cmp = first[x] < second[x] ? -1 : (first[x] == second[x] ? 0 : 1);
if (cmp != 0) {
return ascending ? cmp : -cmp;
}
}
int cmp = first.length - second.length;
return ascending ? cmp : -cmp;
}
@Override
public TypeComparator<long[]> duplicate() {
LongPrimitiveArrayComparator dupe = new LongPrimitiveArrayComparator(this.ascending);
dupe.setReference(this.reference);
return dupe;
}
}
| LongPrimitiveArrayComparator |
java | redisson__redisson | redisson/src/main/java/org/redisson/liveobject/misc/ClassUtils.java | {
"start": 8299,
"end": 8448
} | class ____ a primitive type (int, float, etc.)
* then it is translated into its wrapper type (Integer, Float, etc.). If
* the passed | represents |
java | apache__avro | lang/java/avro/src/main/java/org/apache/avro/Schema.java | {
"start": 33382,
"end": 33843
} | enum ____ set: " + symbols);
}
}
@Override
public List<String> getEnumSymbols() {
return symbols;
}
@Override
public boolean hasEnumSymbol(String symbol) {
return ordinals.containsKey(symbol);
}
@Override
public int getEnumOrdinal(String symbol) {
Integer ordinal = ordinals.get(symbol);
if (ordinal == null) {
throw new TracingAvroTypeException(
new AvroTypeException(" | symbol |
java | alibaba__nacos | common/src/test/java/com/alibaba/nacos/common/task/engine/NacosDelayTaskExecuteEngineTest.java | {
"start": 1448,
"end": 5907
} | class ____ {
private NacosDelayTaskExecuteEngine nacosDelayTaskExecuteEngine;
@Mock
private NacosTaskProcessor taskProcessor;
@Mock
private NacosTaskProcessor testTaskProcessor;
private AbstractDelayTask abstractTask;
@BeforeEach
void setUp() throws Exception {
nacosDelayTaskExecuteEngine = new NacosDelayTaskExecuteEngine(NacosDelayTaskExecuteEngineTest.class.getName());
nacosDelayTaskExecuteEngine.setDefaultTaskProcessor(taskProcessor);
abstractTask = new AbstractDelayTask() {
@Override
public void merge(AbstractDelayTask task) {
}
};
}
@AfterEach
void tearDown() throws Exception {
nacosDelayTaskExecuteEngine.shutdown();
}
@Test
void testSize() {
assertEquals(0, nacosDelayTaskExecuteEngine.size());
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
assertEquals(1, nacosDelayTaskExecuteEngine.size());
nacosDelayTaskExecuteEngine.removeTask("test");
assertEquals(0, nacosDelayTaskExecuteEngine.size());
}
@Test
void testIsEmpty() {
assertTrue(nacosDelayTaskExecuteEngine.isEmpty());
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
assertFalse(nacosDelayTaskExecuteEngine.isEmpty());
nacosDelayTaskExecuteEngine.removeTask("test");
assertTrue(nacosDelayTaskExecuteEngine.isEmpty());
}
@Test
void testAddProcessor() throws InterruptedException {
when(testTaskProcessor.process(abstractTask)).thenReturn(true);
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
TimeUnit.MILLISECONDS.sleep(200);
verify(testTaskProcessor).process(abstractTask);
verify(taskProcessor, never()).process(abstractTask);
assertEquals(1, nacosDelayTaskExecuteEngine.getAllProcessorKey().size());
}
@Test
void testRemoveProcessor() throws InterruptedException {
when(taskProcessor.process(abstractTask)).thenReturn(true);
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
nacosDelayTaskExecuteEngine.removeProcessor("test");
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
TimeUnit.MILLISECONDS.sleep(200);
verify(testTaskProcessor, never()).process(abstractTask);
verify(taskProcessor).process(abstractTask);
}
@Test
void testRetryTaskAfterFail() throws InterruptedException {
when(taskProcessor.process(abstractTask)).thenReturn(false, true);
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
TimeUnit.MILLISECONDS.sleep(300);
verify(taskProcessor, new Times(2)).process(abstractTask);
}
@Test
void testProcessorWithException() throws InterruptedException {
when(taskProcessor.process(abstractTask)).thenThrow(new RuntimeException("test"));
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
nacosDelayTaskExecuteEngine.removeProcessor("test");
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
TimeUnit.MILLISECONDS.sleep(150);
assertEquals(1, nacosDelayTaskExecuteEngine.size());
}
@Test
void testTaskShouldNotExecute() throws InterruptedException {
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
abstractTask.setTaskInterval(10000L);
abstractTask.setLastProcessTime(System.currentTimeMillis());
TimeUnit.MILLISECONDS.sleep(200);
verify(testTaskProcessor, never()).process(abstractTask);
assertEquals(1, nacosDelayTaskExecuteEngine.size());
}
@Test
void testTaskMerge() {
nacosDelayTaskExecuteEngine.addProcessor("test", testTaskProcessor);
nacosDelayTaskExecuteEngine.addTask("test", abstractTask);
nacosDelayTaskExecuteEngine.addTask("test", new AbstractDelayTask() {
@Override
public void merge(AbstractDelayTask task) {
setLastProcessTime(task.getLastProcessTime());
setTaskInterval(task.getTaskInterval());
}
});
assertEquals(1, nacosDelayTaskExecuteEngine.size());
}
}
| NacosDelayTaskExecuteEngineTest |
java | apache__flink | flink-table/flink-table-api-java/src/test/java/org/apache/flink/table/test/program/TableTestProgram.java | {
"start": 4167,
"end": 10104
} | class ____ {
/** Identifier of the test program (e.g. for naming generated files). */
public final String id;
/** Description for internal documentation. */
public final String description;
/** Steps to be executed for setting up an environment. */
public final List<TestStep> setupSteps;
/** Steps to be executed for running the actual test. */
public final List<TestStep> runSteps;
private TableTestProgram(
String id, String description, List<TestStep> setupSteps, List<TestStep> runSteps) {
this.id = id;
this.description = description;
this.setupSteps = setupSteps;
this.runSteps = runSteps;
}
@Override
public String toString() {
return id;
}
/**
* Entrypoint for a {@link TableTestProgram} that forces an identifier and description of the
* test program.
*
* <p>The identifier is necessary to (ideally globally) identify the test program in outputs.
* For example, a runner for plan tests can create directories and use the name as file names.
* The identifier must start with the name of the exec node under testing.
*
* <p>The description should give more context and should start with a verb and "s" suffix.
*
* <p>For example:
*
* <ul>
* <li>TableTestProgram.of("join-outer", "tests outer joins")
* <li>TableTestProgram.of("rank-x-enabled", "validates a rank with config flag 'x' set")
* <li>TableTestProgram.of("calc-with-projection", "verifies FLINK-12345 is fixed due to
* missing row projection")
* </ul>
*/
public static Builder of(String id, String description) {
return new Builder(id, description);
}
/** A helper method to avoid casting. It assumes that the order of steps is not important. */
public List<SourceTestStep> getSetupSourceTestSteps() {
final EnumSet<TestKind> sourceKinds =
EnumSet.of(
TestKind.SOURCE_WITHOUT_DATA,
TestKind.SOURCE_WITH_DATA,
TestKind.SOURCE_WITH_RESTORE_DATA);
return setupSteps.stream()
.filter(s -> sourceKinds.contains(s.getKind()))
.map(SourceTestStep.class::cast)
.collect(Collectors.toList());
}
/** A helper method to avoid casting. It assumes that the order of steps is not important. */
public List<SinkTestStep> getSetupSinkTestSteps() {
final EnumSet<TestKind> sinkKinds =
EnumSet.of(
TestKind.SINK_WITHOUT_DATA,
TestKind.SINK_WITH_DATA,
TestKind.SINK_WITH_RESTORE_DATA);
return setupSteps.stream()
.filter(s -> sinkKinds.contains(s.getKind()))
.map(SinkTestStep.class::cast)
.collect(Collectors.toList());
}
/** A helper method to avoid casting. It assumes that the order of steps is not important. */
public List<ModelTestStep> getSetupModelTestSteps() {
return setupSteps.stream()
.filter(s -> s.getKind() == TestKind.MODEL)
.map(ModelTestStep.class::cast)
.collect(Collectors.toList());
}
/** A helper method to avoid casting. It assumes that the order of steps is not important. */
public List<ConfigOptionTestStep<?>> getSetupConfigOptionTestSteps() {
return setupSteps.stream()
.filter(s -> s.getKind() == TestKind.CONFIG)
.map(s -> (ConfigOptionTestStep<?>) s)
.collect(Collectors.toList());
}
/** A helper method to avoid casting. It assumes that the order of steps is not important. */
public List<FunctionTestStep> getSetupFunctionTestSteps() {
return setupSteps.stream()
.filter(s -> s.getKind() == TestKind.FUNCTION)
.map(FunctionTestStep.class::cast)
.collect(Collectors.toList());
}
/** A helper method to avoid casting. It assumes that the order of steps is not important. */
public List<SqlTestStep> getSetupSqlTestSteps() {
return setupSteps.stream()
.filter(s -> s.getKind() == TestKind.SQL)
.map(SqlTestStep.class::cast)
.collect(Collectors.toList());
}
/** A helper method to avoid casting. It assumes that the order of steps is not important. */
public List<TemporalFunctionTestStep> getSetupTemporalFunctionTestSteps() {
return setupSteps.stream()
.filter(s -> s.getKind() == TestKind.TEMPORAL_FUNCTION)
.map(TemporalFunctionTestStep.class::cast)
.collect(Collectors.toList());
}
/**
* A helper method to avoid boilerplate code. It assumes that only a single SQL statement is
* tested.
*/
public SqlTestStep getRunSqlTestStep() {
final List<TestStep> sqlSteps =
runSteps.stream()
.filter(s -> s.getKind() == TestKind.SQL)
.collect(Collectors.toList());
Preconditions.checkArgument(sqlSteps.size() == 1, "Single SQL step expected.");
return (SqlTestStep) sqlSteps.get(0);
}
/** A helper method to avoid boilerplate code. It assumes only one statement set is tested. */
public StatementSetTestStep getRunStatementSetTestStep() {
List<TestStep> statementSetSteps =
runSteps.stream()
.filter(s -> s.getKind() == TestKind.STATEMENT_SET)
.collect(Collectors.toList());
Preconditions.checkArgument(
statementSetSteps.size() == 1, "Single StatementSet step expected.");
return (StatementSetTestStep) statementSetSteps.get(0);
}
/** Builder pattern for {@link TableTestProgram}. */
public static | TableTestProgram |
java | apache__flink | flink-table/flink-table-api-java/src/main/java/org/apache/flink/table/api/internal/TableImpl.java | {
"start": 22149,
"end": 23393
} | class ____ implements FlatAggregateTable {
private final TableImpl table;
private final List<Expression> groupKey;
private final Expression tableAggregateFunction;
private FlatAggregateTableImpl(
TableImpl table, List<Expression> groupKey, Expression tableAggregateFunction) {
this.table = table;
this.groupKey = groupKey;
this.tableAggregateFunction = tableAggregateFunction;
}
@Override
public Table select(Expression... fields) {
return table.createTable(
table.operationTreeBuilder.project(
Arrays.asList(fields),
table.operationTreeBuilder.tableAggregate(
groupKey,
tableAggregateFunction.accept(table.lookupResolver),
table.operationTree)));
}
}
// --------------------------------------------------------------------------------------------
// Group Windowed Table
// --------------------------------------------------------------------------------------------
private static final | FlatAggregateTableImpl |
java | elastic__elasticsearch | x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/action/ClearDeploymentCacheActionResponseTests.java | {
"start": 427,
"end": 1111
} | class ____ extends AbstractWireSerializingTestCase<ClearDeploymentCacheAction.Response> {
@Override
protected Writeable.Reader<ClearDeploymentCacheAction.Response> instanceReader() {
return ClearDeploymentCacheAction.Response::new;
}
@Override
protected ClearDeploymentCacheAction.Response createTestInstance() {
return new ClearDeploymentCacheAction.Response(randomBoolean());
}
@Override
protected ClearDeploymentCacheAction.Response mutateInstance(ClearDeploymentCacheAction.Response instance) {
return null;// TODO implement https://github.com/elastic/elasticsearch/issues/25929
}
}
| ClearDeploymentCacheActionResponseTests |
java | spring-projects__spring-security | config/src/main/java/org/springframework/security/config/http/SecurityFilters.java | {
"start": 855,
"end": 2192
} | enum ____ {
FIRST(Integer.MIN_VALUE),
DISABLE_ENCODE_URL_FILTER,
FORCE_EAGER_SESSION_FILTER,
@Deprecated
CHANNEL_FILTER,
HTTPS_REDIRECT_FILTER,
SECURITY_CONTEXT_FILTER,
CONCURRENT_SESSION_FILTER,
WEB_ASYNC_MANAGER_FILTER,
HEADERS_FILTER,
CORS_FILTER,
SAML2_LOGOUT_REQUEST_FILTER,
SAML2_LOGOUT_RESPONSE_FILTER,
CSRF_FILTER,
SAML2_LOGOUT_FILTER,
LOGOUT_FILTER,
OAUTH2_AUTHORIZATION_REQUEST_FILTER,
SAML2_AUTHENTICATION_REQUEST_FILTER,
X509_FILTER,
PRE_AUTH_FILTER,
CAS_FILTER,
OAUTH2_LOGIN_FILTER,
SAML2_AUTHENTICATION_FILTER,
FORM_LOGIN_FILTER,
DEFAULT_RESOURCES_FILTER,
LOGIN_PAGE_FILTER,
LOGOUT_PAGE_FILTER,
DIGEST_AUTH_FILTER,
BEARER_TOKEN_AUTH_FILTER,
BASIC_AUTH_FILTER,
REQUEST_CACHE_FILTER,
SERVLET_API_SUPPORT_FILTER,
JAAS_API_SUPPORT_FILTER,
REMEMBER_ME_FILTER,
ANONYMOUS_FILTER,
OAUTH2_AUTHORIZATION_CODE_GRANT_FILTER,
WELL_KNOWN_CHANGE_PASSWORD_REDIRECT_FILTER,
SESSION_MANAGEMENT_FILTER,
EXCEPTION_TRANSLATION_FILTER,
FILTER_SECURITY_INTERCEPTOR,
SWITCH_USER_FILTER,
LAST(Integer.MAX_VALUE);
private static final int INTERVAL = 100;
private final int order;
SecurityFilters() {
this.order = ordinal() * INTERVAL;
}
SecurityFilters(int order) {
this.order = order;
}
public int getOrder() {
return this.order;
}
}
| SecurityFilters |
java | spring-projects__spring-security | oauth2/oauth2-resource-server/src/test/java/org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunctionTests.java | {
"start": 1681,
"end": 4262
} | class ____ {
private ServerBearerExchangeFilterFunction function = new ServerBearerExchangeFilterFunction();
private MockExchangeFunction exchange = new MockExchangeFunction();
private OAuth2AccessToken accessToken = new OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, "token-0",
Instant.now(), Instant.now().plus(Duration.ofDays(1)));
private Authentication authentication = new AbstractOAuth2TokenAuthenticationToken<OAuth2AccessToken>(
this.accessToken) {
@Override
public Map<String, Object> getTokenAttributes() {
return Collections.emptyMap();
}
};
@Test
public void filterWhenUnauthenticatedThenAuthorizationHeaderNull() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange).block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
@Test
public void filterWhenAuthenticatedThenAuthorizationHeaderNull() throws Exception {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication))
.block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION))
.isEqualTo("Bearer " + this.accessToken.getTokenValue());
}
// gh-7353
@Test
public void filterWhenAuthenticatedWithOtherTokenThenAuthorizationHeaderNull() throws Exception {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com")).build();
TestingAuthenticationToken token = new TestingAuthenticationToken("user", "pass");
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(token))
.block();
assertThat(this.exchange.getRequest().headers().getFirst(HttpHeaders.AUTHORIZATION)).isNull();
}
@Test
public void filterWhenExistingAuthorizationThenSingleAuthorizationHeader() {
ClientRequest request = ClientRequest.create(HttpMethod.GET, URI.create("https://example.com"))
.header(HttpHeaders.AUTHORIZATION, "Existing")
.build();
this.function.filter(request, this.exchange)
.contextWrite(ReactiveSecurityContextHolder.withAuthentication(this.authentication))
.block();
HttpHeaders headers = this.exchange.getRequest().headers();
assertThat(headers.get(HttpHeaders.AUTHORIZATION)).containsOnly("Bearer " + this.accessToken.getTokenValue());
}
}
| ServerBearerExchangeFilterFunctionTests |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/Dhis2EndpointBuilderFactory.java | {
"start": 40626,
"end": 42254
} | interface ____
extends
AdvancedDhis2EndpointConsumerBuilder,
AdvancedDhis2EndpointProducerBuilder {
default Dhis2EndpointBuilder basic() {
return (Dhis2EndpointBuilder) this;
}
/**
* References a user-defined
* org.hisp.dhis.integration.sdk.api.Dhis2Client. This option is
* mutually exclusive to the baseApiUrl, username, password, and
* personalAccessToken options.
*
* The option is a:
* <code>org.hisp.dhis.integration.sdk.api.Dhis2Client</code> type.
*
* Group: advanced
*
* @param client the value to set
* @return the dsl builder
*/
default AdvancedDhis2EndpointBuilder client(org.hisp.dhis.integration.sdk.api.Dhis2Client client) {
doSetProperty("client", client);
return this;
}
/**
* References a user-defined
* org.hisp.dhis.integration.sdk.api.Dhis2Client. This option is
* mutually exclusive to the baseApiUrl, username, password, and
* personalAccessToken options.
*
* The option will be converted to a
* <code>org.hisp.dhis.integration.sdk.api.Dhis2Client</code> type.
*
* Group: advanced
*
* @param client the value to set
* @return the dsl builder
*/
default AdvancedDhis2EndpointBuilder client(String client) {
doSetProperty("client", client);
return this;
}
}
public | AdvancedDhis2EndpointBuilder |
java | dropwizard__dropwizard | dropwizard-client/src/test/java/io/dropwizard/client/JerseyIgnoreRequestUserAgentHeaderFilterTest.java | {
"start": 3501,
"end": 3878
} | class ____ extends Application<Configuration> {
public static void main(String[] args) throws Exception {
new TestApplication().run(args);
}
@Override
public void run(Configuration configuration, Environment environment) throws Exception {
environment.jersey().register(TestResource.class);
}
}
}
| TestApplication |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/BothBlockingAndNonBlockingOnApplicationTest.java | {
"start": 692,
"end": 1312
} | class ____ {
@RegisterExtension
static ResteasyReactiveUnitTest test = new ResteasyReactiveUnitTest()
.setArchiveProducer(new Supplier<>() {
@Override
public JavaArchive get() {
return ShrinkWrap.create(JavaArchive.class)
.addClasses(Resource.class, MyApplication.class);
}
}).setExpectedException(DeploymentException.class);
@Test
public void test() {
fail("Should never have been called");
}
@Path("test")
public static | BothBlockingAndNonBlockingOnApplicationTest |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/basic/RelationTargetNotFoundConfigTest.java | {
"start": 4801,
"end": 5707
} | class ____ {
@Id
private Integer id;
@ManyToOne
@Audited(targetAuditMode = RelationTargetAuditMode.NOT_AUDITED)
private Bar bar;
@ManyToOne
private FooBar fooBar;
@ManyToOne
private FooBar fooBar2;
Foo() {
// Required by JPA
}
Foo(Integer id, Bar bar, FooBar fooBar, FooBar fooBar2) {
this.id = id;
this.bar = bar;
this.fooBar = fooBar;
this.fooBar2 = fooBar2;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Bar getBar() {
return bar;
}
public void setBar(Bar bar) {
this.bar = bar;
}
public FooBar getFooBar() {
return fooBar;
}
public void setFooBar(FooBar fooBar) {
this.fooBar = fooBar;
}
public FooBar getFooBar2() {
return fooBar2;
}
public void setFooBar2(FooBar fooBar2) {
this.fooBar2 = fooBar2;
}
}
@Entity(name = "Bar")
public static | Foo |
java | redisson__redisson | redisson/src/main/java/org/redisson/cache/AbstractCacheMap.java | {
"start": 11300,
"end": 12485
} | class ____ extends AbstractCollection<V> {
@Override
public Iterator<V> iterator() {
return new MapIterator<V>() {
@Override
public V next() {
if (mapEntry == null) {
throw new NoSuchElementException();
}
V value = readValue(mapEntry.getValue());
mapEntry = null;
return value;
}
@Override
public void remove() {
if (mapEntry == null) {
throw new IllegalStateException();
}
map.remove(mapEntry.getKey(), mapEntry.getValue());
mapEntry = null;
}
};
}
@Override
public boolean contains(Object o) {
return AbstractCacheMap.this.containsValue(o);
}
@Override
public int size() {
return AbstractCacheMap.this.size();
}
@Override
public void clear() {
AbstractCacheMap.this.clear();
}
}
final | Values |
java | elastic__elasticsearch | x-pack/plugin/esql/compute/src/main/java/org/elasticsearch/compute/lucene/read/SingletonBytesRefBuilder.java | {
"start": 2676,
"end": 4384
} | class ____ implements LongArray {
private final long offset;
private final long size;
ConstantOffsetLongArrayWrapper(long offset, long size) {
this.offset = offset;
this.size = size;
}
@Override
public long get(long index) {
assert index >= 0 && index < size;
return index * offset;
}
@Override
public long getAndSet(long index, long value) {
throw new UnsupportedOperationException();
}
@Override
public void set(long index, long value) {
throw new UnsupportedOperationException();
}
@Override
public long increment(long index, long inc) {
throw new UnsupportedOperationException();
}
@Override
public void fill(long fromIndex, long toIndex, long value) {
throw new UnsupportedOperationException();
}
@Override
public void fillWith(StreamInput in) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public void set(long index, byte[] buf, int offset, int len) {
throw new UnsupportedOperationException();
}
@Override
public void writeTo(StreamOutput out) throws IOException {
throw new UnsupportedOperationException();
}
@Override
public long size() {
return size;
}
@Override
public long ramBytesUsed() {
return 2 * Long.BYTES; // offset + size
}
@Override
public void close() {}
}
static | ConstantOffsetLongArrayWrapper |
java | mapstruct__mapstruct | processor/src/test/java/org/mapstruct/ap/test/bugs/_394/SameClassNameInDifferentPackageTest.java | {
"start": 793,
"end": 1545
} | class ____ {
@ProcessorTest
public void shouldCreateMapMethodImplementation() {
Map<String, AnotherCar> values = new HashMap<String, AnotherCar>();
//given
AnotherCar honda = new AnotherCar( "Honda", 2 );
AnotherCar toyota = new AnotherCar( "Toyota", 2);
values.put( "Honda", honda );
values.put( "Toyota", toyota );
Cars cars = new Cars();
cars.setMakeToCar( values );
org.mapstruct.ap.test.bugs._394._target.Cars targetCars = SameNameForSourceAndTargetCarsMapper.INSTANCE
.sourceCarsToTargetCars( cars );
assertThat( targetCars ).isNotNull();
assertThat( targetCars.getMakeToCar() ).hasSize( 2 );
}
}
| SameClassNameInDifferentPackageTest |
java | elastic__elasticsearch | docs/src/yamlRestTest/java/org/elasticsearch/smoketest/DocsClientYamlTestSuiteIT.java | {
"start": 12823,
"end": 18549
} | class ____ implements ExecutableSection {
private static final ConstructingObjectParser<CompareAnalyzers, XContentLocation> PARSER = new ConstructingObjectParser<>(
"test_analyzer",
false,
(a, location) -> {
String index = (String) a[0];
String first = (String) a[1];
String second = (String) a[2];
return new CompareAnalyzers(location, index, first, second);
}
);
static {
PARSER.declareString(constructorArg(), new ParseField("index"));
PARSER.declareString(constructorArg(), new ParseField("first"));
PARSER.declareString(constructorArg(), new ParseField("second"));
}
private static CompareAnalyzers parse(XContentParser parser) throws IOException {
XContentLocation location = parser.getTokenLocation();
CompareAnalyzers section = PARSER.parse(parser, location);
assert parser.currentToken() == Token.END_OBJECT : "End of object required";
parser.nextToken(); // throw out the END_OBJECT to conform with other ExecutableSections
return section;
}
private final XContentLocation location;
private final String index;
private final String first;
private final String second;
private CompareAnalyzers(XContentLocation location, String index, String first, String second) {
this.location = location;
this.index = index;
this.first = first;
this.second = second;
}
@Override
public XContentLocation getLocation() {
return location;
}
@Override
public void execute(ClientYamlTestExecutionContext executionContext) throws IOException {
int size = 100;
int maxLength = 15;
List<String> testText = new ArrayList<>(size);
for (int i = 0; i < size; i++) {
/*
* Build a string with a few unicode sequences separated by
* spaces. The unicode sequences aren't going to be of the same
* code page which is a shame because it makes the entire
* string less realistic. But this still provides a fairly
* nice string to compare.
*/
int spaces = between(0, 5);
StringBuilder b = new StringBuilder((spaces + 1) * maxLength);
b.append(randomRealisticUnicodeOfCodepointLengthBetween(1, maxLength));
for (int t = 0; t < spaces; t++) {
b.append(' ');
b.append(randomRealisticUnicodeOfCodepointLengthBetween(1, maxLength));
}
testText.add(
b.toString()
// Don't look up stashed values
.replace("$", "\\$")
);
}
Map<String, Object> body = Maps.newMapWithExpectedSize(2);
body.put("analyzer", first);
body.put("text", testText);
ClientYamlTestResponse response = executionContext.callApi(
"indices.analyze",
singletonMap("index", index),
singletonList(body),
emptyMap()
);
Iterator<?> firstTokens = ((List<?>) response.evaluate("tokens")).iterator();
body.put("analyzer", second);
response = executionContext.callApi("indices.analyze", singletonMap("index", index), singletonList(body), emptyMap());
Iterator<?> secondTokens = ((List<?>) response.evaluate("tokens")).iterator();
Object previousFirst = null;
Object previousSecond = null;
while (firstTokens.hasNext()) {
if (false == secondTokens.hasNext()) {
fail(Strings.format("""
%s has fewer tokens than %s. %s has [%s] but %s is out of tokens. \
%s's last token was [%s] and %s's last token was' [%s]
""", second, first, first, firstTokens.next(), second, first, previousFirst, second, previousSecond));
}
Map<?, ?> firstToken = (Map<?, ?>) firstTokens.next();
Map<?, ?> secondToken = (Map<?, ?>) secondTokens.next();
String firstText = (String) firstToken.get("token");
String secondText = (String) secondToken.get("token");
// Check the text and produce an error message with the utf8 sequence if they don't match.
if (false == secondText.equals(firstText)) {
fail(Strings.format("""
text differs: %s was [%s] but %s was [%s]. In utf8 those are
%s and
%s
""", first, firstText, second, secondText, new BytesRef(firstText), new BytesRef(secondText)));
}
// Now check the whole map just in case the text matches but something else differs
assertEquals(firstToken, secondToken);
previousFirst = firstToken;
previousSecond = secondToken;
}
if (secondTokens.hasNext()) {
fail(Strings.format("""
%s has more tokens than %s. %s has [%s] but %s is out of tokens. \
%s's last token was [%s] and %s's last token was [%s]
""", second, first, second, secondTokens.next(), first, first, previousFirst, second, previousSecond));
}
}
}
}
| CompareAnalyzers |
java | apache__camel | components/camel-opentelemetry-metrics/src/test/java/org/apache/camel/opentelemetry/metrics/routepolicy/OpenTelemetryRoutePolicyTest.java | {
"start": 1408,
"end": 3341
} | class ____ extends AbstractOpenTelemetryRoutePolicyTest {
private static final long DELAY_FOO = 20;
private static final long DELAY_BAR = 50;
private static final long TOLERANCE = 20L;
@Test
public void testMetricsRoutePolicy() throws Exception {
int count = 10;
MockEndpoint mockEndpoint = getMockEndpoint("mock:result");
mockEndpoint.expectedMessageCount(count);
for (int i = 0; i < count; i++) {
if (i % 2 == 0) {
template.sendBody("direct:foo", "Hello " + i);
} else {
template.sendBody("direct:bar", "Hello " + i);
}
}
MockEndpoint.assertIsSatisfied(context);
PointData pd = getPointDataForRouteId(DEFAULT_CAMEL_ROUTE_POLICY_METER_NAME, "foo");
verifyHistogramMetric(pd, DELAY_FOO, count / 2);
pd = getPointDataForRouteId(DEFAULT_CAMEL_ROUTE_POLICY_METER_NAME, "bar");
verifyHistogramMetric(pd, DELAY_BAR, count / 2);
}
private void verifyHistogramMetric(PointData pd, long delay, int msgCount) {
assertTrue(pd instanceof HistogramPointData);
HistogramPointData hpd = (HistogramPointData) pd;
assertTrue(hpd.getMax() < delay + TOLERANCE, "max value");
assertTrue(hpd.getMin() >= delay, "min value");
assertEquals(msgCount, hpd.getCount(), "count");
assertTrue(hpd.getSum() >= msgCount * delay, "sum");
}
@Override
protected RouteBuilder createRouteBuilder() {
return new RouteBuilder() {
@Override
public void configure() {
from("direct:foo").routeId("foo")
.delay(DELAY_FOO)
.to("mock:result");
from("direct:bar").routeId("bar")
.delay(DELAY_BAR)
.to("mock:result");
}
};
}
}
| OpenTelemetryRoutePolicyTest |
java | apache__logging-log4j2 | log4j-core/src/main/java/org/apache/logging/log4j/core/appender/mom/kafka/KafkaManager.java | {
"start": 1761,
"end": 7963
} | class ____ extends AbstractManager {
public static final String DEFAULT_TIMEOUT_MILLIS = "30000";
/**
* package-private access for testing.
*/
static KafkaProducerFactory producerFactory = new DefaultKafkaProducerFactory();
private final Properties config = new Properties();
private Producer<byte[], byte[]> producer;
private final int timeoutMillis;
private final String topic;
private final String key;
private final boolean syncSend;
private final boolean sendTimestamp;
private static final KafkaManagerFactory factory = new KafkaManagerFactory();
/*
* The Constructor should have been declared private as all Managers are create
* by the internal factory;
*/
public KafkaManager(
final LoggerContext loggerContext,
final String name,
final String topic,
final boolean syncSend,
final Property[] properties,
final String key) {
this(loggerContext, name, topic, syncSend, false, properties, key);
}
private KafkaManager(
final LoggerContext loggerContext,
final String name,
final String topic,
final boolean syncSend,
final boolean sendTimestamp,
final Property[] properties,
final String key) {
super(loggerContext, name);
this.topic = Objects.requireNonNull(topic, "topic");
this.syncSend = syncSend;
this.sendTimestamp = sendTimestamp;
config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ByteArraySerializer.class);
config.put(ProducerConfig.BATCH_SIZE_CONFIG, 0);
for (final Property property : properties) {
config.setProperty(property.getName(), property.getValue());
}
this.key = key;
String timeoutMillis = config.getProperty("timeout.ms");
if (timeoutMillis == null) {
timeoutMillis = config.getProperty(ProducerConfig.REQUEST_TIMEOUT_MS_CONFIG, DEFAULT_TIMEOUT_MILLIS);
}
this.timeoutMillis = Integers.parseInt(timeoutMillis);
}
@Override
public boolean releaseSub(final long timeout, final TimeUnit timeUnit) {
if (timeout > 0) {
closeProducer(timeout, timeUnit);
} else {
closeProducer(timeoutMillis, TimeUnit.MILLISECONDS);
}
return true;
}
private void closeProducer(final long timeout, final TimeUnit timeUnit) {
if (producer != null) {
// This thread is a workaround for this Kafka issue:
// https://issues.apache.org/jira/browse/KAFKA-1660
final Thread closeThread = new Log4jThread(
() -> {
if (producer != null) {
producer.close();
}
},
"KafkaManager-CloseThread");
closeThread.setDaemon(true); // avoid blocking JVM shutdown
closeThread.start();
try {
closeThread.join(timeUnit.toMillis(timeout));
} catch (final InterruptedException ignore) {
Thread.currentThread().interrupt();
// ignore
}
}
}
@Deprecated
public void send(final byte[] msg) throws ExecutionException, InterruptedException, TimeoutException {
send(msg, null);
}
public void send(final byte[] msg, final Long eventTimestamp)
throws ExecutionException, InterruptedException, TimeoutException {
if (producer != null) {
byte[] newKey = null;
if (key != null && key.contains("${")) {
newKey = getLoggerContext()
.getConfiguration()
.getStrSubstitutor()
.replace(key)
.getBytes(StandardCharsets.UTF_8);
} else if (key != null) {
newKey = key.getBytes(StandardCharsets.UTF_8);
}
final Long timestamp = sendTimestamp ? eventTimestamp : null;
final ProducerRecord<byte[], byte[]> newRecord = new ProducerRecord<>(topic, null, timestamp, newKey, msg);
if (syncSend) {
final Future<RecordMetadata> response = producer.send(newRecord);
response.get(timeoutMillis, TimeUnit.MILLISECONDS);
} else {
producer.send(newRecord, (metadata, e) -> {
if (e != null) {
LOGGER.error("Unable to write to Kafka in appender [" + getName() + "]", e);
}
});
}
}
}
public void startup() {
if (producer == null) {
producer = producerFactory.newKafkaProducer(config);
}
}
public String getTopic() {
return topic;
}
@Deprecated
public static KafkaManager getManager(
final LoggerContext loggerContext,
final String name,
final String topic,
final boolean syncSend,
final Property[] properties,
final String key) {
return getManager(loggerContext, name, topic, syncSend, false, properties, key);
}
static KafkaManager getManager(
final LoggerContext loggerContext,
final String name,
final String topic,
final boolean syncSend,
final boolean sendTimestamp,
final Property[] properties,
final String key) {
final StringBuilder sb = new StringBuilder(name);
sb.append(" ").append(topic).append(" ").append(syncSend).append(" ").append(sendTimestamp);
for (Property prop : properties) {
sb.append(" ").append(prop.getName()).append("=").append(prop.getValue());
}
return getManager(
sb.toString(),
factory,
new FactoryData(loggerContext, topic, syncSend, sendTimestamp, properties, key));
}
private static | KafkaManager |
java | netty__netty | transport/src/main/java/io/netty/channel/socket/nio/SelectorProviderUtil.java | {
"start": 1173,
"end": 3184
} | class ____ {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(SelectorProviderUtil.class);
static Method findOpenMethod(String methodName) {
if (PlatformDependent.javaVersion() >= 15) {
try {
return SelectorProvider.class.getMethod(methodName, java.net.ProtocolFamily.class);
} catch (Throwable e) {
logger.debug("SelectorProvider.{}(ProtocolFamily) not available, will use default", methodName, e);
}
}
return null;
}
/**
* Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in
* {@link SelectorProvider#provider()} which is called by each SocketChannel.open() otherwise.
* <p>
* See <a href="https://github.com/netty/netty/issues/2308">#2308</a>.
*/
private static <C extends Channel> C newChannel(Method method, SelectorProvider provider,
Object family) throws IOException {
if (family != null && method != null) {
try {
@SuppressWarnings("unchecked")
C channel = (C) method.invoke(provider, family);
return channel;
} catch (InvocationTargetException | IllegalAccessException e) {
throw new IOException(e);
}
}
return null;
}
static <C extends Channel> C newChannel(Method method, SelectorProvider provider,
SocketProtocolFamily family) throws IOException {
if (family != null) {
return newChannel(method, provider, family.toJdkFamily());
}
return null;
}
static <C extends Channel> C newDomainSocketChannel(Method method, SelectorProvider provider) throws IOException {
return newChannel(method, provider, StandardProtocolFamily.valueOf("UNIX"));
}
private SelectorProviderUtil() { }
}
| SelectorProviderUtil |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/io/disk/SeekableFileChannelInputView.java | {
"start": 1765,
"end": 6348
} | class ____ extends AbstractPagedInputView {
private BlockChannelReader<MemorySegment> reader;
private final IOManager ioManager;
private final FileIOChannel.ID channelId;
private final MemoryManager memManager;
private final List<MemorySegment> memory;
private final int sizeOfLastBlock;
private final int numBlocksTotal;
private final int segmentSize;
private int numRequestsRemaining;
private int numBlocksRemaining;
// --------------------------------------------------------------------------------------------
public SeekableFileChannelInputView(
IOManager ioManager,
FileIOChannel.ID channelId,
MemoryManager memManager,
List<MemorySegment> memory,
int sizeOfLastBlock)
throws IOException {
super(0);
checkNotNull(ioManager);
checkNotNull(channelId);
checkNotNull(memManager);
checkNotNull(memory);
this.ioManager = ioManager;
this.channelId = channelId;
this.memManager = memManager;
this.memory = memory;
this.sizeOfLastBlock = sizeOfLastBlock;
this.segmentSize = memManager.getPageSize();
this.reader = ioManager.createBlockChannelReader(channelId);
try {
final long channelLength = reader.getSize();
final int blockCount = MathUtils.checkedDownCast(channelLength / segmentSize);
this.numBlocksTotal = (channelLength % segmentSize == 0) ? blockCount : blockCount + 1;
this.numBlocksRemaining = this.numBlocksTotal;
this.numRequestsRemaining = numBlocksRemaining;
for (int i = 0; i < memory.size(); i++) {
sendReadRequest(memory.get(i));
}
advance();
} catch (IOException e) {
memManager.release(memory);
throw e;
}
}
public void seek(long position) throws IOException {
final int block = MathUtils.checkedDownCast(position / segmentSize);
final int positionInBlock = (int) (position % segmentSize);
if (position < 0
|| block >= numBlocksTotal
|| (block == numBlocksTotal - 1 && positionInBlock > sizeOfLastBlock)) {
throw new IllegalArgumentException("Position is out of range");
}
clear();
if (reader != null) {
reader.close();
}
reader = ioManager.createBlockChannelReader(channelId);
if (block > 0) {
reader.seekToPosition(((long) block) * segmentSize);
}
this.numBlocksRemaining = this.numBlocksTotal - block;
this.numRequestsRemaining = numBlocksRemaining;
for (int i = 0; i < memory.size(); i++) {
sendReadRequest(memory.get(i));
}
numBlocksRemaining--;
seekInput(
reader.getNextReturnedBlock(),
positionInBlock,
numBlocksRemaining == 0 ? sizeOfLastBlock : segmentSize);
}
public void close() throws IOException {
close(false);
}
public void closeAndDelete() throws IOException {
close(true);
}
private void close(boolean deleteFile) throws IOException {
try {
clear();
if (deleteFile) {
reader.closeAndDelete();
} else {
reader.close();
}
} finally {
synchronized (memory) {
memManager.release(memory);
memory.clear();
}
}
}
@Override
protected MemorySegment nextSegment(MemorySegment current) throws IOException {
// check for end-of-stream
if (numBlocksRemaining <= 0) {
reader.close();
throw new EOFException();
}
// send a request first. if we have only a single segment, this same segment will be the one
// obtained in the next lines
if (current != null) {
sendReadRequest(current);
}
// get the next segment
numBlocksRemaining--;
return reader.getNextReturnedBlock();
}
@Override
protected int getLimitForSegment(MemorySegment segment) {
return numBlocksRemaining > 0 ? segment.size() : sizeOfLastBlock;
}
private void sendReadRequest(MemorySegment seg) throws IOException {
if (numRequestsRemaining > 0) {
reader.readBlock(seg);
numRequestsRemaining--;
}
}
}
| SeekableFileChannelInputView |
java | alibaba__fastjson | src/test/java/com/alibaba/json/bvt/bug/Issue1030.java | {
"start": 262,
"end": 669
} | class ____ extends TestCase {
public void test_for_issue() throws Exception {
String DOC = "{\"books\":[{\"pageWords\":[{\"num\":10},{\"num\":15}]},{\"pageWords\":[{\"num\":20}]}]}";
//fastjson包
JSONObject result = JSONObject.parseObject(DOC);
List array = (List) JSONPath.eval(result, "$.books[0:].pageWords[0:]");
assertEquals(3, array.size());
}
}
| Issue1030 |
java | apache__camel | dsl/camel-jbang/camel-jbang-plugin-kubernetes/src/test/java/org/apache/camel/dsl/jbang/core/commands/kubernetes/traits/TraitHelperTest.java | {
"start": 1091,
"end": 4923
} | class ____ {
@Test
public void mergeTraitsTest() {
String[] defaultGroup = new String[] {
"container.port=8080",
"container.port-name=custom",
"container.service-port-name=custom-port",
"container.service-port=8443" };
String[] overridesGroup = new String[] {
"container.port=80",
"container.service-port=443",
"container.image-pull-policy=IfNotPresent" };
String[] result = TraitHelper.mergeTraits(overridesGroup, defaultGroup);
Assertions.assertNotNull(result);
Assertions.assertEquals(5, result.length);
Assertions.assertEquals("container.port=80", result[0]);
Assertions.assertEquals("container.service-port-name=custom-port", result[4]);
String[] resultEmptyDefault = TraitHelper.mergeTraits(overridesGroup, new String[0]);
Assertions.assertNotNull(resultEmptyDefault);
Assertions.assertEquals(3, resultEmptyDefault.length);
Assertions.assertArrayEquals(overridesGroup, resultEmptyDefault);
String[] resultNull = TraitHelper.mergeTraits(null);
Assertions.assertNotNull(resultNull);
}
@Test
public void extractTraitsFromAnnotationsTest() {
String[] annotations = new String[] {
"trait.camel.apache.org/container.port=8080",
"trait.camel.apache.org/container.port-name=custom",
"camel.apache.org/name=MyRoute" };
String[] result = TraitHelper.extractTraitsFromAnnotations(annotations);
Assertions.assertNotNull(result);
Assertions.assertEquals(2, result.length);
Assertions.assertEquals("container.port-name=custom", result[1]);
String[] resultEmpty = TraitHelper.extractTraitsFromAnnotations(new String[0]);
Assertions.assertNotNull(resultEmpty);
String[] resultNull = TraitHelper.extractTraitsFromAnnotations(null);
Assertions.assertNotNull(resultNull);
}
@Test
public void extractTraitsFromPropertiesTest() {
Properties properties = new Properties();
properties.setProperty("camel.jbang.trait.container.port", "8080");
properties.setProperty("camel.jbang.trait.container.port-name", "custom");
properties.setProperty("camel.jbang.trait.environment.FOO", "my value");
properties.setProperty("camel.jbang.name", "MyRoute");
String[] result = TraitHelper.extractTraitsFromProperties(properties);
Assertions.assertNotNull(result);
Assertions.assertEquals(3, result.length);
Assertions.assertTrue(Arrays.asList(result).contains("container.port-name=custom"));
Assertions.assertTrue(Arrays.asList(result).contains("environment.FOO=my value"));
String[] resultEmpty = TraitHelper.extractTraitsFromProperties(new Properties());
Assertions.assertNotNull(resultEmpty);
String[] resultNull = TraitHelper.extractTraitsFromProperties(null);
Assertions.assertNotNull(resultNull);
}
@Test
public void parseTraitsTest() {
String[] traits = new String[] {
"my-prop=my-val",
"custom.property=custom",
"container.port=8080",
"container.port-name=custom" };
Traits traitsSpec = TraitHelper.parseTraits(traits);
Assertions.assertNotNull(traitsSpec);
Assertions.assertEquals(8080L, traitsSpec.getContainer().getPort());
Assertions.assertNotNull(traitsSpec.getAddons().get("custom"));
Traits traitsSpecEmpty = TraitHelper.parseTraits(new String[0]);
Assertions.assertNotNull(traitsSpecEmpty);
Traits traitsSpecNull = TraitHelper.parseTraits(null);
Assertions.assertNotNull(traitsSpecNull);
}
}
| TraitHelperTest |
java | spring-projects__spring-security | acl/src/main/java/org/springframework/security/acls/model/NotFoundException.java | {
"start": 767,
"end": 1256
} | class ____ extends AclDataAccessException {
/**
* Constructs an <code>NotFoundException</code> with the specified message.
* @param msg the detail message
*/
public NotFoundException(String msg) {
super(msg);
}
/**
* Constructs an <code>NotFoundException</code> with the specified message and root
* cause.
* @param msg the detail message
* @param cause root cause
*/
public NotFoundException(String msg, Throwable cause) {
super(msg, cause);
}
}
| NotFoundException |
java | quarkusio__quarkus | extensions/panache/hibernate-orm-panache-common/runtime/src/main/java/io/quarkus/hibernate/orm/panache/common/runtime/AbstractJpaOperations.java | {
"start": 918,
"end": 21742
} | class ____<PanacheQueryType> {
private static final Map<String, String> entityToPersistenceUnit = new HashMap<>();
private static volatile Boolean entityToPersistenceUnitIsIncomplete = null;
// Putting synchronized here because fields involved were marked as volatile initially,
// so I expect recorders can be called concurrently?
public static synchronized void addEntityTypesToPersistenceUnit(Map<String, String> map, boolean incomplete) {
// Note: this may be called multiple times if an app uses both Java and Kotlin.
// We don't really test what happens if entities are defined both in Java and Kotlin at the moment,
// so we mostly care about the case where this gets called once with an empty map, and once with a non-empty map:
// in that case, we don't want the empty map to erase the other one.
entityToPersistenceUnit.putAll(map);
if (entityToPersistenceUnitIsIncomplete == null) {
entityToPersistenceUnitIsIncomplete = incomplete;
} else {
entityToPersistenceUnitIsIncomplete = entityToPersistenceUnitIsIncomplete || incomplete;
}
}
protected abstract PanacheQueryType createPanacheQuery(Session session, String query, String originalQuery, String orderBy,
Object paramsArrayOrMap);
public abstract List<?> list(PanacheQueryType query);
public abstract Stream<?> stream(PanacheQueryType query);
/**
* Returns the {@link EntityManager} for the given {@link Class<?> entity}
*
* @return {@link EntityManager}
*/
public EntityManager getEntityManager(Class<?> clazz) {
return getSession(clazz);
}
/**
* Returns the {@link Session} for the given {@link Class<?> entity}
*
* @return {@link Session}
*/
public Session getSession(Class<?> clazz) {
String clazzName = clazz.getName();
String persistentUnitName = entityToPersistenceUnit.get(clazzName);
if (persistentUnitName == null) {
if (entityToPersistenceUnitIsIncomplete == null || entityToPersistenceUnitIsIncomplete) {
// When using persistence.xml, `entityToPersistenceUnit` is most likely empty,
// so we'll just return the default PU and hope for the best.
// The error will be thrown later by Hibernate ORM if necessary;
// it will be a bit less clear, but this is an edge case.
Session session = getSession(PersistenceUnitUtil.DEFAULT_PERSISTENCE_UNIT_NAME);
if (session != null) {
return session;
}
}
// For Quarkus-configured PUs, or if there is no PU, this is definitely an error.
throw new IllegalStateException(String.format(
"Entity '%s' was not found. Did you forget to annotate your Panache Entity classes with '@Entity'?",
clazzName));
}
return getSession(persistentUnitName);
}
public Session getSession(String persistentUnitName) {
ArcContainer arcContainer = Arc.container();
if (persistentUnitName == null || PersistenceUnitUtil.isDefaultPersistenceUnit(persistentUnitName)) {
return arcContainer.instance(Session.class).get();
} else {
return arcContainer.instance(Session.class,
new PersistenceUnit.PersistenceUnitLiteral(persistentUnitName))
.get();
}
}
public Session getSession() {
return getSession(DEFAULT_PERSISTENCE_UNIT_NAME);
}
//
// Instance methods
public void persist(Object entity) {
Session session = getSession(entity.getClass());
persist(session, entity);
}
public void persist(Session session, Object entity) {
if (!session.contains(entity)) {
session.persist(entity);
}
}
public void persist(Iterable<?> entities) {
for (Object entity : entities) {
persist(getSession(entity.getClass()), entity);
}
}
public void persist(Object firstEntity, Object... entities) {
persist(firstEntity);
for (Object entity : entities) {
persist(entity);
}
}
public void persist(Stream<?> entities) {
entities.forEach(entity -> persist(entity));
}
public void delete(Object entity) {
Session session = getSession(entity.getClass());
session.remove(session.contains(entity) ? entity : session.getReference(entity));
}
public boolean isPersistent(Object entity) {
return getSession(entity.getClass()).contains(entity);
}
public void flush() {
getSession().flush();
}
public void flush(Object entity) {
getSession(entity.getClass()).flush();
}
public void flush(Class<?> clazz) {
getSession(clazz).flush();
}
//
// Private stuff
public static TransactionManager getTransactionManager() {
return Arc.container().instance(TransactionManager.class).get();
}
public static <T extends CommonQueryContract> T bindParameters(T query, Object[] params) {
if (params == null || params.length == 0)
return query;
for (int i = 0; i < params.length; i++) {
query.setParameter(i + 1, params[i]);
}
return query;
}
public static <T extends CommonQueryContract> T bindParameters(T query, Map<String, Object> params) {
if (params == null || params.isEmpty())
return query;
for (Entry<String, Object> entry : params.entrySet()) {
query.setParameter(entry.getKey(), entry.getValue());
}
return query;
}
public int paramCount(Object[] params) {
return params != null ? params.length : 0;
}
public int paramCount(Map<String, Object> params) {
return params != null ? params.size() : 0;
}
//
// Queries
public Object findById(Class<?> entityClass, Object id) {
return getSession(entityClass).find(entityClass, id);
}
public Object findById(Class<?> entityClass, Object id, LockModeType lockModeType) {
return getSession(entityClass).find(entityClass, id, lockModeType);
}
public Optional<?> findByIdOptional(Class<?> entityClass, Object id) {
return Optional.ofNullable(findById(entityClass, id));
}
public Optional<?> findByIdOptional(Class<?> entityClass, Object id, LockModeType lockModeType) {
return Optional.ofNullable(findById(entityClass, id, lockModeType));
}
public List<?> findByIds(Class<?> entityClass, List<?> ids) {
return getSession(entityClass).findMultiple(entityClass, ids);
}
public PanacheQueryType find(Class<?> entityClass, String query, Object... params) {
return find(entityClass, query, null, params);
}
public PanacheQueryType find(Class<?> entityClass, String panacheQuery, Sort sort, Object... params) {
Session session = getSession(entityClass);
if (PanacheJpaUtil.isNamedQuery(panacheQuery)) {
String namedQuery = panacheQuery.substring(1);
if (sort != null) {
throw new IllegalArgumentException(
"Sort cannot be used with named query, add an \"order by\" clause to the named query \"" + namedQuery
+ "\" instead");
}
NamedQueryUtil.checkNamedQuery(entityClass, namedQuery);
return createPanacheQuery(session, panacheQuery, panacheQuery, null, params);
}
String translatedHqlQuery = PanacheJpaUtil.createFindQuery(entityClass, panacheQuery, paramCount(params));
return createPanacheQuery(session, translatedHqlQuery, panacheQuery, PanacheJpaUtil.toOrderBy(sort), params);
}
public PanacheQueryType find(Class<?> entityClass, String panacheQuery, Map<String, Object> params) {
return find(entityClass, panacheQuery, null, params);
}
public PanacheQueryType find(Class<?> entityClass, String panacheQuery, Sort sort, Map<String, Object> params) {
Session session = getSession(entityClass);
if (PanacheJpaUtil.isNamedQuery(panacheQuery)) {
String namedQuery = panacheQuery.substring(1);
if (sort != null) {
throw new IllegalArgumentException(
"Sort cannot be used with named query, add an \"order by\" clause to the named query \"" + namedQuery
+ "\" instead");
}
NamedQueryUtil.checkNamedQuery(entityClass, namedQuery);
return createPanacheQuery(session, panacheQuery, panacheQuery, null, params);
}
String translatedHqlQuery = PanacheJpaUtil.createFindQuery(entityClass, panacheQuery, paramCount(params));
return createPanacheQuery(session, translatedHqlQuery, panacheQuery, PanacheJpaUtil.toOrderBy(sort), params);
}
public PanacheQueryType find(Class<?> entityClass, String panacheQuery, Parameters params) {
return find(entityClass, panacheQuery, null, params);
}
public PanacheQueryType find(Class<?> entityClass, String panacheQuery, Sort sort, Parameters params) {
return find(entityClass, panacheQuery, sort, params.map());
}
public List<?> list(Class<?> entityClass, String panacheQuery, Object... params) {
return list(find(entityClass, panacheQuery, params));
}
public List<?> list(Class<?> entityClass, String panacheQuery, Sort sort, Object... params) {
return list(find(entityClass, panacheQuery, sort, params));
}
public List<?> list(Class<?> entityClass, String panacheQuery, Map<String, Object> params) {
return list(find(entityClass, panacheQuery, params));
}
public List<?> list(Class<?> entityClass, String panacheQuery, Sort sort, Map<String, Object> params) {
return list(find(entityClass, panacheQuery, sort, params));
}
public List<?> list(Class<?> entityClass, String panacheQuery, Parameters params) {
return list(find(entityClass, panacheQuery, params));
}
public List<?> list(Class<?> entityClass, String panacheQuery, Sort sort, Parameters params) {
return list(find(entityClass, panacheQuery, sort, params));
}
public Stream<?> stream(Class<?> entityClass, String panacheQuery, Object... params) {
return stream(find(entityClass, panacheQuery, params));
}
public Stream<?> stream(Class<?> entityClass, String panacheQuery, Sort sort, Object... params) {
return stream(find(entityClass, panacheQuery, sort, params));
}
public Stream<?> stream(Class<?> entityClass, String panacheQuery, Map<String, Object> params) {
return stream(find(entityClass, panacheQuery, params));
}
public Stream<?> stream(Class<?> entityClass, String panacheQuery, Sort sort, Map<String, Object> params) {
return stream(find(entityClass, panacheQuery, sort, params));
}
public Stream<?> stream(Class<?> entityClass, String panacheQuery, Parameters params) {
return stream(find(entityClass, panacheQuery, params));
}
public Stream<?> stream(Class<?> entityClass, String panacheQuery, Sort sort, Parameters params) {
return stream(find(entityClass, panacheQuery, sort, params));
}
public PanacheQueryType findAll(Class<?> entityClass) {
String query = "FROM " + PanacheJpaUtil.getEntityName(entityClass);
Session session = getSession(entityClass);
return createPanacheQuery(session, query, null, null, null);
}
public PanacheQueryType findAll(Class<?> entityClass, Sort sort) {
String query = "FROM " + PanacheJpaUtil.getEntityName(entityClass);
Session session = getSession(entityClass);
return createPanacheQuery(session, query, null, PanacheJpaUtil.toOrderBy(sort), null);
}
public List<?> listAll(Class<?> entityClass) {
return list(findAll(entityClass));
}
public List<?> listAll(Class<?> entityClass, Sort sort) {
return list(findAll(entityClass, sort));
}
public Stream<?> streamAll(Class<?> entityClass) {
return stream(findAll(entityClass));
}
public Stream<?> streamAll(Class<?> entityClass, Sort sort) {
return stream(findAll(entityClass, sort));
}
public long count(Class<?> entityClass) {
return getSession(entityClass)
.createSelectionQuery("FROM " + PanacheJpaUtil.getEntityName(entityClass), entityClass)
.getResultCount();
}
public long count(Class<?> entityClass, String panacheQuery, Object... params) {
if (PanacheJpaUtil.isNamedQuery(panacheQuery)) {
SelectionQuery<?> namedQuery = extractNamedSelectionQuery(entityClass, panacheQuery);
return (long) bindParameters(namedQuery, params).getSingleResult();
}
try {
String query = PanacheJpaUtil.createQueryForCount(entityClass, panacheQuery, paramCount(params));
return bindParameters(getSession(entityClass).createSelectionQuery(query, Object.class), params).getResultCount();
} catch (RuntimeException x) {
throw NamedQueryUtil.checkForNamedQueryMistake(x, panacheQuery);
}
}
public long count(Class<?> entityClass, String panacheQuery, Map<String, Object> params) {
if (PanacheJpaUtil.isNamedQuery(panacheQuery)) {
SelectionQuery<?> namedQuery = extractNamedSelectionQuery(entityClass, panacheQuery);
return (long) bindParameters(namedQuery, params).getSingleResult();
}
try {
String query = PanacheJpaUtil.createQueryForCount(entityClass, panacheQuery, paramCount(params));
return bindParameters(getSession(entityClass).createSelectionQuery(query, Object.class), params).getResultCount();
} catch (RuntimeException x) {
throw NamedQueryUtil.checkForNamedQueryMistake(x, panacheQuery);
}
}
public long count(Class<?> entityClass, String query, Parameters params) {
return count(entityClass, query, params.map());
}
private SelectionQuery<?> extractNamedSelectionQuery(Class<?> entityClass, String query) {
String namedQueryName = extractNamedQueryName(entityClass, query);
return getSession(entityClass).createNamedSelectionQuery(namedQueryName);
}
private MutationQuery extractNamedMutationQuery(Class<?> entityClass, String query) {
String namedQueryName = extractNamedQueryName(entityClass, query);
return getSession(entityClass).createNamedMutationQuery(namedQueryName);
}
private String extractNamedQueryName(Class<?> entityClass, String query) {
if (!PanacheJpaUtil.isNamedQuery(query))
throw new IllegalArgumentException("Must be a named query!");
String namedQueryName = query.substring(1);
NamedQueryUtil.checkNamedQuery(entityClass, namedQueryName);
return namedQueryName;
}
public boolean exists(Class<?> entityClass) {
return count(entityClass) > 0;
}
public boolean exists(Class<?> entityClass, String query, Object... params) {
return count(entityClass, query, params) > 0;
}
public boolean exists(Class<?> entityClass, String query, Map<String, Object> params) {
return count(entityClass, query, params) > 0;
}
public boolean exists(Class<?> entityClass, String query, Parameters params) {
return count(entityClass, query, params) > 0;
}
public long deleteAll(Class<?> entityClass) {
return getSession(entityClass).createMutationQuery("DELETE FROM " + PanacheJpaUtil.getEntityName(entityClass))
.executeUpdate();
}
public boolean deleteById(Class<?> entityClass, Object id) {
// Impl note : we load the entity then delete it because it's the only implementation generic enough for any model,
// and correct in all cases (composite key, graph of entities, ...). HQL cannot be directly used for these reasons.
Object entity = findById(entityClass, id);
if (entity == null) {
return false;
}
getSession(entityClass).remove(entity);
return true;
}
public long delete(Class<?> entityClass, String panacheQuery, Object... params) {
if (PanacheJpaUtil.isNamedQuery(panacheQuery)) {
return bindParameters(extractNamedMutationQuery(entityClass, panacheQuery), params).executeUpdate();
}
try {
return bindParameters(
getSession(entityClass).createMutationQuery(
PanacheJpaUtil.createDeleteQuery(entityClass, panacheQuery, paramCount(params))),
params)
.executeUpdate();
} catch (RuntimeException x) {
throw NamedQueryUtil.checkForNamedQueryMistake(x, panacheQuery);
}
}
public long delete(Class<?> entityClass, String panacheQuery, Map<String, Object> params) {
if (PanacheJpaUtil.isNamedQuery(panacheQuery)) {
return bindParameters(extractNamedMutationQuery(entityClass, panacheQuery), params).executeUpdate();
}
try {
return bindParameters(
getSession(entityClass)
.createMutationQuery(
PanacheJpaUtil.createDeleteQuery(entityClass, panacheQuery, paramCount(params))),
params)
.executeUpdate();
} catch (RuntimeException x) {
throw NamedQueryUtil.checkForNamedQueryMistake(x, panacheQuery);
}
}
public long delete(Class<?> entityClass, String query, Parameters params) {
return delete(entityClass, query, params.map());
}
public static IllegalStateException implementationInjectionMissing() {
return new IllegalStateException(
"This method is normally automatically overridden in subclasses: did you forget to annotate your entity with @Entity?");
}
/**
* Execute update on default persistence unit
*/
public int executeUpdate(String query, Object... params) {
return bindParameters(getSession(DEFAULT_PERSISTENCE_UNIT_NAME).createMutationQuery(query), params)
.executeUpdate();
}
/**
* Execute update on default persistence unit
*/
public int executeUpdate(String query, Map<String, Object> params) {
return bindParameters(getSession(DEFAULT_PERSISTENCE_UNIT_NAME).createMutationQuery(query), params)
.executeUpdate();
}
public int executeUpdate(Class<?> entityClass, String panacheQuery, Object... params) {
if (PanacheJpaUtil.isNamedQuery(panacheQuery)) {
return bindParameters(extractNamedMutationQuery(entityClass, panacheQuery), params).executeUpdate();
}
try {
String updateQuery = PanacheJpaUtil.createUpdateQuery(entityClass, panacheQuery, paramCount(params));
return bindParameters(getSession(entityClass).createMutationQuery(updateQuery), params)
.executeUpdate();
} catch (RuntimeException x) {
throw NamedQueryUtil.checkForNamedQueryMistake(x, panacheQuery);
}
}
public int executeUpdate(Class<?> entityClass, String panacheQuery, Map<String, Object> params) {
if (PanacheJpaUtil.isNamedQuery(panacheQuery)) {
return bindParameters(extractNamedMutationQuery(entityClass, panacheQuery), params).executeUpdate();
}
try {
String updateQuery = PanacheJpaUtil.createUpdateQuery(entityClass, panacheQuery, paramCount(params));
return bindParameters(getSession(entityClass).createMutationQuery(updateQuery), params)
.executeUpdate();
} catch (RuntimeException x) {
throw NamedQueryUtil.checkForNamedQueryMistake(x, panacheQuery);
}
}
public int update(Class<?> entityClass, String query, Map<String, Object> params) {
return executeUpdate(entityClass, query, params);
}
public int update(Class<?> entityClass, String query, Parameters params) {
return update(entityClass, query, params.map());
}
public int update(Class<?> entityClass, String query, Object... params) {
return executeUpdate(entityClass, query, params);
}
public static void setRollbackOnly() {
try {
getTransactionManager().setRollbackOnly();
} catch (SystemException e) {
throw new IllegalStateException(e);
}
}
}
| AbstractJpaOperations |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/impl/verifier/DefaultComponentVerifierTest.java | {
"start": 3653,
"end": 3803
} | class ____ extends DefaultComponentVerifierExtension {
public TestVerifier() {
super("timer", context);
}
}
}
| TestVerifier |
java | apache__flink | flink-table/flink-table-code-splitter/src/test/resources/declaration/code/TestNotRewriteLocalVariableInFunctionWithReturnValue.java | {
"start": 7,
"end": 205
} | class ____ {
public int myFun() {
int local1;
String local2 = "local2";
final long local3;
local3 = 100L;
}
}
| TestNotRewriteLocalVariableInFunctionWithReturnValue |
java | apache__camel | components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/aggregator/SpringAggregateCompletionIntervalTest.java | {
"start": 1074,
"end": 1404
} | class ____ extends AggregateCompletionIntervalTest {
@Override
protected CamelContext createCamelContext() throws Exception {
return createSpringCamelContext(this,
"org/apache/camel/spring/processor/aggregator/SpringAggregateCompletionIntervalTest.xml");
}
}
| SpringAggregateCompletionIntervalTest |
java | apache__flink | flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/MessageHeaders.java | {
"start": 1716,
"end": 1769
} | class ____ the response message.
*
* @return | of |
java | ReactiveX__RxJava | src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableRefCountTest.java | {
"start": 31382,
"end": 32810
} | class ____ extends ConnectableFlowable<Object> {
int count;
@Override
public void connect(Consumer<? super Disposable> connection) {
try {
connection.accept(Disposable.empty());
} catch (Throwable ex) {
throw ExceptionHelper.wrapOrThrow(ex);
}
}
@Override
public void reset() {
// nothing to do in this test
}
@Override
protected void subscribeActual(Subscriber<? super Object> subscriber) {
if (++count == 1) {
subscriber.onSubscribe(new BooleanSubscription());
} else {
throw new TestException("subscribeActual");
}
}
}
@Test
public void badSourceSubscribe2() {
List<Throwable> errors = TestHelper.trackPluginErrors();
try {
BadFlowableSubscribe2 bf = new BadFlowableSubscribe2();
Flowable<Object> f = bf.refCount();
f.test();
try {
f.test();
fail("Should have thrown");
} catch (NullPointerException ex) {
assertTrue(ex.getCause() instanceof TestException);
}
TestHelper.assertUndeliverable(errors, 0, TestException.class);
} finally {
RxJavaPlugins.reset();
}
}
static final | BadFlowableSubscribe2 |
java | spring-projects__spring-security | kerberos/kerberos-test/src/test/java/org/springframework/security/kerberos/test/TestMiniKdc.java | {
"start": 1338,
"end": 4797
} | class ____ extends KerberosSecurityTestcase {
private static final boolean IBM_JAVA = shouldUseIbmPackages();
// duplicated to avoid cycles in the build
private static boolean shouldUseIbmPackages() {
final List<String> ibmTechnologyEditionSecurityModules = Arrays.asList(
"com.ibm.security.auth.module.JAASLoginModule", "com.ibm.security.auth.module.Win64LoginModule",
"com.ibm.security.auth.module.NTLoginModule", "com.ibm.security.auth.module.AIX64LoginModule",
"com.ibm.security.auth.module.LinuxLoginModule", "com.ibm.security.auth.module.Krb5LoginModule");
if (System.getProperty("java.vendor").contains("IBM")) {
return ibmTechnologyEditionSecurityModules.stream().anyMatch((module) -> isSystemClassAvailable(module));
}
return false;
}
@Test
public void testKerberosLogin() throws Exception {
MiniKdc kdc = getKdc();
File workDir = getWorkDir();
LoginContext loginContext = null;
try {
String principal = "foo";
File keytab = new File(workDir, "foo.keytab");
kdc.createPrincipal(keytab, principal);
Set<Principal> principals = new HashSet<Principal>();
principals.add(new KerberosPrincipal(principal));
// client login
Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
loginContext = new LoginContext("", subject, null,
KerberosConfiguration.createClientConfig(principal, keytab));
loginContext.login();
subject = loginContext.getSubject();
assertThat(subject.getPrincipals().size()).isEqualTo(1);
assertThat(subject.getPrincipals().iterator().next().getClass()).isEqualTo(KerberosPrincipal.class);
assertThat(subject.getPrincipals().iterator().next().getName()).isEqualTo(principal + "@" + kdc.getRealm());
loginContext.logout();
// server login
subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
loginContext = new LoginContext("", subject, null,
KerberosConfiguration.createServerConfig(principal, keytab));
loginContext.login();
subject = loginContext.getSubject();
assertThat(subject.getPrincipals().size()).isEqualTo(1);
assertThat(subject.getPrincipals().iterator().next().getClass()).isEqualTo(KerberosPrincipal.class);
assertThat(subject.getPrincipals().iterator().next().getName()).isEqualTo(principal + "@" + kdc.getRealm());
loginContext.logout();
}
finally {
if (loginContext != null && loginContext.getSubject() != null
&& !loginContext.getSubject().getPrivateCredentials().isEmpty()) {
loginContext.logout();
}
}
}
private static boolean isSystemClassAvailable(String className) {
try {
Class.forName(className);
return true;
}
catch (Exception ignored) {
return false;
}
}
@Test
public void testMiniKdcStart() {
MiniKdc kdc = getKdc();
assertThat(kdc.getPort()).isNotEqualTo(0);
}
@Test
public void testKeytabGen() throws Exception {
MiniKdc kdc = getKdc();
File workDir = getWorkDir();
kdc.createPrincipal(new File(workDir, "keytab"), "foo/bar", "bar/foo");
List<PrincipalName> principalNameList = Keytab.loadKeytab(new File(workDir, "keytab")).getPrincipals();
Set<String> principals = new HashSet<String>();
for (PrincipalName principalName : principalNameList) {
principals.add(principalName.getName());
}
assertThat(principals).containsExactlyInAnyOrder("foo/bar@" + kdc.getRealm(), "bar/foo@" + kdc.getRealm());
}
private static final | TestMiniKdc |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/VertxEndpointBuilderFactory.java | {
"start": 12761,
"end": 14174
} | interface ____
extends
VertxEndpointConsumerBuilder,
VertxEndpointProducerBuilder {
default AdvancedVertxEndpointBuilder advanced() {
return (AdvancedVertxEndpointBuilder) this;
}
/**
* Whether to use publish/subscribe instead of point to point when
* sending to a vertx endpoint.
*
* The option is a: <code>java.lang.Boolean</code> type.
*
* Default: false
* Group: common
*
* @param pubSub the value to set
* @return the dsl builder
*/
default VertxEndpointBuilder pubSub(Boolean pubSub) {
doSetProperty("pubSub", pubSub);
return this;
}
/**
* Whether to use publish/subscribe instead of point to point when
* sending to a vertx endpoint.
*
* The option will be converted to a <code>java.lang.Boolean</code>
* type.
*
* Default: false
* Group: common
*
* @param pubSub the value to set
* @return the dsl builder
*/
default VertxEndpointBuilder pubSub(String pubSub) {
doSetProperty("pubSub", pubSub);
return this;
}
}
/**
* Advanced builder for endpoint for the Vert.x component.
*/
public | VertxEndpointBuilder |
java | elastic__elasticsearch | x-pack/plugin/migrate/src/main/java/org/elasticsearch/xpack/migrate/action/GetMigrationReindexStatusAction.java | {
"start": 1062,
"end": 1444
} | class ____ extends ActionType<GetMigrationReindexStatusAction.Response> {
public static final GetMigrationReindexStatusAction INSTANCE = new GetMigrationReindexStatusAction();
public static final String NAME = "indices:admin/migration/reindex_status";
public GetMigrationReindexStatusAction() {
super(NAME);
}
public static | GetMigrationReindexStatusAction |
java | apache__hadoop | hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/MockJobs.java | {
"start": 3460,
"end": 14803
} | class ____ extends MockApps {
static final Iterator<JobState> JOB_STATES = Iterators.cycle(JobState
.values());
static final Iterator<TaskState> TASK_STATES = Iterators.cycle(TaskState
.values());
static final Iterator<TaskAttemptState> TASK_ATTEMPT_STATES = Iterators
.cycle(TaskAttemptState.values());
static final Iterator<TaskType> TASK_TYPES = Iterators.cycle(TaskType
.values());
static final Iterator<JobCounter> JOB_COUNTERS = Iterators.cycle(JobCounter
.values());
static final Iterator<FileSystemCounter> FS_COUNTERS = Iterators
.cycle(FileSystemCounter.values());
static final Iterator<TaskCounter> TASK_COUNTERS = Iterators
.cycle(TaskCounter.values());
static final Iterator<String> FS_SCHEMES = Iterators.cycle("FILE", "HDFS",
"LAFS", "CEPH");
static final Iterator<String> USER_COUNTER_GROUPS = Iterators
.cycle(
"com.company.project.subproject.component.subcomponent.UserDefinedSpecificSpecialTask$Counters",
"PigCounters");
static final Iterator<String> USER_COUNTERS = Iterators.cycle("counter1",
"counter2", "counter3");
static final Iterator<Phase> PHASES = Iterators.cycle(Phase.values());
static final Iterator<String> DIAGS = Iterators.cycle(
"Error: java.lang.OutOfMemoryError: Java heap space",
"Lost task tracker: tasktracker.domain/127.0.0.1:40879");
public static final String NM_HOST = "localhost";
public static final int NM_PORT = 1234;
public static final int NM_HTTP_PORT = 8042;
static final int DT = 1000000; // ms
public static String newJobName() {
return newAppName();
}
/**
* Create numJobs in a map with jobs having appId==jobId
*/
public static Map<JobId, Job> newJobs(int numJobs, int numTasksPerJob,
int numAttemptsPerTask) {
Map<JobId, Job> map = Maps.newHashMap();
for (int j = 0; j < numJobs; ++j) {
ApplicationId appID = MockJobs.newAppID(j);
Job job = newJob(appID, j, numTasksPerJob, numAttemptsPerTask);
map.put(job.getID(), job);
}
return map;
}
public static Map<JobId, Job> newJobs(ApplicationId appID, int numJobsPerApp,
int numTasksPerJob, int numAttemptsPerTask) {
Map<JobId, Job> map = Maps.newHashMap();
for (int j = 0; j < numJobsPerApp; ++j) {
Job job = newJob(appID, j, numTasksPerJob, numAttemptsPerTask);
map.put(job.getID(), job);
}
return map;
}
public static Map<JobId, Job> newJobs(ApplicationId appID, int numJobsPerApp,
int numTasksPerJob, int numAttemptsPerTask, boolean hasFailedTasks) {
Map<JobId, Job> map = Maps.newHashMap();
for (int j = 0; j < numJobsPerApp; ++j) {
Job job = newJob(appID, j, numTasksPerJob, numAttemptsPerTask, null,
hasFailedTasks);
map.put(job.getID(), job);
}
return map;
}
public static JobId newJobID(ApplicationId appID, int i) {
JobId id = Records.newRecord(JobId.class);
id.setAppId(appID);
id.setId(i);
return id;
}
public static JobReport newJobReport(JobId id) {
JobReport report = Records.newRecord(JobReport.class);
report.setJobId(id);
report.setSubmitTime(System.currentTimeMillis()-DT);
report
.setStartTime(System.currentTimeMillis() - (int) (Math.random() * DT));
report.setFinishTime(System.currentTimeMillis()
+ (int) (Math.random() * DT) + 1);
report.setMapProgress((float) Math.random());
report.setReduceProgress((float) Math.random());
report.setJobState(JOB_STATES.next());
return report;
}
public static TaskReport newTaskReport(TaskId id) {
TaskReport report = Records.newRecord(TaskReport.class);
report.setTaskId(id);
report
.setStartTime(System.currentTimeMillis() - (int) (Math.random() * DT));
report.setFinishTime(System.currentTimeMillis()
+ (int) (Math.random() * DT) + 1);
report.setProgress((float) Math.random());
report.setStatus("Moving average: " + Math.random());
report.setCounters(TypeConverter.toYarn(newCounters()));
report.setTaskState(TASK_STATES.next());
return report;
}
public static TaskAttemptReport newTaskAttemptReport(TaskAttemptId id) {
ApplicationAttemptId appAttemptId = ApplicationAttemptId.newInstance(
id.getTaskId().getJobId().getAppId(), 0);
ContainerId containerId = ContainerId.newContainerId(appAttemptId, 0);
TaskAttemptReport report = Records.newRecord(TaskAttemptReport.class);
report.setTaskAttemptId(id);
report
.setStartTime(System.currentTimeMillis() - (int) (Math.random() * DT));
report.setFinishTime(System.currentTimeMillis()
+ (int) (Math.random() * DT) + 1);
if (id.getTaskId().getTaskType() == TaskType.REDUCE) {
report.setShuffleFinishTime(
(report.getFinishTime() + report.getStartTime()) / 2);
report.setSortFinishTime(
(report.getFinishTime() + report.getShuffleFinishTime()) / 2);
}
report.setPhase(PHASES.next());
report.setTaskAttemptState(TASK_ATTEMPT_STATES.next());
report.setProgress((float) Math.random());
report.setCounters(TypeConverter.toYarn(newCounters()));
report.setContainerId(containerId);
report.setDiagnosticInfo(DIAGS.next());
report.setStateString("Moving average " + Math.random());
return report;
}
public static Counters newCounters() {
Counters hc = new Counters();
for (JobCounter c : JobCounter.values()) {
hc.findCounter(c).setValue((long) (Math.random() * 1000));
}
for (TaskCounter c : TaskCounter.values()) {
hc.findCounter(c).setValue((long) (Math.random() * 1000));
}
int nc = FileSystemCounter.values().length * 4;
for (int i = 0; i < nc; ++i) {
for (FileSystemCounter c : FileSystemCounter.values()) {
hc.findCounter(FS_SCHEMES.next(), c).setValue(
(long) (Math.random() * DT));
}
}
for (int i = 0; i < 2 * 3; ++i) {
hc.findCounter(USER_COUNTER_GROUPS.next(), USER_COUNTERS.next())
.setValue((long) (Math.random() * 100000));
}
return hc;
}
public static Map<TaskAttemptId, TaskAttempt> newTaskAttempts(TaskId tid,
int m) {
Map<TaskAttemptId, TaskAttempt> map = Maps.newHashMap();
for (int i = 0; i < m; ++i) {
TaskAttempt ta = newTaskAttempt(tid, i);
map.put(ta.getID(), ta);
}
return map;
}
public static TaskAttempt newTaskAttempt(TaskId tid, int i) {
final TaskAttemptId taid = Records.newRecord(TaskAttemptId.class);
taid.setTaskId(tid);
taid.setId(i);
final TaskAttemptReport report = newTaskAttemptReport(taid);
return new TaskAttempt() {
@Override
public NodeId getNodeId() throws UnsupportedOperationException{
throw new UnsupportedOperationException();
}
@Override
public TaskAttemptId getID() {
return taid;
}
@Override
public TaskAttemptReport getReport() {
return report;
}
@Override
public long getLaunchTime() {
return report.getStartTime();
}
@Override
public long getFinishTime() {
return report.getFinishTime();
}
@Override
public int getShufflePort() {
return ShuffleHandler.DEFAULT_SHUFFLE_PORT;
}
@Override
public Counters getCounters() {
if (report != null && report.getCounters() != null) {
return new Counters(TypeConverter.fromYarn(report.getCounters()));
}
return null;
}
@Override
public float getProgress() {
return report.getProgress();
}
@Override
public Phase getPhase() {
return report.getPhase();
}
@Override
public TaskAttemptState getState() {
return report.getTaskAttemptState();
}
@Override
public boolean isFinished() {
switch (report.getTaskAttemptState()) {
case SUCCEEDED:
case FAILED:
case KILLED:
return true;
}
return false;
}
@Override
public ContainerId getAssignedContainerID() {
ApplicationAttemptId appAttemptId =
ApplicationAttemptId.newInstance(taid.getTaskId().getJobId()
.getAppId(), 0);
ContainerId id = ContainerId.newContainerId(appAttemptId, 0);
return id;
}
@Override
public String getNodeHttpAddress() {
return "localhost:8042";
}
@Override
public List<String> getDiagnostics() {
return Lists.newArrayList(report.getDiagnosticInfo());
}
@Override
public String getAssignedContainerMgrAddress() {
return "localhost:9998";
}
@Override
public long getShuffleFinishTime() {
return report.getShuffleFinishTime();
}
@Override
public long getSortFinishTime() {
return report.getSortFinishTime();
}
@Override
public String getNodeRackName() {
return "/default-rack";
}
};
}
public static Map<TaskId, Task> newTasks(JobId jid, int n, int m, boolean hasFailedTasks) {
Map<TaskId, Task> map = Maps.newHashMap();
for (int i = 0; i < n; ++i) {
Task task = newTask(jid, i, m, hasFailedTasks);
map.put(task.getID(), task);
}
return map;
}
public static Task newTask(JobId jid, int i, int m, final boolean hasFailedTasks) {
final TaskId tid = Records.newRecord(TaskId.class);
tid.setJobId(jid);
tid.setId(i);
tid.setTaskType(TASK_TYPES.next());
final TaskReport report = newTaskReport(tid);
final Map<TaskAttemptId, TaskAttempt> attempts = newTaskAttempts(tid, m);
return new Task() {
@Override
public TaskId getID() {
return tid;
}
@Override
public TaskReport getReport() {
return report;
}
@Override
public Counters getCounters() {
if (hasFailedTasks) {
return null;
}
return new Counters(
TypeConverter.fromYarn(report.getCounters()));
}
@Override
public float getProgress() {
return report.getProgress();
}
@Override
public TaskType getType() {
return tid.getTaskType();
}
@Override
public Map<TaskAttemptId, TaskAttempt> getAttempts() {
return attempts;
}
@Override
public TaskAttempt getAttempt(TaskAttemptId attemptID) {
return attempts.get(attemptID);
}
@Override
public boolean isFinished() {
switch (report.getTaskState()) {
case SUCCEEDED:
case KILLED:
case FAILED:
return true;
}
return false;
}
@Override
public boolean canCommit(TaskAttemptId taskAttemptID) {
return false;
}
@Override
public TaskState getState() {
return report.getTaskState();
}
};
}
public static Counters getCounters(
Collection<Task> tasks) {
List<Task> completedTasks = new ArrayList<Task>();
for (Task task : tasks) {
if (task.getCounters() != null) {
completedTasks.add(task);
}
}
Counters counters = new Counters();
return JobImpl.incrTaskCounters(counters, completedTasks);
}
static | MockJobs |
java | spring-projects__spring-boot | module/spring-boot-micrometer-tracing/src/test/java/org/springframework/boot/micrometer/tracing/autoconfigure/TracingAndMeterObservationHandlerGroupTests.java | {
"start": 1744,
"end": 5716
} | class ____ {
@Test
void compareToSortsBeforeMeterObservationHandlerGroup() {
ObservationHandlerGroup meterGroup = ObservationHandlerGroup.of(MeterObservationHandler.class);
TracingAndMeterObservationHandlerGroup tracingAndMeterGroup = new TracingAndMeterObservationHandlerGroup(
mock(Tracer.class));
assertThat(sort(meterGroup, tracingAndMeterGroup)).containsExactly(tracingAndMeterGroup, meterGroup);
assertThat(sort(tracingAndMeterGroup, meterGroup)).containsExactly(tracingAndMeterGroup, meterGroup);
}
@Test
void isMemberAcceptsMeterObservationHandlerOrTracingObservationHandler() {
TracingAndMeterObservationHandlerGroup group = new TracingAndMeterObservationHandlerGroup(mock(Tracer.class));
assertThat(group.isMember(mock(ObservationHandler.class))).isFalse();
assertThat(group.isMember(mock(MeterObservationHandler.class))).isTrue();
assertThat(group.isMember(mock(TracingObservationHandler.class))).isTrue();
}
@Test
void registerMembersWrapsMeterObservationHandlersAndRegistersDistinctGroups() {
Tracer tracer = mock(Tracer.class);
TracingAndMeterObservationHandlerGroup group = new TracingAndMeterObservationHandlerGroup(tracer);
TracingObservationHandler<?> tracingHandler1 = mock(TracingObservationHandler.class);
TracingObservationHandler<?> tracingHandler2 = mock(TracingObservationHandler.class);
MeterObservationHandler<?> meterHandler1 = mock(MeterObservationHandler.class);
MeterObservationHandler<?> meterHandler2 = mock(MeterObservationHandler.class);
ObservationConfig config = mock(ObservationConfig.class);
List<ObservationHandler<?>> members = List.of(tracingHandler1, meterHandler1, tracingHandler2, meterHandler2);
group.registerMembers(config, members);
ArgumentCaptor<ObservationHandler<?>> handlerCaptor = ArgumentCaptor.captor();
then(config).should(times(2)).observationHandler(handlerCaptor.capture());
List<ObservationHandler<?>> actualComposites = handlerCaptor.getAllValues();
assertThat(actualComposites).hasSize(2);
ObservationHandler<?> tracingComposite = actualComposites.get(0);
assertThat(tracingComposite).isInstanceOf(FirstMatchingCompositeObservationHandler.class)
.extracting("handlers", InstanceOfAssertFactories.LIST)
.containsExactly(tracingHandler1, tracingHandler2);
ObservationHandler<?> metricsComposite = actualComposites.get(1);
assertThat(metricsComposite).isInstanceOf(FirstMatchingCompositeObservationHandler.class)
.extracting("handlers", InstanceOfAssertFactories.LIST)
.extracting("delegate")
.containsExactly(meterHandler1, meterHandler2);
}
@Test
void registerMembersOnlyUsesCompositeWhenMoreThanOneHandler() {
Tracer tracer = mock(Tracer.class);
TracingAndMeterObservationHandlerGroup group = new TracingAndMeterObservationHandlerGroup(tracer);
TracingObservationHandler<?> tracingHandler1 = mock(TracingObservationHandler.class);
TracingObservationHandler<?> tracingHandler2 = mock(TracingObservationHandler.class);
MeterObservationHandler<?> meterHandler = mock(MeterObservationHandler.class);
ObservationConfig config = mock(ObservationConfig.class);
List<ObservationHandler<?>> members = List.of(tracingHandler1, meterHandler, tracingHandler2);
group.registerMembers(config, members);
ArgumentCaptor<ObservationHandler<?>> handlerCaptor = ArgumentCaptor.captor();
then(config).should(times(2)).observationHandler(handlerCaptor.capture());
List<ObservationHandler<?>> actualComposites = handlerCaptor.getAllValues();
assertThat(actualComposites).hasSize(2);
assertThat(actualComposites.get(0)).isInstanceOf(FirstMatchingCompositeObservationHandler.class);
assertThat(actualComposites.get(1)).isInstanceOf(TracingAwareMeterObservationHandler.class);
}
private List<ObservationHandlerGroup> sort(ObservationHandlerGroup... groups) {
List<ObservationHandlerGroup> list = new ArrayList<>(List.of(groups));
Collections.sort(list);
return list;
}
}
| TracingAndMeterObservationHandlerGroupTests |
java | apache__dubbo | dubbo-spring-boot-project/dubbo-spring-boot-autoconfigure/src/test/java/org/apache/dubbo/spring/boot/env/DubboDefaultPropertiesEnvironmentPostProcessorTest.java | {
"start": 1415,
"end": 4995
} | class ____ {
private DubboDefaultPropertiesEnvironmentPostProcessor instance =
new DubboDefaultPropertiesEnvironmentPostProcessor();
private SpringApplication springApplication = new SpringApplication();
@Test
void testOrder() {
assertEquals(Ordered.LOWEST_PRECEDENCE, instance.getOrder());
}
@Test
void testPostProcessEnvironment() {
MockEnvironment environment = new MockEnvironment();
// Case 1 : Not Any property
instance.postProcessEnvironment(environment, springApplication);
// Get PropertySources
MutablePropertySources propertySources = environment.getPropertySources();
// Nothing to change
PropertySource defaultPropertySource = propertySources.get("defaultProperties");
assertNotNull(defaultPropertySource);
assertEquals("true", defaultPropertySource.getProperty("dubbo.config.multiple"));
// assertEquals("true", defaultPropertySource.getProperty("dubbo.application.qos-enable"));
// Case 2 : Only set property "spring.application.name"
environment.setProperty("spring.application.name", "demo-dubbo-application");
instance.postProcessEnvironment(environment, springApplication);
defaultPropertySource = propertySources.get("defaultProperties");
Object dubboApplicationName = defaultPropertySource.getProperty("dubbo.application.name");
assertEquals("demo-dubbo-application", dubboApplicationName);
// Case 3 : Only set property "dubbo.application.name"
// Reset environment
environment = new MockEnvironment();
propertySources = environment.getPropertySources();
environment.setProperty("dubbo.application.name", "demo-dubbo-application");
instance.postProcessEnvironment(environment, springApplication);
defaultPropertySource = propertySources.get("defaultProperties");
assertNotNull(defaultPropertySource);
dubboApplicationName = environment.getProperty("dubbo.application.name");
assertEquals("demo-dubbo-application", dubboApplicationName);
// Case 4 : If "defaultProperties" PropertySource is present in PropertySources
// Reset environment
environment = new MockEnvironment();
propertySources = environment.getPropertySources();
propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>()));
environment.setProperty("spring.application.name", "demo-dubbo-application");
instance.postProcessEnvironment(environment, springApplication);
defaultPropertySource = propertySources.get("defaultProperties");
dubboApplicationName = defaultPropertySource.getProperty("dubbo.application.name");
assertEquals("demo-dubbo-application", dubboApplicationName);
// Case 5 : Reset dubbo.config.multiple and dubbo.application.qos-enable
environment = new MockEnvironment();
propertySources = environment.getPropertySources();
propertySources.addLast(new MapPropertySource("defaultProperties", new HashMap<String, Object>()));
environment.setProperty("dubbo.config.multiple", "false");
environment.setProperty("dubbo.application.qos-enable", "false");
instance.postProcessEnvironment(environment, springApplication);
assertEquals("false", environment.getProperty("dubbo.config.multiple"));
assertEquals("false", environment.getProperty("dubbo.application.qos-enable"));
}
}
| DubboDefaultPropertiesEnvironmentPostProcessorTest |
java | elastic__elasticsearch | test/framework/src/main/java/org/elasticsearch/test/disruption/SlowClusterStateProcessing.java | {
"start": 5156,
"end": 6230
} | class ____ implements Runnable {
@Override
public void run() {
while (disrupting && disruptedNode != null) {
try {
TimeValue duration = new TimeValue(delayDurationMin + random.nextInt((int) (delayDurationMax - delayDurationMin)));
if (interruptClusterStateProcessing(duration) == false) {
continue;
}
if (intervalBetweenDelaysMax > 0) {
duration = new TimeValue(
intervalBetweenDelaysMin + random.nextInt((int) (intervalBetweenDelaysMax - intervalBetweenDelaysMin))
);
if (disrupting && disruptedNode != null) {
Thread.sleep(duration.millis());
}
}
} catch (InterruptedException e) {} catch (Exception e) {
logger.error("error in background worker", e);
}
}
}
}
}
| BackgroundWorker |
java | hibernate__hibernate-orm | hibernate-core/src/test/java/org/hibernate/orm/test/mapping/type/java/JdbcTimestampJavaTypeTest.java | {
"start": 274,
"end": 752
} | class ____ extends AbstractDescriptorTest<Date> {
final Date original = new Date();
final Date copy = new Date( original.getTime() );
final Date different = new Date( original.getTime() + 500L);
public JdbcTimestampJavaTypeTest() {
super( JdbcTimestampJavaType.INSTANCE );
}
@Override
protected Data<Date> getTestData() {
return new Data<>( original, copy, different );
}
@Override
protected boolean shouldBeMutable() {
return true;
}
}
| JdbcTimestampJavaTypeTest |
java | quarkusio__quarkus | extensions/devui/runtime/src/main/java/io/quarkus/devui/runtime/js/JavaScriptResponseWriter.java | {
"start": 201,
"end": 955
} | class ____ implements JsonRpcResponseWriter {
private final ServerWebSocket socket;
public JavaScriptResponseWriter(ServerWebSocket socket) {
this.socket = socket;
}
@Override
public void write(String message) {
if (!socket.isClosed()) {
socket.writeTextMessage(message);
}
}
@Override
public void close() {
socket.close();
}
@Override
public boolean isOpen() {
return !socket.isClosed();
}
@Override
public boolean isClosed() {
return socket.isClosed();
}
@Override
public Object decorateObject(Object object, MessageType messageType) {
return new Result(messageType.name(), object);
}
} | JavaScriptResponseWriter |
java | quarkusio__quarkus | integration-tests/test-extension/extension/deployment/src/test/java/io/quarkus/logging/NoRotationLoggingTest.java | {
"start": 504,
"end": 1524
} | class ____ {
@RegisterExtension
static final QuarkusUnitTest config = new QuarkusUnitTest()
.withConfigurationResource("application-no-log-rotation.properties")
.withApplicationRoot((jar) -> jar
.addClass(LoggingTestsHelper.class)
.addAsManifestResource("application.properties", "microprofile-config.properties"))
.setLogFileName("NoRotationLoggingTest.log");
@Test
public void sizeRotatingConfigurationTest() {
Handler handler = getHandler(FileHandler.class);
assertThat(handler.getLevel()).isEqualTo(Level.INFO);
assertThat(handler).isExactlyInstanceOf(FileHandler.class);
Formatter formatter = handler.getFormatter();
assertThat(formatter).isInstanceOf(PatternFormatter.class);
PatternFormatter patternFormatter = (PatternFormatter) formatter;
assertThat(patternFormatter.getPattern()).isEqualTo("%d{HH:mm:ss} %-5p [%c{2.}]] (%t) %s%e%n");
}
}
| NoRotationLoggingTest |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/index/fielddata/FieldData.java | {
"start": 17756,
"end": 18231
} | class ____ extends DoubleValues {
private final LongValues values;
DoubleCastedValues(LongValues values) {
this.values = values;
}
@Override
public double doubleValue() throws IOException {
return values.longValue();
}
@Override
public boolean advanceExact(int doc) throws IOException {
return values.advanceExact(doc);
}
}
private static | DoubleCastedValues |
java | elastic__elasticsearch | server/src/main/java/org/elasticsearch/common/Rounding.java | {
"start": 59740,
"end": 61217
} | class ____ implements Prepared {
private final long[] values;
private final int max;
private final Prepared delegate;
private ArrayRounding(long[] values, int max, Prepared delegate) {
this.values = values;
this.max = max;
this.delegate = delegate;
}
@Override
public long round(long utcMillis) {
assert values[0] <= utcMillis : utcMillis + " must be after " + values[0];
int idx = Arrays.binarySearch(values, 0, max, utcMillis);
assert idx != -1 : "The insertion point is before the array! This should have tripped the assertion above.";
assert -1 - idx <= values.length : "This insertion point is after the end of the array.";
if (idx < 0) {
idx = -2 - idx;
}
return values[idx];
}
@Override
public long nextRoundingValue(long utcMillis) {
return delegate.nextRoundingValue(utcMillis);
}
@Override
public double roundingSize(long utcMillis, DateTimeUnit timeUnit) {
return delegate.roundingSize(utcMillis, timeUnit);
}
@Override
public double roundingSize(DateTimeUnit timeUnit) {
return delegate.roundingSize(timeUnit);
}
@Override
public long[] fixedRoundingPoints() {
return Arrays.copyOf(values, max);
}
}
}
| ArrayRounding |
java | apache__hadoop | hadoop-common-project/hadoop-auth/src/main/java/org/apache/hadoop/security/authentication/util/ZookeeperClient.java | {
"start": 4161,
"end": 10555
} | class ____ {
private static final Logger LOG = LoggerFactory.getLogger(ZookeeperClient.class);
private String connectionString;
private String namespace;
private String authenticationType = "none";
private String keytab;
private String principal;
private String jaasLoginEntryName;
private int sessionTimeout =
Integer.getInteger("curator-default-session-timeout", 60 * 1000);
private int connectionTimeout =
Integer.getInteger("curator-default-connection-timeout", 15 * 1000);
private RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);
private ZookeeperFactory zkFactory = new ConfigurableZookeeperFactory();
private boolean isSSLEnabled;
private String keystoreLocation;
private String keystorePassword;
private String truststoreLocation;
private String truststorePassword;
public static ZookeeperClient configure() {
return new ZookeeperClient();
}
public ZookeeperClient withConnectionString(String conn) {
connectionString = conn;
return this;
}
public ZookeeperClient withNamespace(String ns) {
this.namespace = ns;
return this;
}
public ZookeeperClient withAuthType(String authType) {
this.authenticationType = authType;
return this;
}
public ZookeeperClient withKeytab(String keytabPath) {
this.keytab = keytabPath;
return this;
}
public ZookeeperClient withPrincipal(String princ) {
this.principal = princ;
return this;
}
public ZookeeperClient withJaasLoginEntryName(String entryName) {
this.jaasLoginEntryName = entryName;
return this;
}
public ZookeeperClient withSessionTimeout(int timeoutMS) {
this.sessionTimeout = timeoutMS;
return this;
}
public ZookeeperClient withConnectionTimeout(int timeoutMS) {
this.connectionTimeout = timeoutMS;
return this;
}
public ZookeeperClient withRetryPolicy(RetryPolicy policy) {
this.retryPolicy = policy;
return this;
}
public ZookeeperClient withZookeeperFactory(ZookeeperFactory factory) {
this.zkFactory = factory;
return this;
}
public ZookeeperClient enableSSL(boolean enable) {
this.isSSLEnabled = enable;
return this;
}
public ZookeeperClient withKeystore(String keystorePath) {
this.keystoreLocation = keystorePath;
return this;
}
public ZookeeperClient withKeystorePassword(String keystorePass) {
this.keystorePassword = keystorePass;
return this;
}
public ZookeeperClient withTruststore(String truststorePath) {
this.truststoreLocation = truststorePath;
return this;
}
public ZookeeperClient withTruststorePassword(String truststorePass) {
this.truststorePassword = truststorePass;
return this;
}
public CuratorFramework create() {
checkNotNull(connectionString, "Zookeeper connection string cannot be null!");
checkNotNull(retryPolicy, "Zookeeper connection retry policy cannot be null!");
return createFrameworkFactoryBuilder()
.connectString(connectionString)
.zookeeperFactory(zkFactory)
.namespace(namespace)
.sessionTimeoutMs(sessionTimeout)
.connectionTimeoutMs(connectionTimeout)
.retryPolicy(retryPolicy)
.aclProvider(aclProvider())
.zkClientConfig(zkClientConfig())
.build();
}
@VisibleForTesting
CuratorFrameworkFactory.Builder createFrameworkFactoryBuilder() {
return CuratorFrameworkFactory.builder();
}
private ACLProvider aclProvider() {
// AuthType has to be explicitly set to 'none' or 'sasl'
checkNotNull(authenticationType, "Zookeeper authType cannot be null!");
checkArgument(authenticationType.equals("sasl") || authenticationType.equals("none"),
"Zookeeper authType must be one of [none, sasl]!");
ACLProvider aclProvider;
if (authenticationType.equals("sasl")) {
LOG.info("Connecting to ZooKeeper with SASL/Kerberos and using 'sasl' ACLs.");
checkArgument(!isEmpty(keytab), "Zookeeper client's Kerberos Keytab must be specified!");
checkArgument(!isEmpty(principal),
"Zookeeper client's Kerberos Principal must be specified!");
checkArgument(!isEmpty(jaasLoginEntryName), "JAAS Login Entry name must be specified!");
JaasConfiguration jConf = new JaasConfiguration(jaasLoginEntryName, principal, keytab);
Configuration.setConfiguration(jConf);
System.setProperty(ZKClientConfig.LOGIN_CONTEXT_NAME_KEY, jaasLoginEntryName);
System.setProperty("zookeeper.authProvider.1",
"org.apache.zookeeper.server.auth.SASLAuthenticationProvider");
aclProvider = new SASLOwnerACLProvider(principal.split("[/@]")[0]);
} else { // "none"
LOG.info("Connecting to ZooKeeper without authentication.");
aclProvider = new DefaultACLProvider(); // open to everyone
}
return aclProvider;
}
private ZKClientConfig zkClientConfig() {
ZKClientConfig zkClientConfig = new ZKClientConfig();
if (isSSLEnabled){
LOG.info("Zookeeper client will use SSL connection. (keystore = {}; truststore = {};)",
keystoreLocation, truststoreLocation);
checkArgument(!isEmpty(keystoreLocation),
"The keystore location parameter is empty for the ZooKeeper client connection.");
checkArgument(!isEmpty(truststoreLocation),
"The truststore location parameter is empty for the ZooKeeper client connection.");
try (ClientX509Util sslOpts = new ClientX509Util()) {
zkClientConfig.setProperty(ZKClientConfig.SECURE_CLIENT, "true");
zkClientConfig.setProperty(ZKClientConfig.ZOOKEEPER_CLIENT_CNXN_SOCKET,
"org.apache.zookeeper.ClientCnxnSocketNetty");
zkClientConfig.setProperty(sslOpts.getSslKeystoreLocationProperty(), keystoreLocation);
zkClientConfig.setProperty(sslOpts.getSslKeystorePasswdProperty(), keystorePassword);
zkClientConfig.setProperty(sslOpts.getSslTruststoreLocationProperty(), truststoreLocation);
zkClientConfig.setProperty(sslOpts.getSslTruststorePasswdProperty(), truststorePassword);
}
} else {
LOG.info("Zookeeper client will use Plain connection.");
}
return zkClientConfig;
}
/**
* Simple implementation of an {@link ACLProvider} that simply returns an ACL
* that gives all permissions only to a single principal.
*/
@VisibleForTesting
static final | ZookeeperClient |
java | resilience4j__resilience4j | resilience4j-ratelimiter/src/main/java/io/github/resilience4j/ratelimiter/RateLimiterRegistry.java | {
"start": 10978,
"end": 14203
} | class ____ {
private static final String DEFAULT_CONFIG = "default";
private RegistryStore<RateLimiter> registryStore;
private Map<String, RateLimiterConfig> rateLimiterConfigsMap;
private List<RegistryEventConsumer<RateLimiter>> registryEventConsumers;
private Map<String, String> tags;
public Builder() {
this.rateLimiterConfigsMap = new java.util.HashMap<>();
this.registryEventConsumers = new ArrayList<>();
}
public Builder withRegistryStore(RegistryStore<RateLimiter> registryStore) {
this.registryStore = registryStore;
return this;
}
/**
* Configures a RateLimiterRegistry with a custom default RateLimiter configuration.
*
* @param rateLimiterConfig a custom default RateLimiter configuration
* @return a {@link RateLimiterRegistry.Builder}
*/
public Builder withRateLimiterConfig(RateLimiterConfig rateLimiterConfig) {
rateLimiterConfigsMap.put(DEFAULT_CONFIG, rateLimiterConfig);
return this;
}
/**
* Configures a RateLimiterRegistry with a custom RateLimiter configuration.
*
* @param configName configName for a custom shared RateLimiter configuration
* @param configuration a custom shared RateLimiter configuration
* @return a {@link RateLimiterRegistry.Builder}
* @throws IllegalArgumentException if {@code configName.equals("default")}
*/
public Builder addRateLimiterConfig(String configName, RateLimiterConfig configuration) {
if (configName.equals(DEFAULT_CONFIG)) {
throw new IllegalArgumentException(
"You cannot add another configuration with name 'default' as it is preserved for default configuration");
}
rateLimiterConfigsMap.put(configName, configuration);
return this;
}
/**
* Configures a RateLimiterRegistry with a RateLimiter registry event consumer.
*
* @param registryEventConsumer a RateLimiter registry event consumer.
* @return a {@link RateLimiterRegistry.Builder}
*/
public Builder addRegistryEventConsumer(RegistryEventConsumer<RateLimiter> registryEventConsumer) {
this.registryEventConsumers.add(registryEventConsumer);
return this;
}
/**
* Configures a RateLimiterRegistry with Tags.
* <p>
* Tags added to the registry will be added to every instance created by this registry.
*
* @param tags default tags to add to the registry.
* @return a {@link RateLimiterRegistry.Builder}
*/
public Builder withTags(Map<String, String> tags) {
this.tags = tags;
return this;
}
/**
* Builds a RateLimiterRegistry
*
* @return the RateLimiterRegistry
*/
public RateLimiterRegistry build() {
return new InMemoryRateLimiterRegistry(rateLimiterConfigsMap, registryEventConsumers, tags,
registryStore);
}
}
}
| Builder |
java | ReactiveX__RxJava | src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableDoFinally.java | {
"start": 1745,
"end": 4327
} | class ____<T> extends BasicIntQueueDisposable<T> implements Observer<T> {
private static final long serialVersionUID = 4109457741734051389L;
final Observer<? super T> downstream;
final Action onFinally;
Disposable upstream;
QueueDisposable<T> qd;
boolean syncFused;
DoFinallyObserver(Observer<? super T> actual, Action onFinally) {
this.downstream = actual;
this.onFinally = onFinally;
}
@SuppressWarnings("unchecked")
@Override
public void onSubscribe(Disposable d) {
if (DisposableHelper.validate(this.upstream, d)) {
this.upstream = d;
if (d instanceof QueueDisposable) {
this.qd = (QueueDisposable<T>)d;
}
downstream.onSubscribe(this);
}
}
@Override
public void onNext(T t) {
downstream.onNext(t);
}
@Override
public void onError(Throwable t) {
downstream.onError(t);
runFinally();
}
@Override
public void onComplete() {
downstream.onComplete();
runFinally();
}
@Override
public void dispose() {
upstream.dispose();
runFinally();
}
@Override
public boolean isDisposed() {
return upstream.isDisposed();
}
@Override
public int requestFusion(int mode) {
QueueDisposable<T> qd = this.qd;
if (qd != null && (mode & BOUNDARY) == 0) {
int m = qd.requestFusion(mode);
if (m != NONE) {
syncFused = m == SYNC;
}
return m;
}
return NONE;
}
@Override
public void clear() {
qd.clear();
}
@Override
public boolean isEmpty() {
return qd.isEmpty();
}
@Nullable
@Override
public T poll() throws Throwable {
T v = qd.poll();
if (v == null && syncFused) {
runFinally();
}
return v;
}
void runFinally() {
if (compareAndSet(0, 1)) {
try {
onFinally.run();
} catch (Throwable ex) {
Exceptions.throwIfFatal(ex);
RxJavaPlugins.onError(ex);
}
}
}
}
}
| DoFinallyObserver |
java | google__guava | android/guava/src/com/google/common/collect/ForwardingSortedSet.java | {
"start": 1710,
"end": 2724
} | class ____ <i>not</i> forward calls to {@code
* default} methods. Instead, it inherits their default implementations. When those implementations
* invoke methods, they invoke methods on the {@code ForwardingSortedSet}.
*
* <p>Each of the {@code standard} methods, where appropriate, uses the set's comparator (or the
* natural ordering of the elements, if there is no comparator) to test element equality. As a
* result, if the comparator is not consistent with equals, some of the standard implementations may
* violate the {@code Set} contract.
*
* <p>The {@code standard} methods and the collection views they return are not guaranteed to be
* thread-safe, even when all of the methods that they depend on are thread-safe.
*
* @author Mike Bostock
* @author Louis Wasserman
* @since 2.0
*/
@GwtCompatible
/*
* We provide and encourage use of ForwardingNavigableSet over this class, but we still provide this
* one to preserve compatibility.
*/
@SuppressWarnings("JdkObsolete")
public abstract | does |
java | spring-projects__spring-boot | module/spring-boot-jersey/src/test/java/org/springframework/boot/jersey/autoconfigure/JerseyAutoConfigurationServletContainerTests.java | {
"start": 3314,
"end": 4029
} | class ____ {
@Bean
TomcatServletWebServerFactory tomcat() {
return new TomcatServletWebServerFactory() {
@Override
protected void postProcessContext(Context context) {
Wrapper jerseyServlet = context.createWrapper();
String servletName = Application.class.getName();
jerseyServlet.setName(servletName);
jerseyServlet.setServletClass(ServletContainer.class.getName());
jerseyServlet.setServlet(new ServletContainer());
jerseyServlet.setOverridable(false);
context.addChild(jerseyServlet);
String pattern = UDecoder.URLDecode("/*", StandardCharsets.UTF_8);
context.addServletMappingDecoded(pattern, servletName);
}
};
}
}
}
| ContainerConfiguration |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/PreferredInterfaceTypeTest.java | {
"start": 18226,
"end": 18589
} | interface ____ {
int applyAndGetSize(Function<String, List<String>> fun);
}
""")
.addSourceLines(
"ApplyImpl.java",
"""
import com.google.common.collect.ImmutableList;
import java.util.function.Function;
import java.util.List;
public | ApplyInterface |
java | google__error-prone | core/src/test/java/com/google/errorprone/bugpatterns/UnusedVariableTest.java | {
"start": 33935,
"end": 34351
} | class ____ {
public void test() {
Integer a = 1;
a.hashCode();
a = null;
}
}
""")
.doTest();
}
@Test
public void unusedAssignment_nulledOut_thenAssignedAgain() {
refactoringHelper
.addInputLines(
"Test.java",
"""
package unusedvars;
public | Test |
java | spring-projects__spring-framework | spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/ServletAnnotationControllerHandlerMethodTests.java | {
"start": 138674,
"end": 139105
} | class ____ {
@RequestMapping(value = "/bug/EXISTING", method = RequestMethod.POST)
public void directMatch(Writer writer) throws IOException {
writer.write("Direct");
}
@RequestMapping(value = "/bug/{type}", method = RequestMethod.GET)
public void patternMatch(Writer writer) throws IOException {
writer.write("Pattern");
}
}
@Controller
@RequestMapping("/test*")
static | AmbiguousPathAndRequestMethodController |
java | elastic__elasticsearch | server/src/test/java/org/elasticsearch/action/admin/indices/close/CloseIndexRequestTests.java | {
"start": 983,
"end": 5945
} | class ____ extends ESTestCase {
public void testSerialization() throws Exception {
final CloseIndexRequest request = randomRequest();
try (BytesStreamOutput out = new BytesStreamOutput()) {
request.writeTo(out);
final CloseIndexRequest deserializedRequest;
try (StreamInput in = out.bytes().streamInput()) {
deserializedRequest = new CloseIndexRequest(in);
}
assertEquals(request.ackTimeout(), deserializedRequest.ackTimeout());
assertEquals(request.masterNodeTimeout(), deserializedRequest.masterNodeTimeout());
assertEquals(request.indicesOptions(), deserializedRequest.indicesOptions());
assertEquals(request.getParentTask(), deserializedRequest.getParentTask());
assertEquals(request.waitForActiveShards(), deserializedRequest.waitForActiveShards());
assertArrayEquals(request.indices(), deserializedRequest.indices());
}
}
public void testBwcSerialization() throws Exception {
{
final CloseIndexRequest request = randomRequest();
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.setTransportVersion(TransportVersionUtils.randomCompatibleVersion(random()));
request.writeTo(out);
try (StreamInput in = out.bytes().streamInput()) {
in.setTransportVersion(out.getTransportVersion());
assertEquals(request.getParentTask(), TaskId.readFromStream(in));
assertEquals(request.masterNodeTimeout(), in.readTimeValue());
if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_15_0)) {
assertEquals(request.masterTerm(), in.readVLong());
}
assertEquals(request.ackTimeout(), in.readTimeValue());
assertArrayEquals(request.indices(), in.readStringArray());
final IndicesOptions indicesOptions = IndicesOptions.readIndicesOptions(in);
assertEquals(request.indicesOptions(), indicesOptions);
assertEquals(request.waitForActiveShards(), ActiveShardCount.readFrom(in));
}
}
}
{
final CloseIndexRequest sample = randomRequest();
final TransportVersion version = TransportVersionUtils.randomCompatibleVersion(random());
try (BytesStreamOutput out = new BytesStreamOutput()) {
out.setTransportVersion(version);
sample.getParentTask().writeTo(out);
out.writeTimeValue(sample.masterNodeTimeout());
if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_15_0)) {
out.writeVLong(sample.masterTerm());
}
out.writeTimeValue(sample.ackTimeout());
out.writeStringArray(sample.indices());
sample.indicesOptions().writeIndicesOptions(out);
sample.waitForActiveShards().writeTo(out);
final CloseIndexRequest deserializedRequest;
try (StreamInput in = out.bytes().streamInput()) {
in.setTransportVersion(version);
deserializedRequest = new CloseIndexRequest(in);
}
assertEquals(sample.getParentTask(), deserializedRequest.getParentTask());
assertEquals(sample.masterNodeTimeout(), deserializedRequest.masterNodeTimeout());
assertEquals(sample.ackTimeout(), deserializedRequest.ackTimeout());
assertArrayEquals(sample.indices(), deserializedRequest.indices());
assertEquals(sample.indicesOptions(), deserializedRequest.indicesOptions());
assertEquals(sample.waitForActiveShards(), deserializedRequest.waitForActiveShards());
}
}
}
private CloseIndexRequest randomRequest() {
CloseIndexRequest request = new CloseIndexRequest();
request.indices(generateRandomStringArray(10, 5, false, false));
if (randomBoolean()) {
request.indicesOptions(
IndicesOptions.fromOptions(randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean(), randomBoolean())
);
}
if (randomBoolean()) {
request.ackTimeout(randomPositiveTimeValue());
}
if (randomBoolean()) {
request.masterNodeTimeout(randomPositiveTimeValue());
}
if (randomBoolean()) {
request.setParentTask(randomAlphaOfLength(5), randomNonNegativeLong());
}
if (randomBoolean()) {
request.waitForActiveShards(
randomFrom(ActiveShardCount.DEFAULT, ActiveShardCount.NONE, ActiveShardCount.ONE, ActiveShardCount.ALL)
);
}
return request;
}
}
| CloseIndexRequestTests |
java | elastic__elasticsearch | x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/authz/permission/IndicesPermission.java | {
"start": 55052,
"end": 55723
} | class ____ {
public static final DocumentLevelPermissions ALLOW_ALL = new DocumentLevelPermissions();
static {
ALLOW_ALL.allowAll = true;
}
private Set<BytesReference> queries = null;
private boolean allowAll = false;
private void addAll(Set<BytesReference> query) {
if (allowAll == false) {
if (queries == null) {
queries = Sets.newHashSetWithExpectedSize(query.size());
}
queries.addAll(query);
}
}
private boolean isAllowAll() {
return allowAll;
}
}
}
| DocumentLevelPermissions |
java | spring-projects__spring-framework | spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostConstructAndAutowiringTests.java | {
"start": 1696,
"end": 1858
} | class ____ {
/**
* Prior to the fix for SPR-8080, this method would succeed due to ordering of
* configuration | ConfigurationClassPostConstructAndAutowiringTests |
java | spring-projects__spring-data-jpa | spring-data-jpa/src/test/java/org/springframework/data/jpa/repository/support/DefaultJpaEntityMetadataUnitTest.java | {
"start": 2360,
"end": 2511
} | interface ____ {
@AliasFor(annotation = Entity.class, attribute = "name")
String entityName();
}
private static | CustomEntityAnnotationUsingAliasFor |
java | spring-projects__spring-boot | buildpack/spring-boot-buildpack-platform/src/main/java/org/springframework/boot/buildpack/platform/io/InspectedContent.java | {
"start": 4289,
"end": 5676
} | class ____ extends OutputStream {
private final Inspector[] inspectors;
private int size;
private OutputStream delegate;
private @Nullable File tempFile;
private final byte[] singleByteBuffer = new byte[0];
private InspectingOutputStream(Inspector[] inspectors) {
this.inspectors = inspectors;
this.delegate = new ByteArrayOutputStream();
}
@Override
public void write(int b) throws IOException {
this.singleByteBuffer[0] = (byte) (b & 0xFF);
write(this.singleByteBuffer);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
int size = len - off;
if (this.tempFile == null && (this.size + size) > MEMORY_LIMIT) {
convertToTempFile();
}
this.delegate.write(b, off, len);
for (Inspector inspector : this.inspectors) {
inspector.update(b, off, len);
}
this.size += size;
}
private void convertToTempFile() throws IOException {
this.tempFile = File.createTempFile("buildpack", ".tmp");
byte[] bytes = ((ByteArrayOutputStream) this.delegate).toByteArray();
this.delegate = new FileOutputStream(this.tempFile);
StreamUtils.copy(bytes, this.delegate);
}
private Object getContent() {
return (this.tempFile != null) ? this.tempFile : ((ByteArrayOutputStream) this.delegate).toByteArray();
}
private int getSize() {
return this.size;
}
}
}
| InspectingOutputStream |
java | apache__camel | core/camel-core/src/test/java/org/apache/camel/processor/enricher/EnricherAggregateOnExceptionTest.java | {
"start": 3271,
"end": 3667
} | class ____ implements Processor {
@Override
public void process(Exchange exchange) {
String body = exchange.getIn().getBody(String.class);
if (body.startsWith("Kaboom")) {
throw new IllegalArgumentException("I cannot do this");
}
exchange.getIn().setBody("Hello " + body);
}
}
public static | MyProcessor |
java | elastic__elasticsearch | x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/multivalue/MvLastBooleanEvaluator.java | {
"start": 2834,
"end": 3326
} | class ____ implements EvalOperator.ExpressionEvaluator.Factory {
private final EvalOperator.ExpressionEvaluator.Factory field;
public Factory(EvalOperator.ExpressionEvaluator.Factory field) {
this.field = field;
}
@Override
public MvLastBooleanEvaluator get(DriverContext context) {
return new MvLastBooleanEvaluator(field.get(context), context);
}
@Override
public String toString() {
return "MvLast[field=" + field + "]";
}
}
}
| Factory |
java | hibernate__hibernate-orm | hibernate-core/src/main/java/org/hibernate/dialect/pagination/AbstractSimpleLimitHandler.java | {
"start": 593,
"end": 2661
} | class ____ extends AbstractLimitHandler {
protected abstract String limitClause(boolean hasFirstRow);
protected String limitClause(boolean hasFirstRow, int jdbcParameterCount, ParameterMarkerStrategy parameterMarkerStrategy) {
return limitClause( hasFirstRow );
}
protected String offsetOnlyClause() {
return null;
}
protected String offsetOnlyClause(int jdbcParameterCount, ParameterMarkerStrategy parameterMarkerStrategy) {
return offsetOnlyClause();
}
@Override
public String processSql(String sql, Limit limit) {
return processSql( sql, -1, null, limit );
}
@Override
public String processSql(String sql, int jdbcParameterCount, @Nullable ParameterMarkerStrategy parameterMarkerStrategy, QueryOptions queryOptions) {
return processSql( sql, jdbcParameterCount, parameterMarkerStrategy, queryOptions.getLimit() );
}
private String processSql(String sql, int jdbcParameterCount, @Nullable ParameterMarkerStrategy parameterMarkerStrategy, @Nullable Limit limit) {
final boolean hasMaxRows = hasMaxRows( limit );
final boolean hasFirstRow = hasFirstRow( limit );
if ( hasMaxRows ) {
final String limitClause =
isStandardRenderer( parameterMarkerStrategy )
? limitClause( hasFirstRow )
: limitClause( hasFirstRow, jdbcParameterCount, parameterMarkerStrategy );
return insert( limitClause, sql );
}
else if ( hasFirstRow ) {
final String offsetOnlyClause =
isStandardRenderer( parameterMarkerStrategy )
? offsetOnlyClause()
: offsetOnlyClause( jdbcParameterCount, parameterMarkerStrategy );
return offsetOnlyClause != null
? insert( offsetOnlyClause, sql )
: sql;
}
else {
return sql;
}
}
protected String insert(String limitClause, String sql) {
return insertBeforeForUpdate( limitClause, sql );
}
@Override
public final boolean supportsLimit() {
return true;
}
@Override
public final boolean supportsVariableLimit() {
return true;
}
@Override
public boolean supportsOffset() {
return super.supportsOffset();
}
}
| AbstractSimpleLimitHandler |
java | spring-projects__spring-framework | spring-webflux/src/main/java/org/springframework/web/reactive/function/client/DefaultClientResponseBuilder.java | {
"start": 1784,
"end": 6489
} | class ____ implements ClientResponse.Builder {
private static final HttpRequest EMPTY_REQUEST = new HttpRequest() {
private final URI empty = URI.create("");
@Override
public HttpMethod getMethod() {
return HttpMethod.valueOf("UNKNOWN");
}
@Override
public URI getURI() {
return this.empty;
}
@Override
public HttpHeaders getHeaders() {
return HttpHeaders.EMPTY;
}
@Override
public Map<String, Object> getAttributes() {
return Collections.emptyMap();
}
};
private final ExchangeStrategies strategies;
private HttpStatusCode statusCode = HttpStatus.OK;
private @Nullable HttpHeaders headers;
private @Nullable MultiValueMap<String, ResponseCookie> cookies;
private Flux<DataBuffer> body = Flux.empty();
private @Nullable ClientResponse originalResponse;
private HttpRequest request;
DefaultClientResponseBuilder(ExchangeStrategies strategies) {
Assert.notNull(strategies, "ExchangeStrategies must not be null");
this.strategies = strategies;
this.headers = new HttpHeaders();
this.cookies = new LinkedMultiValueMap<>();
this.request = EMPTY_REQUEST;
}
DefaultClientResponseBuilder(ClientResponse other, boolean mutate) {
Assert.notNull(other, "ClientResponse must not be null");
this.strategies = other.strategies();
this.statusCode = other.statusCode();
if (mutate) {
this.body = other.bodyToFlux(DataBuffer.class);
}
else {
this.headers = new HttpHeaders();
this.headers.addAll(other.headers().asHttpHeaders());
}
this.originalResponse = other;
this.request = (other instanceof DefaultClientResponse defaultClientResponse ?
defaultClientResponse.request() : EMPTY_REQUEST);
}
@Override
public DefaultClientResponseBuilder statusCode(HttpStatusCode statusCode) {
Assert.notNull(statusCode, "HttpStatusCode must not be null");
this.statusCode = statusCode;
return this;
}
@Override
public DefaultClientResponseBuilder rawStatusCode(int statusCode) {
return statusCode(HttpStatusCode.valueOf(statusCode));
}
@Override
public ClientResponse.Builder header(String headerName, String... headerValues) {
for (String headerValue : headerValues) {
getHeaders().add(headerName, headerValue);
}
return this;
}
@Override
public ClientResponse.Builder headers(Consumer<HttpHeaders> headersConsumer) {
headersConsumer.accept(getHeaders());
return this;
}
@SuppressWarnings({"ConstantConditions", "NullAway"})
private HttpHeaders getHeaders() {
if (this.headers == null) {
this.headers = new HttpHeaders(this.originalResponse.headers().asHttpHeaders());
}
return this.headers;
}
@Override
public DefaultClientResponseBuilder cookie(String name, String... values) {
for (String value : values) {
getCookies().add(name, ResponseCookie.from(name, value).build());
}
return this;
}
@Override
public ClientResponse.Builder cookies(Consumer<MultiValueMap<String, ResponseCookie>> cookiesConsumer) {
cookiesConsumer.accept(getCookies());
return this;
}
@SuppressWarnings({"ConstantConditions", "NullAway"})
private MultiValueMap<String, ResponseCookie> getCookies() {
if (this.cookies == null) {
this.cookies = new LinkedMultiValueMap<>(this.originalResponse.cookies());
}
return this.cookies;
}
@Override
public ClientResponse.Builder body(Function<Flux<DataBuffer>, Flux<DataBuffer>> transformer) {
this.body = transformer.apply(this.body);
return this;
}
@Override
public ClientResponse.Builder body(Flux<DataBuffer> body) {
Assert.notNull(body, "Body must not be null");
releaseBody();
this.body = body;
return this;
}
@Override
public ClientResponse.Builder body(String body) {
Assert.notNull(body, "Body must not be null");
releaseBody();
this.body = Flux.just(body).
map(s -> {
byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
return DefaultDataBufferFactory.sharedInstance.wrap(bytes);
});
return this;
}
private void releaseBody() {
this.body.subscribe(DataBufferUtils.releaseConsumer());
}
@Override
public ClientResponse.Builder request(HttpRequest request) {
Assert.notNull(request, "Request must not be null");
this.request = request;
return this;
}
@Override
public ClientResponse build() {
ClientHttpResponse httpResponse = new BuiltClientHttpResponse(
this.statusCode, this.headers, this.cookies, this.body, this.originalResponse);
return new DefaultClientResponse(httpResponse, this.strategies,
this.originalResponse != null ? this.originalResponse.logPrefix() : "",
WebClientUtils.getRequestDescription(this.request.getMethod(), this.request.getURI()),
() -> this.request);
}
private static | DefaultClientResponseBuilder |
java | spring-projects__spring-framework | spring-test/src/test/java/org/springframework/test/context/junit/jupiter/AutowiredConfigurationErrorsIntegrationTests.java | {
"start": 6747,
"end": 6974
} | class ____ {
@Autowired
@BeforeEach
void beforeEach(TestInfo testInfo) {
}
@Test
@DisplayName(DISPLAY_NAME)
void test() {
}
}
@SpringJUnitConfig(Config.class)
@FailingTestCase
static | AutowiredBeforeEachMethod |
java | hibernate__hibernate-orm | hibernate-envers/src/test/java/org/hibernate/orm/test/envers/integration/ids/idclass/ReferenceIdentifierClassId.java | {
"start": 236,
"end": 1439
} | class ____ implements Serializable {
private Integer iiie;
private String type;
public ReferenceIdentifierClassId() {
}
public ReferenceIdentifierClassId(Integer iiie, String type) {
this.iiie = iiie;
this.type = type;
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( !(o instanceof ReferenceIdentifierClassId) ) {
return false;
}
ReferenceIdentifierClassId that = (ReferenceIdentifierClassId) o;
if ( iiie != null ? !iiie.equals( that.iiie) : that.iiie != null ) {
return false;
}
if ( type != null ? !type.equals( that.type ) : that.type != null ) {
return false;
}
return true;
}
@Override
public int hashCode() {
int result = iiie != null ? iiie.hashCode() : 0;
result = 31 * result + (type != null ? type.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "ReferenceIdentifierClassId(iiie = " + iiie + ", type = " + type + ")";
}
public Integer getIiie() {
return iiie;
}
public void setIiie(Integer iiie) {
this.iiie = iiie;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
| ReferenceIdentifierClassId |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/introspect/IsGetterRenaming2527Test.java | {
"start": 521,
"end": 811
} | class ____ {
boolean isEnabled;
protected POJO2527() { }
public POJO2527(boolean b) {
isEnabled = b;
}
public boolean getEnabled() { return isEnabled; }
public void setEnabled(boolean b) { isEnabled = b; }
}
static | POJO2527 |
java | quarkusio__quarkus | independent-projects/resteasy-reactive/common/runtime/src/main/java/org/jboss/resteasy/reactive/RestMulti.java | {
"start": 1487,
"end": 2836
} | class ____<T> extends AbstractMulti<T> {
public abstract Integer getStatus();
public abstract Map<String, List<String>> getHeaders();
public static <T> RestMulti.SyncRestMulti.Builder<T> fromMultiData(Multi<T> multi) {
return new RestMulti.SyncRestMulti.Builder<>(multi);
}
public static <T, R> RestMulti<R> fromUniResponse(Uni<T> uni,
Function<T, Multi<R>> dataExtractor) {
return fromUniResponse(uni, dataExtractor, null, null);
}
public static <T, R> RestMulti<R> fromUniResponse(Uni<T> uni,
Function<T, Multi<R>> dataExtractor,
Function<T, Map<String, List<String>>> headersExtractor) {
return fromUniResponse(uni, dataExtractor, headersExtractor, null);
}
public static <T, R> RestMulti<R> fromUniResponse(Uni<T> uni,
Function<T, Multi<R>> dataExtractor,
Function<T, Map<String, List<String>>> headersExtractor,
Function<T, Integer> statusExtractor) {
Function<? super T, ? extends Multi<? extends R>> actualDataExtractor = Infrastructure
.decorate(nonNull(dataExtractor, "dataExtractor"));
return (RestMulti<R>) Infrastructure.onMultiCreation(new AsyncRestMulti<>(uni, actualDataExtractor,
headersExtractor, statusExtractor));
}
public static | RestMulti |
java | FasterXML__jackson-databind | src/test/java/tools/jackson/databind/deser/filter/ReadOnlyDeserFailOnUnknown2719Test.java | {
"start": 409,
"end": 486
} | class ____
{
// [databind#2719]
static | ReadOnlyDeserFailOnUnknown2719Test |
java | grpc__grpc-java | xds/src/generated/thirdparty/grpc/io/envoyproxy/envoy/service/rate_limit_quota/v3/RateLimitQuotaServiceGrpc.java | {
"start": 9719,
"end": 10442
} | class ____
extends io.grpc.stub.AbstractBlockingStub<RateLimitQuotaServiceBlockingStub> {
private RateLimitQuotaServiceBlockingStub(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
super(channel, callOptions);
}
@java.lang.Override
protected RateLimitQuotaServiceBlockingStub build(
io.grpc.Channel channel, io.grpc.CallOptions callOptions) {
return new RateLimitQuotaServiceBlockingStub(channel, callOptions);
}
}
/**
* A stub to allow clients to do ListenableFuture-style rpc calls to service RateLimitQuotaService.
* <pre>
* Defines the Rate Limit Quota Service (RLQS).
* </pre>
*/
public static final | RateLimitQuotaServiceBlockingStub |
java | elastic__elasticsearch | x-pack/plugin/security/src/internalClusterTest/java/org/elasticsearch/xpack/security/TemplateUpgraderTests.java | {
"start": 1598,
"end": 4120
} | class ____ extends SecurityIntegTestCase {
public void testTemplatesWorkAsExpected() throws Exception {
ClusterService clusterService = internalCluster().getInstance(ClusterService.class, internalCluster().getMasterName());
ThreadPool threadPool = internalCluster().getInstance(ThreadPool.class, internalCluster().getMasterName());
Client client = internalCluster().getInstance(Client.class, internalCluster().getMasterName());
UnaryOperator<Map<String, IndexTemplateMetadata>> indexTemplateMetadataUpgraders = map -> {
map.remove("removed-template");
map.put(
"added-template",
IndexTemplateMetadata.builder("added-template")
.order(1)
.patterns(Collections.singletonList(randomAlphaOfLength(10)))
.build()
);
return map;
};
AcknowledgedResponse putIndexTemplateResponse = indicesAdmin().preparePutTemplate("removed-template")
.setOrder(1)
.setPatterns(Collections.singletonList(randomAlphaOfLength(10)))
.get();
assertAcked(putIndexTemplateResponse);
assertTemplates("removed-template", "added-template");
TemplateUpgradeService templateUpgradeService = new TemplateUpgradeService(
client,
clusterService,
threadPool,
Collections.singleton(indexTemplateMetadataUpgraders)
);
// ensure the cluster listener gets triggered
ClusterChangedEvent event = new ClusterChangedEvent("testing", clusterService.state(), clusterService.state());
final ThreadContext threadContext = threadPool.getThreadContext();
try (ThreadContext.StoredContext ignore = threadContext.stashContext()) {
threadContext.markAsSystemContext();
templateUpgradeService.clusterChanged(event);
}
assertBusy(() -> assertTemplates("added-template", "removed-template"));
}
private void assertTemplates(String existingTemplate, String deletedTemplate) {
GetIndexTemplatesResponse response = client().admin().indices().prepareGetTemplates(TEST_REQUEST_TIMEOUT).get();
List<String> templateNames = response.getIndexTemplates().stream().map(IndexTemplateMetadata::name).collect(Collectors.toList());
assertThat(templateNames, hasItem(existingTemplate));
assertThat(templateNames, not(hasItem(deletedTemplate)));
}
}
| TemplateUpgraderTests |
java | quarkusio__quarkus | extensions/hibernate-search-backend-elasticsearch-common/runtime/src/main/java/io/quarkus/hibernate/search/backend/elasticsearch/common/runtime/HibernateSearchBackendElasticsearchBuildTimeConfig.java | {
"start": 3556,
"end": 4656
} | interface ____ {
/**
* One or more xref:#bean-reference-note-anchor[bean references]
* to the component(s) used to configure full text analysis (e.g. analyzers, normalizers).
*
* The referenced beans must implement `ElasticsearchAnalysisConfigurer`.
*
* See xref:#analysis-configurer[Setting up the analyzers] for more
* information.
*
* [NOTE]
* ====
* Instead of setting this configuration property,
* you can simply annotate your custom `ElasticsearchAnalysisConfigurer` implementations with `@SearchExtension`
* and leave the configuration property unset: Hibernate Search will use the annotated implementation automatically.
* See xref:#plugging-in-custom-components[this section]
* for more information.
*
* If this configuration property is set, it takes precedence over any `@SearchExtension` annotation.
* ====
*
* @asciidoclet
*/
Optional<List<String>> configurer();
}
}
| AnalysisConfig |
java | google__auto | value/src/test/java/com/google/auto/value/processor/AutoAnnotationCompilationTest.java | {
"start": 6125,
"end": 6728
} | class ____ {",
" @AutoAnnotation",
" public static MyAnnotation newMyAnnotation() {",
" return new AutoAnnotation_AnnotationFactory_newMyAnnotation();",
" }",
"}");
JavaFileObject expectedOutput =
JavaFileObjects.forSourceLines(
"AutoAnnotation_AnnotationFactory_newMyAnnotation",
"import java.io.Serializable;",
GeneratedImport.importGeneratedAnnotationType(),
"",
"@Generated(\"" + AutoAnnotationProcessor.class.getName() + "\")",
"final | AnnotationFactory |
java | assertj__assertj-core | assertj-tests/assertj-integration-tests/assertj-core-tests/src/test/java/org/assertj/tests/core/api/period/PeriodAssert_isPositive_Test.java | {
"start": 1086,
"end": 2111
} | class ____ {
@Test
void should_pass_if_period_is_positive() {
// GIVEN
Period period = Period.ofMonths(10);
// WHEN/THEN
then(period).isPositive();
}
@Test
void should_fail_when_period_is_null() {
// GIVEN
Period period = null;
// WHEN
final AssertionError code = expectAssertionError(() -> assertThat(period).isPositive());
// THEN
then(code).hasMessage(actualIsNull());
}
@Test
void should_fail_if_period_is_negative() {
// GIVEN
Period period = Period.ofMonths(-10);
// WHEN
final AssertionError code = expectAssertionError(() -> assertThat(period).isPositive());
// THEN
then(code).hasMessage(shouldBePositive(period).create());
}
@Test
void should_fail_if_period_is_zero() {
// GIVEN
Period period = Period.ZERO;
// WHEN
final AssertionError code = expectAssertionError(() -> assertThat(period).isPositive());
// THEN
then(code).hasMessage(shouldBePositive(period).create());
}
}
| PeriodAssert_isPositive_Test |
java | grpc__grpc-java | xds/src/test/java/io/grpc/xds/SharedCallCounterMapTest.java | {
"start": 1124,
"end": 2988
} | class ____ {
private static final String CLUSTER = "cluster-foo.googleapis.com";
private static final String EDS_SERVICE_NAME = null;
private final Map<String, Map<String, CounterReference>> counters = new HashMap<>();
private final SharedCallCounterMap map = new SharedCallCounterMap(counters);
@Test
public void sharedCounterInstance() {
AtomicLong counter1 = map.getOrCreate(CLUSTER, EDS_SERVICE_NAME);
AtomicLong counter2 = map.getOrCreate(CLUSTER, EDS_SERVICE_NAME);
assertThat(counter2).isSameInstanceAs(counter1);
}
@Test
public void autoCleanUp() {
@SuppressWarnings("UnusedVariable")
AtomicLong counter = map.getOrCreate(CLUSTER, EDS_SERVICE_NAME);
final CounterReference ref = counters.get(CLUSTER).get(EDS_SERVICE_NAME);
counter = null;
GcFinalization.awaitDone(new FinalizationPredicate() {
@SuppressWarnings("deprecation") // Use refersTo(null) once we require Java 17+
@Override
public boolean isDone() {
return ref.isEnqueued();
}
});
map.cleanQueue();
assertThat(counters).isEmpty();
}
@Test
public void gcAndRecreate() {
@SuppressWarnings("UnusedVariable") // assign to null for GC only
AtomicLong counter = map.getOrCreate(CLUSTER, EDS_SERVICE_NAME);
final CounterReference ref = counters.get(CLUSTER).get(EDS_SERVICE_NAME);
assertThat(counter.get()).isEqualTo(0);
counter = null;
GcFinalization.awaitDone(new FinalizationPredicate() {
@SuppressWarnings("deprecation") // Use refersTo(null) once we require Java 17+
@Override
public boolean isDone() {
return ref.isEnqueued();
}
});
map.getOrCreate(CLUSTER, EDS_SERVICE_NAME);
assertThat(counters.get(CLUSTER)).isNotNull();
assertThat(counters.get(CLUSTER).get(EDS_SERVICE_NAME)).isNotNull();
}
}
| SharedCallCounterMapTest |
java | grpc__grpc-java | alts/src/main/java/io/grpc/alts/internal/AesGcmHkdfAeadCrypter.java | {
"start": 1419,
"end": 4830
} | class ____ implements AeadCrypter {
private static final int KDF_KEY_LENGTH = 32;
// Rekey after 2^(2*8) = 2^16 operations by ignoring the first 2 nonce bytes for key derivation.
private static final int KDF_COUNTER_OFFSET = 2;
// Use remaining bytes of 64-bit counter included in nonce for key derivation.
private static final int KDF_COUNTER_LENGTH = 6;
private static final int NONCE_LENGTH = AesGcmAeadCrypter.NONCE_LENGTH;
private static final int KEY_LENGTH = KDF_KEY_LENGTH + NONCE_LENGTH;
private final byte[] kdfKey;
private final byte[] kdfCounter = new byte[KDF_COUNTER_LENGTH];
private final byte[] nonceMask;
private final byte[] nonceBuffer = new byte[NONCE_LENGTH];
private AeadCrypter aeadCrypter;
AesGcmHkdfAeadCrypter(byte[] key) {
checkArgument(key.length == KEY_LENGTH);
this.kdfKey = Arrays.copyOf(key, KDF_KEY_LENGTH);
this.nonceMask = Arrays.copyOfRange(key, KDF_KEY_LENGTH, KDF_KEY_LENGTH + NONCE_LENGTH);
}
@Override
public void encrypt(ByteBuffer ciphertext, ByteBuffer plaintext, byte[] nonce)
throws GeneralSecurityException {
maybeRekey(nonce);
maskNonce(nonceBuffer, nonceMask, nonce);
aeadCrypter.encrypt(ciphertext, plaintext, nonceBuffer);
}
@Override
public void encrypt(ByteBuffer ciphertext, ByteBuffer plaintext, ByteBuffer aad, byte[] nonce)
throws GeneralSecurityException {
maybeRekey(nonce);
maskNonce(nonceBuffer, nonceMask, nonce);
aeadCrypter.encrypt(ciphertext, plaintext, aad, nonceBuffer);
}
@Override
public void decrypt(ByteBuffer plaintext, ByteBuffer ciphertext, byte[] nonce)
throws GeneralSecurityException {
maybeRekey(nonce);
maskNonce(nonceBuffer, nonceMask, nonce);
aeadCrypter.decrypt(plaintext, ciphertext, nonceBuffer);
}
@Override
public void decrypt(ByteBuffer plaintext, ByteBuffer ciphertext, ByteBuffer aad, byte[] nonce)
throws GeneralSecurityException {
maybeRekey(nonce);
maskNonce(nonceBuffer, nonceMask, nonce);
aeadCrypter.decrypt(plaintext, ciphertext, aad, nonceBuffer);
}
private void maybeRekey(byte[] nonce) throws GeneralSecurityException {
if (aeadCrypter != null
&& arrayEqualOn(nonce, KDF_COUNTER_OFFSET, kdfCounter, 0, KDF_COUNTER_LENGTH)) {
return;
}
System.arraycopy(nonce, KDF_COUNTER_OFFSET, kdfCounter, 0, KDF_COUNTER_LENGTH);
int aeKeyLen = AesGcmAeadCrypter.getKeyLength();
byte[] aeKey = Arrays.copyOf(hkdfExpandSha256(kdfKey, kdfCounter), aeKeyLen);
aeadCrypter = new AesGcmAeadCrypter(aeKey);
}
private static void maskNonce(byte[] nonceBuffer, byte[] nonceMask, byte[] nonce) {
checkArgument(nonce.length == NONCE_LENGTH);
for (int i = 0; i < NONCE_LENGTH; i++) {
nonceBuffer[i] = (byte) (nonceMask[i] ^ nonce[i]);
}
}
private static byte[] hkdfExpandSha256(byte[] key, byte[] info) throws GeneralSecurityException {
Mac mac = Mac.getInstance("HMACSHA256");
mac.init(new SecretKeySpec(key, mac.getAlgorithm()));
mac.update(info);
mac.update((byte) 0x01);
return mac.doFinal();
}
private static boolean arrayEqualOn(byte[] a, int aPos, byte[] b, int bPos, int length) {
for (int i = 0; i < length; i++) {
if (a[aPos + i] != b[bPos + i]) {
return false;
}
}
return true;
}
static int getKeyLength() {
return KEY_LENGTH;
}
}
| AesGcmHkdfAeadCrypter |
java | apache__camel | dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/DataSetTestEndpointBuilderFactory.java | {
"start": 9839,
"end": 27909
} | interface ____
extends
EndpointProducerBuilder {
default DataSetTestEndpointBuilder basic() {
return (DataSetTestEndpointBuilder) this;
}
/**
* Sets whether to make a deep copy of the incoming Exchange when
* received at this mock endpoint.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer (advanced)
*
* @param copyOnExchange the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder copyOnExchange(boolean copyOnExchange) {
doSetProperty("copyOnExchange", copyOnExchange);
return this;
}
/**
* Sets whether to make a deep copy of the incoming Exchange when
* received at this mock endpoint.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer (advanced)
*
* @param copyOnExchange the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder copyOnExchange(String copyOnExchange) {
doSetProperty("copyOnExchange", copyOnExchange);
return this;
}
/**
* Sets whether assertIsSatisfied() should fail fast at the first
* detected failed expectation while it may otherwise wait for all
* expected messages to arrive before performing expectations
* verifications. Is by default true. Set to false to use behavior as in
* Camel 2.x.
*
* The option is a: <code>boolean</code> type.
*
* Default: true
* Group: producer (advanced)
*
* @param failFast the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder failFast(boolean failFast) {
doSetProperty("failFast", failFast);
return this;
}
/**
* Sets whether assertIsSatisfied() should fail fast at the first
* detected failed expectation while it may otherwise wait for all
* expected messages to arrive before performing expectations
* verifications. Is by default true. Set to false to use behavior as in
* Camel 2.x.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: true
* Group: producer (advanced)
*
* @param failFast the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder failFast(String failFast) {
doSetProperty("failFast", failFast);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder lazyStartProducer(boolean lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* Whether the producer should be started lazy (on the first message).
* By starting lazy you can use this to allow CamelContext and routes to
* startup in situations where a producer may otherwise fail during
* starting and cause the route to fail being started. By deferring this
* startup to be lazy then the startup failure can be handled during
* routing messages via Camel's routing error handlers. Beware that when
* the first message is processed then creating and starting the
* producer may take a little time and prolong the total processing time
* of the processing.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param lazyStartProducer the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder lazyStartProducer(String lazyStartProducer) {
doSetProperty("lazyStartProducer", lazyStartProducer);
return this;
}
/**
* To turn on logging when the mock receives an incoming message. This
* will log only one time at INFO level for the incoming message. For
* more detailed logging, then set the logger to DEBUG level for the
* org.apache.camel.component.mock.MockEndpoint class.
*
* The option is a: <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param log the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder log(boolean log) {
doSetProperty("log", log);
return this;
}
/**
* To turn on logging when the mock receives an incoming message. This
* will log only one time at INFO level for the incoming message. For
* more detailed logging, then set the logger to DEBUG level for the
* org.apache.camel.component.mock.MockEndpoint class.
*
* The option will be converted to a <code>boolean</code> type.
*
* Default: false
* Group: producer (advanced)
*
* @param log the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder log(String log) {
doSetProperty("log", log);
return this;
}
/**
* A number that is used to turn on throughput logging based on groups
* of the size.
*
* The option is a: <code>int</code> type.
*
* Group: producer (advanced)
*
* @param reportGroup the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder reportGroup(int reportGroup) {
doSetProperty("reportGroup", reportGroup);
return this;
}
/**
* A number that is used to turn on throughput logging based on groups
* of the size.
*
* The option will be converted to a <code>int</code> type.
*
* Group: producer (advanced)
*
* @param reportGroup the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder reportGroup(String reportGroup) {
doSetProperty("reportGroup", reportGroup);
return this;
}
/**
* Sets the minimum expected amount of time the assertIsSatisfied() will
* wait on a latch until it is satisfied.
*
* The option is a: <code>long</code> type.
*
* Group: producer (advanced)
*
* @param resultMinimumWaitTime the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder resultMinimumWaitTime(long resultMinimumWaitTime) {
doSetProperty("resultMinimumWaitTime", resultMinimumWaitTime);
return this;
}
/**
* Sets the minimum expected amount of time the assertIsSatisfied() will
* wait on a latch until it is satisfied.
*
* The option will be converted to a <code>long</code> type.
*
* Group: producer (advanced)
*
* @param resultMinimumWaitTime the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder resultMinimumWaitTime(String resultMinimumWaitTime) {
doSetProperty("resultMinimumWaitTime", resultMinimumWaitTime);
return this;
}
/**
* Sets the maximum amount of time the assertIsSatisfied() will wait on
* a latch until it is satisfied.
*
* The option is a: <code>long</code> type.
*
* Group: producer (advanced)
*
* @param resultWaitTime the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder resultWaitTime(long resultWaitTime) {
doSetProperty("resultWaitTime", resultWaitTime);
return this;
}
/**
* Sets the maximum amount of time the assertIsSatisfied() will wait on
* a latch until it is satisfied.
*
* The option will be converted to a <code>long</code> type.
*
* Group: producer (advanced)
*
* @param resultWaitTime the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder resultWaitTime(String resultWaitTime) {
doSetProperty("resultWaitTime", resultWaitTime);
return this;
}
/**
* Specifies to only retain the first nth number of received Exchanges.
* This is used when testing with big data, to reduce memory consumption
* by not storing copies of every Exchange this mock endpoint receives.
* Important: When using this limitation, then the getReceivedCounter()
* will still return the actual number of received message. For example
* if we have received 5000 messages and have configured to only retain
* the first 10 Exchanges, then the getReceivedCounter() will still
* return 5000 but there is only the first 10 Exchanges in the
* getExchanges() and getReceivedExchanges() methods. When using this
* method, then some of the other expectation methods is not supported,
* for example the expectedBodiesReceived(Object...) sets a expectation
* on the first number of bodies received. You can configure both
* retainFirst and retainLast options, to limit both the first and last
* received.
*
* The option is a: <code>int</code> type.
*
* Default: -1
* Group: producer (advanced)
*
* @param retainFirst the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder retainFirst(int retainFirst) {
doSetProperty("retainFirst", retainFirst);
return this;
}
/**
* Specifies to only retain the first nth number of received Exchanges.
* This is used when testing with big data, to reduce memory consumption
* by not storing copies of every Exchange this mock endpoint receives.
* Important: When using this limitation, then the getReceivedCounter()
* will still return the actual number of received message. For example
* if we have received 5000 messages and have configured to only retain
* the first 10 Exchanges, then the getReceivedCounter() will still
* return 5000 but there is only the first 10 Exchanges in the
* getExchanges() and getReceivedExchanges() methods. When using this
* method, then some of the other expectation methods is not supported,
* for example the expectedBodiesReceived(Object...) sets a expectation
* on the first number of bodies received. You can configure both
* retainFirst and retainLast options, to limit both the first and last
* received.
*
* The option will be converted to a <code>int</code> type.
*
* Default: -1
* Group: producer (advanced)
*
* @param retainFirst the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder retainFirst(String retainFirst) {
doSetProperty("retainFirst", retainFirst);
return this;
}
/**
* Specifies to only retain the last nth number of received Exchanges.
* This is used when testing with big data, to reduce memory consumption
* by not storing copies of every Exchange this mock endpoint receives.
* Important: When using this limitation, then the getReceivedCounter()
* will still return the actual number of received message. For example
* if we have received 5000 messages and have configured to only retain
* the last 20 Exchanges, then the getReceivedCounter() will still
* return 5000 but there is only the last 20 Exchanges in the
* getExchanges() and getReceivedExchanges() methods. When using this
* method, then some of the other expectation methods is not supported,
* for example the expectedBodiesReceived(Object...) sets a expectation
* on the first number of bodies received. You can configure both
* retainFirst and retainLast options, to limit both the first and last
* received.
*
* The option is a: <code>int</code> type.
*
* Default: -1
* Group: producer (advanced)
*
* @param retainLast the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder retainLast(int retainLast) {
doSetProperty("retainLast", retainLast);
return this;
}
/**
* Specifies to only retain the last nth number of received Exchanges.
* This is used when testing with big data, to reduce memory consumption
* by not storing copies of every Exchange this mock endpoint receives.
* Important: When using this limitation, then the getReceivedCounter()
* will still return the actual number of received message. For example
* if we have received 5000 messages and have configured to only retain
* the last 20 Exchanges, then the getReceivedCounter() will still
* return 5000 but there is only the last 20 Exchanges in the
* getExchanges() and getReceivedExchanges() methods. When using this
* method, then some of the other expectation methods is not supported,
* for example the expectedBodiesReceived(Object...) sets a expectation
* on the first number of bodies received. You can configure both
* retainFirst and retainLast options, to limit both the first and last
* received.
*
* The option will be converted to a <code>int</code> type.
*
* Default: -1
* Group: producer (advanced)
*
* @param retainLast the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder retainLast(String retainLast) {
doSetProperty("retainLast", retainLast);
return this;
}
/**
* Allows a sleep to be specified to wait to check that this mock really
* is empty when expectedMessageCount(int) is called with zero value.
*
* The option is a: <code>long</code> type.
*
* Group: producer (advanced)
*
* @param sleepForEmptyTest the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder sleepForEmptyTest(long sleepForEmptyTest) {
doSetProperty("sleepForEmptyTest", sleepForEmptyTest);
return this;
}
/**
* Allows a sleep to be specified to wait to check that this mock really
* is empty when expectedMessageCount(int) is called with zero value.
*
* The option will be converted to a <code>long</code> type.
*
* Group: producer (advanced)
*
* @param sleepForEmptyTest the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder sleepForEmptyTest(String sleepForEmptyTest) {
doSetProperty("sleepForEmptyTest", sleepForEmptyTest);
return this;
}
/**
* Maximum number of messages to keep in memory available for browsing.
* Use 0 for unlimited.
*
* The option is a: <code>int</code> type.
*
* Default: 100
* Group: advanced
*
* @param browseLimit the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder browseLimit(int browseLimit) {
doSetProperty("browseLimit", browseLimit);
return this;
}
/**
* Maximum number of messages to keep in memory available for browsing.
* Use 0 for unlimited.
*
* The option will be converted to a <code>int</code> type.
*
* Default: 100
* Group: advanced
*
* @param browseLimit the value to set
* @return the dsl builder
*/
default AdvancedDataSetTestEndpointBuilder browseLimit(String browseLimit) {
doSetProperty("browseLimit", browseLimit);
return this;
}
}
public | AdvancedDataSetTestEndpointBuilder |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.