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
quarkusio__quarkus
independent-projects/resteasy-reactive/server/vertx/src/test/java/org/jboss/resteasy/reactive/server/vertx/test/simple/SimpleQuarkusRestResource.java
{ "start": 1504, "end": 11374 }
class ____ { private static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0]; @Inject HelloService service; @GET public String get() { return "GET"; } @GET @Path("empty") public String empty() { return null; } @Path("sub") public Object subResource() { return new SubResource(); } @GET @Path("/hello") public String hello() { return service.sayHello(); } @GET @Path("{id}") public String get(@PathParam("id") String id) { return "GET:" + id; } @GET @Path("arrayHeaders") public String arrayHeaders(@HeaderParam("h1") String[] h1, @HeaderParam("h2") String[] h2, @HeaderParam("h3") Integer[] h3, @HeaderParam("h4") int[] h4) { return "h1: " + Arrays.toString(h1) + ", h2: " + Arrays.toString(h2) + ", h3: " + Arrays.toString(h3) + ", h4: " + Arrays.toString( h4); } @POST @Path("arrayForms") public String arrayForms(@FormParam("f1") String[] f1, @FormParam("f2") String[] f2, @FormParam("f3") Integer[] f3, @FormParam("f4") int[] f4) { return "f1: " + Arrays.toString(f1) + ", f2: " + Arrays.toString(f2) + ", f3: " + Arrays.toString(f3) + ", f4: " + Arrays.toString( f4); } @POST @Path("params/{p}") public String params(@PathParam("p") String p, @QueryParam("q") String q, @HeaderParam("h") int h, @HeaderParam("h2") char h2, @HeaderParam("h3") Character h3, @FormParam("f") String f) { return "params: p: " + p + ", q: " + q + ", h: " + h + ", h2: " + h2 + ", h3: " + h3 + ", f: " + f; } @POST public String post() { return "POST"; } @DELETE public String delete() { return "DELETE"; } @PUT public String put() { return "PUT"; } @PATCH public String patch() { return "PATCH"; } @OPTIONS public String options() { return "OPTIONS"; } @HEAD public Response head() { return Response.ok().header("Stef", "head").build(); } @GET @Path("/person") @Produces(MediaType.APPLICATION_JSON) public Person getPerson() { Person person = new Person(); person.setFirst("Bob"); person.setLast("Builder"); return person; } @GET @Path("/blocking") @Blocking public String blocking() { service.sayHello(); return String.valueOf(BlockingOperationSupport.isBlockingAllowed()); } @GET @Path("providers") public Response filters(@Context Providers providers) { // TODO: enhance this test return Response.ok().entity(providers.getExceptionMapper(TestException.class).getClass().getName()).build(); } @GET @Path("filters") public Response filters(@Context HttpHeaders headers, @RestHeader("filter-request") String header) { return Response.ok().header("filter-request", header).build(); } @GET @Path("feature-filters") public Response featureFilters(@Context HttpHeaders headers) { return Response.ok().header("feature-filter-request", headers.getHeaderString("feature-filter-request")).build(); } @GET @Path("dynamic-feature-filters") public Response dynamicFeatureFilters(@Context HttpHeaders headers) { return Response.ok().header("feature-filter-request", headers.getHeaderString("feature-filter-request")).build(); } @GET @Path("fooFilters") @Foo public Response fooFilters(@Context HttpHeaders headers) { return Response.ok().header("filter-request", headers.getHeaderString("filter-request")).build(); } @GET @Path("barFilters") @Bar public Response barFilters(@Context HttpHeaders headers) { return Response.ok().header("filter-request", headers.getHeaderString("filter-request")).build(); } @GET @Path("fooBarFilters") @Foo @Bar public Response fooBarFilters(@Context HttpHeaders headers) { return Response.ok().header("filter-request", headers.getHeaderString("filter-request")).build(); } @GET @Path("mapped-exception") public String mappedException() { TestException exception = new TestException(); exception.setStackTrace(EMPTY_STACK_TRACE); throw exception; } @GET @Path("feature-mapped-exception") public String featureMappedException() { FeatureMappedException exception = new FeatureMappedException(); exception.setStackTrace(EMPTY_STACK_TRACE); throw exception; } @GET @Path("unknown-exception") public String unknownException() { RuntimeException exception = new RuntimeException("OUCH"); exception.setStackTrace(EMPTY_STACK_TRACE); throw exception; } @GET @Path("web-application-exception") public String webApplicationException() { throw new WebApplicationException(Response.status(666).entity("OK").build()); } @GET @Path("writer") public TestClass writer() { return new TestClass(); } @GET @Path("uni-writer") public Uni<TestClass> uniWriter() { return Uni.createFrom().item(new TestClass()); } @GET @Path("fast-writer") @Produces("text/plain") public String fastWriter() { return "OK"; } @GET @Path("lookup-writer") public Object slowWriter() { return "OK"; } @GET @Path("writer/vertx-buffer") public Buffer vertxBuffer() { return Buffer.buffer("VERTX-BUFFER"); } @GET @Path("writer/mutiny-buffer") public io.vertx.mutiny.core.buffer.Buffer mutinyBuffer() { return io.vertx.mutiny.core.buffer.Buffer.buffer("MUTINY-BUFFER"); } @GET @Path("async/cs/ok") public CompletionStage<String> asyncCompletionStageOK() { return CompletableFuture.completedFuture("CS-OK"); } @GET @Path("async/cs/fail") public CompletionStage<String> asyncCompletionStageFail() { CompletableFuture<String> ret = new CompletableFuture<>(); ret.completeExceptionally(new TestException()); return ret; } @GET @Path("async/cf/ok") public CompletableFuture<String> asyncCompletableFutureOK() { return CompletableFuture.completedFuture("CF-OK"); } @GET @Path("async/cf/fail") public CompletableFuture<String> asyncCompletableFutureFail() { CompletableFuture<String> ret = new CompletableFuture<>(); ret.completeExceptionally(new TestException()); return ret; } @GET @Path("async/uni/ok") public Uni<String> asyncUniOK() { return Uni.createFrom().item("UNI-OK"); } @Produces(MediaType.APPLICATION_JSON) @GET @Path("async/uni/list") public Uni<List<Person>> asyncUniListJson() { Person person = new Person(); person.setFirst("Bob"); person.setLast("Builder"); return Uni.createFrom().item(Arrays.asList(person)); } @GET @Path("async/uni/fail") public Uni<String> asyncUniStageFail() { return Uni.createFrom().failure(new TestException()); } @GET @Path("pre-match") public String preMatchGet() { return "pre-match-get"; } @POST @Path("pre-match") public String preMatchPost() { return "pre-match-post"; } @GET @Path("request-response-params") public String requestAndResponseParams(@Context HttpServerRequest request, @Context HttpServerResponse response) { response.headers().add("dummy", "value"); return request.remoteAddress().host(); } @GET @Path("jax-rs-request") public String jaxRsRequest(@Context Request request) { return request.getMethod(); } @GET @Path("resource-info") public Response resourceInfo(@Context ResourceInfo resourceInfo, @Context HttpHeaders headers) { return Response.ok() .header("class-name", resourceInfo.getResourceClass().getSimpleName()) .header("method-name", headers.getHeaderString("method-name")) .build(); } @Path("form-map") @POST @Produces(MediaType.APPLICATION_FORM_URLENCODED) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public MultivaluedMap<String, String> map(MultivaluedMap<String, String> map) { return map; } @Path("jsonp-object") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) public String jsonpObject(JsonObject jsonbObject) { return jsonbObject.getString("k"); } @Path("jsonp-array") @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.TEXT_PLAIN) public Integer jsonpArray(JsonArray jsonArray) { return jsonArray.size(); } @Path("/bool") @POST @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public boolean bool(boolean bool) { return bool; } @Path("/trace") @TRACE public Response trace() { return Response.status(Response.Status.OK).build(); } @GET @Path("simplifiedResourceInfo") @Produces(MediaType.TEXT_PLAIN) public String simplifiedResourceInfo(@Context SimpleResourceInfo simplifiedResourceInfo) { return simplifiedResourceInfo.getResourceClass().getName() + "#" + simplifiedResourceInfo.getMethodName() + "-" + simplifiedResourceInfo.parameterTypes().length; } @GET @Path("bigDecimal/{val}") @Produces(MediaType.TEXT_PLAIN) public String bigDecimalConverter(BigDecimal val) { return val.toString(); } }
SimpleQuarkusRestResource
java
apache__camel
components/camel-jte/src/main/java/org/apache/camel/component/jte/JteEndpoint.java
{ "start": 1656, "end": 6029 }
class ____ extends ResourceEndpoint { @UriParam private boolean allowTemplateFromHeader; public JteEndpoint() { } public JteEndpoint(String endpointUri, Component component, String resourceUri) { super(endpointUri, component, resourceUri); } @Override public boolean isRemote() { return false; } @Override public void clearContentCache() { super.clearContentCache(); TemplateEngine template = getComponent().getTemplateEngine(); if (template != null) { template.clearCache(); template.cleanAll(); } } @Override public JteComponent getComponent() { return (JteComponent) super.getComponent(); } public boolean isAllowTemplateFromHeader() { return allowTemplateFromHeader; } /** * Whether to allow to use resource template from header or not (default false). * * Enabling this allows to specify dynamic templates via message header. However this can be seen as a potential * security vulnerability if the header is coming from a malicious user, so use this with care. */ public void setAllowTemplateFromHeader(boolean allowTemplateFromHeader) { this.allowTemplateFromHeader = allowTemplateFromHeader; } public JteEndpoint findOrCreateEndpoint(String uri, String newResourceUri) { String newUri = uri.replace(getResourceUri(), newResourceUri); log.debug("Getting endpoint with URI: {}", newUri); return getCamelContext().getEndpoint(newUri, JteEndpoint.class); } @Override protected void onExchange(Exchange exchange) throws Exception { String path = getResourceUri(); ObjectHelper.notNull(path, "resourceUri"); if (allowTemplateFromHeader) { String newResourceUri = exchange.getIn().getHeader(JteConstants.JTE_RESOURCE_URI, String.class); if (newResourceUri != null) { exchange.getIn().removeHeader(JteConstants.JTE_RESOURCE_URI); log.debug("{} set to {} creating new endpoint to handle exchange", JteConstants.JTE_RESOURCE_URI, newResourceUri); JteEndpoint newEndpoint = findOrCreateEndpoint(getEndpointUri(), newResourceUri); newEndpoint.onExchange(exchange); return; } } JteCodeResolver codeResolver = getComponent().getCodeResolver(); String name = getResourceUri(); String content; if (allowTemplateFromHeader) { content = exchange.getIn().getHeader(JteConstants.JTE_TEMPLATE, String.class); if (content != null) { // remove the header to avoid it being propagated in the routing exchange.getIn().removeHeader(JteConstants.JTE_TEMPLATE); // add template in code resolver so we can find it if (codeResolver != null) { name = exchange.getExchangeId(); codeResolver.addTemplateFromHeader(name, content); } } } else if (ResourceHelper.hasScheme(name)) { // name should not include scheme String uri = StringHelper.after(name, ":"); name = StringHelper.before(name, ":"); codeResolver.addPathMapping(name, uri); } Object dataModel = null; if (allowTemplateFromHeader) { dataModel = exchange.getIn().getHeader(JteConstants.JTE_DATA_MODEL, Object.class); } if (dataModel == null) { Model model = new Model(getCamelContext()); model.body = exchange.getMessage().getBody(); model.headers = exchange.getMessage().getHeaders(); if (isAllowContextMapAll()) { model.exchange = exchange; } dataModel = model; } // let JTE parse and generate the result in buffer TemplateEngine template = getComponent().getTemplateEngine(); TemplateOutput buffer = new StringOutput(); template.render(name, dataModel, buffer); // now lets store the result String s = buffer.toString(); // trim leading and ending empty lines s = s.trim(); ExchangeHelper.setInOutBodyPatternAware(exchange, s); } }
JteEndpoint
java
elastic__elasticsearch
x-pack/plugin/inference/src/test/java/org/elasticsearch/xpack/inference/services/elastic/request/ElasticInferenceServiceUnifiedChatCompletionRequestEntityTests.java
{ "start": 1303, "end": 9135 }
class ____ extends ESTestCase { private static final String ROLE = "user"; public void testModelUserFieldsSerialization() throws IOException { UnifiedCompletionRequest.Message message = new UnifiedCompletionRequest.Message( new UnifiedCompletionRequest.ContentString("Hello, world!"), ROLE, null, null ); var messageList = new ArrayList<UnifiedCompletionRequest.Message>(); messageList.add(message); var unifiedRequest = UnifiedCompletionRequest.of(messageList); UnifiedChatInput unifiedChatInput = new UnifiedChatInput(unifiedRequest, true); OpenAiChatCompletionModel model = createCompletionModel("test-url", "organizationId", "api-key", "test-endpoint", null); OpenAiUnifiedChatCompletionRequestEntity entity = new OpenAiUnifiedChatCompletionRequestEntity(unifiedChatInput, model); XContentBuilder builder = JsonXContent.contentBuilder(); entity.toXContent(builder, ToXContent.EMPTY_PARAMS); String jsonString = Strings.toString(builder); String expectedJson = """ { "messages": [ { "content": "Hello, world!", "role": "user" } ], "model": "test-endpoint", "n": 1, "stream": true, "stream_options": { "include_usage": true } } """; assertJsonEquals(jsonString, expectedJson); } public void testSerialization_NonStreaming_ForCompletion() throws IOException { // Test non-streaming case (used for COMPLETION task type) var unifiedChatInput = new UnifiedChatInput(List.of("What is 2+2?"), ROLE, false); var model = ElasticInferenceServiceCompletionModelTests.createModel("http://eis-gateway.com", "my-model-id"); var entity = new ElasticInferenceServiceUnifiedChatCompletionRequestEntity(unifiedChatInput, model.getServiceSettings().modelId()); XContentBuilder builder = JsonXContent.contentBuilder(); entity.toXContent(builder, ToXContent.EMPTY_PARAMS); String jsonString = Strings.toString(builder); String expectedJson = """ { "messages": [ { "content": "What is 2+2?", "role": "user" } ], "model": "my-model-id", "n": 1, "stream": false } """; assertJsonEquals(jsonString, expectedJson); } public void testSerialization_MultipleInputs_NonStreaming() throws IOException { // Test multiple inputs converted to messages (used for COMPLETION task type) var unifiedChatInput = new UnifiedChatInput(List.of("What is 2+2?", "What is the capital of France?"), ROLE, false); var model = ElasticInferenceServiceCompletionModelTests.createModel("http://eis-gateway.com", "my-model-id"); var entity = new ElasticInferenceServiceUnifiedChatCompletionRequestEntity(unifiedChatInput, model.getServiceSettings().modelId()); XContentBuilder builder = JsonXContent.contentBuilder(); entity.toXContent(builder, ToXContent.EMPTY_PARAMS); String jsonString = Strings.toString(builder); String expectedJson = """ { "messages": [ { "content": "What is 2+2?", "role": "user" }, { "content": "What is the capital of France?", "role": "user" } ], "model": "my-model-id", "n": 1, "stream": false } """; assertJsonEquals(jsonString, expectedJson); } public void testSerialization_EmptyInput_NonStreaming() throws IOException { var unifiedChatInput = new UnifiedChatInput(List.of(""), ROLE, false); var model = ElasticInferenceServiceCompletionModelTests.createModel("http://eis-gateway.com", "my-model-id"); var entity = new ElasticInferenceServiceUnifiedChatCompletionRequestEntity(unifiedChatInput, model.getServiceSettings().modelId()); XContentBuilder builder = JsonXContent.contentBuilder(); entity.toXContent(builder, ToXContent.EMPTY_PARAMS); String jsonString = Strings.toString(builder); String expectedJson = """ { "messages": [ { "content": "", "role": "user" } ], "model": "my-model-id", "n": 1, "stream": false } """; assertJsonEquals(jsonString, expectedJson); } public void testSerialization_AlwaysSetsNToOne_NonStreaming() throws IOException { // Verify n is always 1 regardless of number of inputs var unifiedChatInput = new UnifiedChatInput(List.of("input1", "input2", "input3"), ROLE, false); var model = ElasticInferenceServiceCompletionModelTests.createModel("http://eis-gateway.com", "my-model-id"); var entity = new ElasticInferenceServiceUnifiedChatCompletionRequestEntity(unifiedChatInput, model.getServiceSettings().modelId()); XContentBuilder builder = JsonXContent.contentBuilder(); entity.toXContent(builder, ToXContent.EMPTY_PARAMS); String jsonString = Strings.toString(builder); String expectedJson = """ { "messages": [ { "content": "input1", "role": "user" }, { "content": "input2", "role": "user" }, { "content": "input3", "role": "user" } ], "model": "my-model-id", "n": 1, "stream": false } """; assertJsonEquals(jsonString, expectedJson); } public void testSerialization_AllMessagesHaveUserRole_NonStreaming() throws IOException { // Verify all messages have "user" role when converting from simple inputs var unifiedChatInput = new UnifiedChatInput(List.of("first", "second", "third"), ROLE, false); var model = ElasticInferenceServiceCompletionModelTests.createModel("http://eis-gateway.com", "test-model"); var entity = new ElasticInferenceServiceUnifiedChatCompletionRequestEntity(unifiedChatInput, model.getServiceSettings().modelId()); XContentBuilder builder = JsonXContent.contentBuilder(); entity.toXContent(builder, ToXContent.EMPTY_PARAMS); String jsonString = Strings.toString(builder); String expectedJson = """ { "messages": [ { "content": "first", "role": "user" }, { "content": "second", "role": "user" }, { "content": "third", "role": "user" } ], "model": "test-model", "n": 1, "stream": false } """; assertJsonEquals(jsonString, expectedJson); } }
ElasticInferenceServiceUnifiedChatCompletionRequestEntityTests
java
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/context/request/async/StandardServletAsyncWebRequest.java
{ "start": 12543, "end": 17111 }
class ____ extends PrintWriter { private final PrintWriter delegate; private final StandardServletAsyncWebRequest asyncWebRequest; private LifecyclePrintWriter(PrintWriter delegate, StandardServletAsyncWebRequest asyncWebRequest) { super(delegate); this.delegate = delegate; this.asyncWebRequest = asyncWebRequest; } @Override public void flush() { int level = this.asyncWebRequest.tryObtainLock(); if (level > -1) { try { this.delegate.flush(); } finally { releaseLock(level); } } } @Override public void close() { int level = this.asyncWebRequest.tryObtainLock(); if (level > -1) { try { this.delegate.close(); } finally { releaseLock(level); } } } @Override public boolean checkError() { return this.delegate.checkError(); } @Override public void write(int c) { int level = this.asyncWebRequest.tryObtainLock(); if (level > -1) { try { this.delegate.write(c); } finally { releaseLock(level); } } } @Override public void write(char[] buf, int off, int len) { int level = this.asyncWebRequest.tryObtainLock(); if (level > -1) { try { this.delegate.write(buf, off, len); } finally { releaseLock(level); } } } @Override public void write(char[] buf) { this.delegate.write(buf); } @Override public void write(String s, int off, int len) { int level = this.asyncWebRequest.tryObtainLock(); if (level > -1) { try { this.delegate.write(s, off, len); } finally { releaseLock(level); } } } @Override public void write(String s) { this.delegate.write(s); } private void releaseLock(int level) { if (level > 0) { this.asyncWebRequest.stateLock.unlock(); } } // Plain delegates @Override public void print(boolean b) { this.delegate.print(b); } @Override public void print(char c) { this.delegate.print(c); } @Override public void print(int i) { this.delegate.print(i); } @Override public void print(long l) { this.delegate.print(l); } @Override public void print(float f) { this.delegate.print(f); } @Override public void print(double d) { this.delegate.print(d); } @Override public void print(char[] s) { this.delegate.print(s); } @Override public void print(String s) { this.delegate.print(s); } @Override public void print(Object obj) { this.delegate.print(obj); } @Override public void println() { this.delegate.println(); } @Override public void println(boolean x) { this.delegate.println(x); } @Override public void println(char x) { this.delegate.println(x); } @Override public void println(int x) { this.delegate.println(x); } @Override public void println(long x) { this.delegate.println(x); } @Override public void println(float x) { this.delegate.println(x); } @Override public void println(double x) { this.delegate.println(x); } @Override public void println(char[] x) { this.delegate.println(x); } @Override public void println(String x) { this.delegate.println(x); } @Override public void println(Object x) { this.delegate.println(x); } @Override public PrintWriter printf(String format, Object... args) { return this.delegate.printf(format, args); } @Override public PrintWriter printf(Locale l, String format, Object... args) { return this.delegate.printf(l, format, args); } @Override public PrintWriter format(String format, Object... args) { return this.delegate.format(format, args); } @Override public PrintWriter format(Locale l, String format, Object... args) { return this.delegate.format(l, format, args); } @Override public PrintWriter append(CharSequence csq) { return this.delegate.append(csq); } @Override public PrintWriter append(CharSequence csq, int start, int end) { return this.delegate.append(csq, start, end); } @Override public PrintWriter append(char c) { return this.delegate.append(c); } } /** * Represents a state for {@link StandardServletAsyncWebRequest} to be in. * <p><pre> * +------ NEW * | | * | v * | ASYNC ----> + * | | | * | v | * +----> ERROR | * | | * v | * COMPLETED <---+ * </pre> * @since 5.3.33 */ private
LifecyclePrintWriter
java
elastic__elasticsearch
x-pack/plugin/inference/src/main/java/org/elasticsearch/xpack/inference/services/huggingface/completion/HuggingFaceChatCompletionServiceSettings.java
{ "start": 1933, "end": 6980 }
class ____ extends FilteredXContentObject implements ServiceSettings, HuggingFaceRateLimitServiceSettings { public static final String NAME = "hugging_face_completion_service_settings"; // At the time of writing HuggingFace hasn't posted the default rate limit for inference endpoints so the value his is only a guess // 3000 requests per minute private static final RateLimitSettings DEFAULT_RATE_LIMIT_SETTINGS = new RateLimitSettings(3000); private static final TransportVersion ML_INFERENCE_HUGGING_FACE_CHAT_COMPLETION_ADDED = TransportVersion.fromName( "ml_inference_hugging_face_chat_completion_added" ); /** * Creates a new instance of {@link HuggingFaceChatCompletionServiceSettings} from a map of settings. * @param map the map of settings * @param context the context for parsing the settings * @return a new instance of {@link HuggingFaceChatCompletionServiceSettings} */ public static HuggingFaceChatCompletionServiceSettings fromMap(Map<String, Object> map, ConfigurationParseContext context) { ValidationException validationException = new ValidationException(); String modelId = extractOptionalString(map, MODEL_ID, ModelConfigurations.SERVICE_SETTINGS, validationException); var uri = extractUri(map, URL, validationException); RateLimitSettings rateLimitSettings = RateLimitSettings.of( map, DEFAULT_RATE_LIMIT_SETTINGS, validationException, HuggingFaceService.NAME, context ); if (validationException.validationErrors().isEmpty() == false) { throw validationException; } return new HuggingFaceChatCompletionServiceSettings(modelId, uri, rateLimitSettings); } private final String modelId; private final URI uri; private final RateLimitSettings rateLimitSettings; public HuggingFaceChatCompletionServiceSettings(@Nullable String modelId, String url, @Nullable RateLimitSettings rateLimitSettings) { this(modelId, createUri(url), rateLimitSettings); } public HuggingFaceChatCompletionServiceSettings(@Nullable String modelId, URI uri, @Nullable RateLimitSettings rateLimitSettings) { this.modelId = modelId; this.uri = uri; this.rateLimitSettings = Objects.requireNonNullElse(rateLimitSettings, DEFAULT_RATE_LIMIT_SETTINGS); } /** * Creates a new instance of {@link HuggingFaceChatCompletionServiceSettings} from a stream input. * @param in the stream input * @throws IOException if an I/O error occurs */ public HuggingFaceChatCompletionServiceSettings(StreamInput in) throws IOException { this.modelId = in.readOptionalString(); this.uri = createUri(in.readString()); this.rateLimitSettings = new RateLimitSettings(in); } @Override public RateLimitSettings rateLimitSettings() { return rateLimitSettings; } @Override public URI uri() { return uri; } @Override public String modelId() { return modelId; } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); toXContentFragmentOfExposedFields(builder, params); builder.endObject(); return builder; } @Override protected XContentBuilder toXContentFragmentOfExposedFields(XContentBuilder builder, Params params) throws IOException { if (modelId != null) { builder.field(MODEL_ID, modelId); } builder.field(URL, uri.toString()); rateLimitSettings.toXContent(builder, params); return builder; } @Override public String getWriteableName() { return NAME; } @Override public TransportVersion getMinimalSupportedVersion() { assert false : "should never be called when supportsVersion is used"; return ML_INFERENCE_HUGGING_FACE_CHAT_COMPLETION_ADDED; } @Override public boolean supportsVersion(TransportVersion version) { return version.supports(ML_INFERENCE_HUGGING_FACE_CHAT_COMPLETION_ADDED); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeOptionalString(modelId); out.writeString(uri.toString()); rateLimitSettings.writeTo(out); } @Override public boolean equals(Object object) { if (this == object) return true; if (object == null || getClass() != object.getClass()) return false; HuggingFaceChatCompletionServiceSettings that = (HuggingFaceChatCompletionServiceSettings) object; return Objects.equals(modelId, that.modelId) && Objects.equals(uri, that.uri) && Objects.equals(rateLimitSettings, that.rateLimitSettings); } @Override public int hashCode() { return Objects.hash(modelId, uri, rateLimitSettings); } }
HuggingFaceChatCompletionServiceSettings
java
google__guava
android/guava/src/com/google/common/base/Optional.java
{ "start": 2827, "end": 3070 }
class ____ added for Java 8. The two classes are extremely similar, but incompatible (they cannot * share a common supertype). <i>All</i> known differences are listed either here or with the * relevant methods below. * * <ul> * <li>This
was
java
alibaba__nacos
naming/src/test/java/com/alibaba/nacos/naming/core/v2/client/manager/ClientManagerDelegateTest.java
{ "start": 1736, "end": 5501 }
class ____ { private final String connectionId = System.currentTimeMillis() + "_127.0.0.1_80"; private final String connectionIdForV6 = System.currentTimeMillis() + "_0:0:0:0:0:0:0:1_80"; private final String ephemeralIpPortId = "127.0.0.1:80#true"; private final String persistentIpPortId = "127.0.0.1:80#false"; @Mock private ConnectionBasedClientManager connectionBasedClientManager; @Mock private EphemeralIpPortClientManager ephemeralIpPortClientManager; @Mock private PersistentIpPortClientManager persistentIpPortClientManager; private ClientManagerDelegate delegate; @BeforeEach void setUp() throws Exception { delegate = new ClientManagerDelegate(connectionBasedClientManager, ephemeralIpPortClientManager, persistentIpPortClientManager); when(connectionBasedClientManager.contains(connectionId)).thenReturn(true); when(ephemeralIpPortClientManager.contains(ephemeralIpPortId)).thenReturn(true); when(persistentIpPortClientManager.contains(persistentIpPortId)).thenReturn(true); when(connectionBasedClientManager.allClientId()).thenReturn(Collections.singletonList(connectionId)); when(ephemeralIpPortClientManager.allClientId()).thenReturn(Collections.singletonList(ephemeralIpPortId)); when(persistentIpPortClientManager.allClientId()).thenReturn(Collections.singletonList(persistentIpPortId)); } @Test void testChooseConnectionClient() { delegate.getClient(connectionId); verify(connectionBasedClientManager).getClient(connectionId); verify(ephemeralIpPortClientManager, never()).getClient(connectionId); verify(persistentIpPortClientManager, never()).getClient(connectionId); } @Test void testChooseConnectionClientForV6() { delegate.getClient(connectionIdForV6); verify(connectionBasedClientManager).getClient(connectionIdForV6); verify(ephemeralIpPortClientManager, never()).getClient(connectionIdForV6); verify(persistentIpPortClientManager, never()).getClient(connectionIdForV6); } @Test void testChooseEphemeralIpPortClient() { DistroClientVerifyInfo verify = new DistroClientVerifyInfo(ephemeralIpPortId, 0); delegate.verifyClient(verify); verify(connectionBasedClientManager, never()).verifyClient(verify); verify(ephemeralIpPortClientManager).verifyClient(verify); verify(persistentIpPortClientManager, never()).verifyClient(verify); } @Test void testChoosePersistentIpPortClient() { DistroClientVerifyInfo verify = new DistroClientVerifyInfo(persistentIpPortId, 0); delegate.verifyClient(verify); verify(connectionBasedClientManager, never()).verifyClient(verify); verify(ephemeralIpPortClientManager, never()).verifyClient(verify); verify(persistentIpPortClientManager).verifyClient(verify); } @Test void testContainsConnectionId() { assertTrue(delegate.contains(connectionId)); } @Test void testContainsConnectionIdFailed() { assertFalse(delegate.contains(connectionIdForV6)); } @Test void testContainsEphemeralIpPortId() { assertTrue(delegate.contains(ephemeralIpPortId)); } @Test void testContainsPersistentIpPortId() { assertTrue(delegate.contains(persistentIpPortId)); } @Test void testAllClientId() { Collection<String> actual = delegate.allClientId(); assertTrue(actual.contains(connectionId)); assertTrue(actual.contains(ephemeralIpPortId)); assertTrue(actual.contains(persistentIpPortId)); } }
ClientManagerDelegateTest
java
FasterXML__jackson-core
src/main/java/tools/jackson/core/io/CharacterEscapes.java
{ "start": 366, "end": 3095 }
class ____ implements java.io.Serializable // since 2.1 { /** * Value used for lookup tables to indicate that matching characters * do not need to be escaped. */ public final static int ESCAPE_NONE = 0; /** * Value used for lookup tables to indicate that matching characters * are to be escaped using standard escaping; for JSON this means * (for example) using "backslash - u" escape method. */ public final static int ESCAPE_STANDARD = -1; /** * Value used for lookup tables to indicate that matching characters * will need custom escapes; and that another call * to {@link #getEscapeSequence} is needed to figure out exact escape * sequence to output. */ public final static int ESCAPE_CUSTOM = -2; /** * Method generators can call to get lookup table for determining * escape handling for first 128 characters of Unicode (ASCII * characters. Caller is not to modify contents of this array, since * this is expected to be a shared copy. * * @return Array with size of at least 128, where first 128 entries * have either one of <code>ESCAPE_xxx</code> constants, or non-zero positive * integer (meaning of which is data format specific; for JSON it means * that combination of backslash and character with that value is to be used) * to indicate that specific escape sequence is to be used. */ public abstract int[] getEscapeCodesForAscii(); /** * Method generators can call to get lookup table for determining * exact escape sequence to use for given character. * It can be called for any character, but typically is called for * either for ASCII characters for which custom escape * sequence is needed; or for any non-ASCII character. * * @param ch Character to look escape sequence for * * @return Escape sequence to use for the character, if any; {@code null} if not */ public abstract SerializableString getEscapeSequence(int ch); /** * Helper method that can be used to get a copy of standard JSON * escape definitions; this is useful when just wanting to slightly * customize definitions. Caller can modify this array as it sees * fit and usually returns modified instance via {@link #getEscapeCodesForAscii} * * @return Set of escapes, similar to {@link #getEscapeCodesForAscii()} (array of * 128 {@code int}s), but a copy that caller owns and is free to modify */ public static int[] standardAsciiEscapesForJSON() { int[] esc = CharTypes.get7BitOutputEscapes(); return Arrays.copyOf(esc, esc.length); } }
CharacterEscapes
java
apache__camel
components/camel-atom/src/main/java/org/apache/camel/component/atom/AtomUtils.java
{ "start": 1284, "end": 2145 }
class ____ { public static List<Item> readItems(CamelContext camelContext, String uri, RssReader reader, boolean sort) throws IOException { if (ResourceHelper.isHttpUri(uri)) { return reader .read(uri) .sorted(sort ? ItemComparator.oldestItemFirst() : Comparator.naturalOrder()) .collect(Collectors.toList()); } else { InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, uri); try { return reader .read(is) .sorted(sort ? ItemComparator.oldestItemFirst() : Comparator.naturalOrder()) .collect(Collectors.toList()); } finally { IOHelper.close(is); } } } }
AtomUtils
java
grpc__grpc-java
core/src/test/java/io/grpc/internal/AutoConfiguredLoadBalancerFactoryTest.java
{ "start": 28691, "end": 29645 }
class ____ extends ForwardingLoadBalancerHelper { final SynchronizationContext syncContext = new SynchronizationContext( new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { throw new AssertionError(e); } }); final FakeClock fakeClock = new FakeClock(); @Override protected Helper delegate() { return null; } @Override public ChannelLogger getChannelLogger() { return channelLogger; } @Override public void updateBalancingState(ConnectivityState newState, SubchannelPicker newPicker) { // noop } @Override public SynchronizationContext getSynchronizationContext() { return syncContext; } @Override public ScheduledExecutorService getScheduledExecutorService() { return fakeClock.getScheduledExecutorService(); } } private static
TestHelper
java
google__dagger
javatests/dagger/functional/cycle/Cycles.java
{ "start": 1768, "end": 1864 }
class ____ { public final D d; @Inject E(D d) { this.d = d; } } static
E
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/engine/support/hierarchical/ParallelExecutionIntegrationTests.java
{ "start": 29122, "end": 29334 }
class ____ extends BarrierTestCase { static final CyclicBarrier GLOBAL_BARRIER = new CyclicBarrier(3); @Override CyclicBarrier getBarrier() { return GLOBAL_BARRIER; } } static
ParallelClassesTestCase
java
elastic__elasticsearch
x-pack/plugin/logsdb/qa/rolling-upgrade/src/javaRestTest/java/org/elasticsearch/upgrades/MatchOnlyTextRollingUpgradeIT.java
{ "start": 684, "end": 1485 }
class ____ extends AbstractStringTypeRollingUpgradeIT { public MatchOnlyTextRollingUpgradeIT(@Name("upgradedNodes") int upgradedNodes) { super(upgradedNodes); } @Override public String stringType() { return "match_only_text"; } @Override protected void testIndexing(boolean shouldIncludeKeywordMultiField) throws Exception { assumeTrue( "Match only text block loader bug is present and fix is not present in this cluster", TextFieldMapper.multiFieldsNotStoredByDefaultIndexVersionCheck(getOldClusterIndexVersion()) == oldClusterHasFeature( MapperFeatures.MATCH_ONLY_TEXT_BLOCK_LOADER_FIX ) ); super.testIndexing(shouldIncludeKeywordMultiField); } }
MatchOnlyTextRollingUpgradeIT
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/containermanager/linux/runtime/runc/RuncContainerExecutorConfig.java
{ "start": 13099, "end": 14263 }
class ____ { final private List<String> effective; final private List<String> bounding; final private List<String> inheritable; final private List<String> permitted; final private List<String> ambient; public List<String> getEffective() { return effective; } public List<String> getBounding() { return bounding; } public List<String> getInheritable() { return inheritable; } public List<String> getPermitted() { return permitted; } public List<String> getAmbient() { return ambient; } public Capabilities(List<String> effective, List<String> bounding, List<String> inheritable, List<String> permitted, List<String> ambient) { this.effective = effective; this.bounding = bounding; this.inheritable = inheritable; this.permitted = permitted; this.ambient = ambient; } public Capabilities() { this(null, null, null, null, null); } } /** * This
Capabilities
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/lookup/ConcurrentSegmentSourceProvider.java
{ "start": 1359, "end": 4467 }
class ____ implements SourceProvider { private final Function<SourceFilter, SourceLoader> sourceLoaderProvider; private final SourceLoader sourceLoader; private final StoredFieldLoader storedFieldLoader; private final Map<Object, Leaf> leaves = ConcurrentCollections.newConcurrentMap(); private final boolean isStoredSource; ConcurrentSegmentSourceProvider(MappingLookup lookup, SourceFilter filter, SourceFieldMetrics metrics) { this.sourceLoaderProvider = sourceFilter -> lookup.newSourceLoader(sourceFilter, metrics); this.sourceLoader = sourceLoaderProvider.apply(filter); // we force a sequential reader here since it is used during query execution where documents are scanned sequentially this.isStoredSource = lookup.isSourceSynthetic() == false; this.storedFieldLoader = StoredFieldLoader.create(isStoredSource, sourceLoader.requiredStoredFields(), true); } private ConcurrentSegmentSourceProvider(ConcurrentSegmentSourceProvider source, SourceFilter filter) { assert source.isStoredSource == false; this.sourceLoaderProvider = source.sourceLoaderProvider; this.isStoredSource = source.isStoredSource; this.sourceLoader = source.sourceLoaderProvider.apply(filter); // Also re-initialize stored field loader: this.storedFieldLoader = StoredFieldLoader.create(isStoredSource, sourceLoader.requiredStoredFields(), true); } @Override public Source getSource(LeafReaderContext ctx, int doc) throws IOException { final Object id = ctx.id(); var leaf = leaves.get(id); if (leaf == null) { leaf = new Leaf(sourceLoader.leaf(ctx.reader(), null), storedFieldLoader.getLoader(ctx, null)); var existing = leaves.put(id, leaf); assert existing == null : "unexpected source provider [" + existing + "]"; } else if (isStoredSource == false && doc < leaf.doc) { // When queries reference the same runtime field in multiple clauses, each clause re-reads the values from the source in // increasing docId order. So the last docId accessed by the first clause is higher than the first docId read by the second // clause. This is okay for stored source, as stored fields do not restrict the order that docIds that can be accessed. // But with synthetic source, field values may come from doc values, which require than docIds only be read in increasing order. // To handle this, we detect lower docIds and create a new doc value reader for each clause. leaf = new Leaf(sourceLoader.leaf(ctx.reader(), null), storedFieldLoader.getLoader(ctx, null)); leaves.put(id, leaf); } return leaf.getSource(ctx, doc); } @Override public SourceProvider optimizedSourceProvider(SourceFilter sourceFilter) { if (isStoredSource) { return this; } else { return new ConcurrentSegmentSourceProvider(this, sourceFilter); } } private static
ConcurrentSegmentSourceProvider
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/NullOptionalTest.java
{ "start": 1414, "end": 1690 }
class ____ { void a(Optional<Object> o) {} void test() { a(null); } } """) .addOutputLines( "Test.java", """ import java.util.Optional;
Test
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/JSR166TestCase.java
{ "start": 31318, "end": 31508 }
class ____ extends CheckedInterruptedRunnable { @Override protected void realRun() throws InterruptedException { delay(SHORT_DELAY_MS); } } public
ShortInterruptedRunnable
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/event/ApplicationContextEventTests.java
{ "start": 25211, "end": 25358 }
class ____ implements MyOrderedListenerIfc<MyEvent> { @Override public int getOrder() { return 1; } } public static
MyOrderedListenerBase
java
apache__kafka
group-coordinator/src/test/java/org/apache/kafka/coordinator/group/streams/TopologyMetadataTest.java
{ "start": 1825, "end": 4635 }
class ____ { private CoordinatorMetadataImage metadataImage; private SortedMap<String, ConfiguredSubtopology> subtopologyMap; private TopologyMetadata topologyMetadata; @BeforeEach void setUp() { metadataImage = new KRaftCoordinatorMetadataImage(new MetadataImageBuilder() .addTopic(Uuid.randomUuid(), "source_topic", 3) .addTopic(Uuid.randomUuid(), "repartition_source_topic", 4) .build()); subtopologyMap = new TreeMap<>(); topologyMetadata = new TopologyMetadata(metadataImage, subtopologyMap); } @Test void testMetadataImage() { assertEquals(metadataImage, topologyMetadata.metadataImage()); } @Test void testTopology() { assertEquals(subtopologyMap, topologyMetadata.subtopologyMap()); } @Test void testIsStateful() { ConfiguredInternalTopic internalTopic = mock(ConfiguredInternalTopic.class); ConfiguredSubtopology subtopology1 = mock(ConfiguredSubtopology.class); ConfiguredSubtopology subtopology2 = mock(ConfiguredSubtopology.class); subtopologyMap.put("subtopology1", subtopology1); subtopologyMap.put("subtopology2", subtopology2); when(subtopology1.stateChangelogTopics()).thenReturn(Map.of("state_changelog_topic", internalTopic)); when(subtopology2.stateChangelogTopics()).thenReturn(Map.of()); assertTrue(topologyMetadata.isStateful("subtopology1")); assertFalse(topologyMetadata.isStateful("subtopology2")); } @Test void testMaxNumInputPartitions() { ConfiguredSubtopology subtopology = mock(ConfiguredSubtopology.class); subtopologyMap.put("subtopology1", subtopology); when(subtopology.numberOfTasks()).thenReturn(4); assertEquals(4, topologyMetadata.maxNumInputPartitions("subtopology1")); } @Test void testSubtopologies() { ConfiguredSubtopology subtopology1 = mock(ConfiguredSubtopology.class); ConfiguredSubtopology subtopology2 = mock(ConfiguredSubtopology.class); subtopologyMap.put("subtopology1", subtopology1); subtopologyMap.put("subtopology2", subtopology2); List<String> expectedSubtopologies = List.of("subtopology1", "subtopology2"); assertEquals(expectedSubtopologies, topologyMetadata.subtopologies()); } @Test void testIsStatefulThrowsExceptionWhenSubtopologyIdDoesNotExist() { assertThrows(NoSuchElementException.class, () -> topologyMetadata.isStateful("non_existent_subtopology")); } @Test void testMaxNumInputPartitionsThrowsExceptionWhenSubtopologyIdDoesNotExist() { assertThrows(NoSuchElementException.class, () -> topologyMetadata.maxNumInputPartitions("non_existent_subtopology")); } }
TopologyMetadataTest
java
spring-projects__spring-framework
spring-beans/src/test/java/org/springframework/beans/factory/DefaultListableBeanFactoryTests.java
{ "start": 146857, "end": 147137 }
class ____ implements FactoryBean<TestBean> { @Override public TestBean getObject() { return new TestBean("fromHighestPrecedenceTestBeanFactoryBean"); } @Override public Class<?> getObjectType() { return TestBean.class; } } }
HighestPrecedenceTestBeanFactoryBean
java
apache__logging-log4j2
log4j-core/src/main/java/org/apache/logging/log4j/core/layout/StringBuilderEncoder.java
{ "start": 1743, "end": 4472 }
class ____ which cannot be garbage collected if a thread pool * threadlocal still has a reference to it. * * Using just one ThreadLocal instead of three separate ones is an optimization: {@link ThreadLocal.ThreadLocalMap} * is polluted less, {@link ThreadLocal.ThreadLocalMap#get()} is called only once on each call to {@link #encode} * instead of three times. */ private final ThreadLocal<Object[]> threadLocal = new ThreadLocal<>(); private final Charset charset; private final int charBufferSize; private final int byteBufferSize; public StringBuilderEncoder(final Charset charset) { this(charset, Constants.ENCODER_CHAR_BUFFER_SIZE, Constants.ENCODER_BYTE_BUFFER_SIZE); } public StringBuilderEncoder(final Charset charset, final int charBufferSize, final int byteBufferSize) { this.charBufferSize = charBufferSize; this.byteBufferSize = byteBufferSize; this.charset = Objects.requireNonNull(charset, "charset"); } @Override public void encode(final StringBuilder source, final ByteBufferDestination destination) { try { final Object[] threadLocalState = getThreadLocalState(); final CharsetEncoder charsetEncoder = (CharsetEncoder) threadLocalState[0]; final CharBuffer charBuffer = (CharBuffer) threadLocalState[1]; final ByteBuffer byteBuffer = (ByteBuffer) threadLocalState[2]; TextEncoderHelper.encodeText(charsetEncoder, charBuffer, byteBuffer, source, destination); } catch (final Exception ex) { logEncodeTextException(ex, source); TextEncoderHelper.encodeTextFallBack(charset, source, destination); } } private Object[] getThreadLocalState() { Object[] threadLocalState = threadLocal.get(); if (threadLocalState == null) { threadLocalState = new Object[] { charset.newEncoder() .onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE), CharBuffer.allocate(charBufferSize), ByteBuffer.allocate(byteBufferSize) }; threadLocal.set(threadLocalState); } else { ((CharsetEncoder) threadLocalState[0]).reset(); ((CharBuffer) threadLocalState[1]).clear(); ((ByteBuffer) threadLocalState[2]).clear(); } return threadLocalState; } private static void logEncodeTextException(final Exception ex, final StringBuilder text) { StatusLogger.getLogger().error("Recovering from StringBuilderEncoder.encode('{}') error: {}", text, ex, ex); } }
loader
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/plugin/SqlStatsRequest.java
{ "start": 1038, "end": 1645 }
class ____ extends AbstractTransportRequest { boolean includeStats; NodeStatsRequest(StreamInput in) throws IOException { super(in); includeStats = in.readBoolean(); } NodeStatsRequest(SqlStatsRequest request) { includeStats = request.includeStats(); } public boolean includeStats() { return includeStats; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBoolean(includeStats); } } }
NodeStatsRequest
java
elastic__elasticsearch
libs/x-content/src/main/java/org/elasticsearch/xcontent/XContent.java
{ "start": 770, "end": 4372 }
interface ____ { /** * The type this content handles and produces. */ XContentType type(); /** * @return {@code true} if this {@link XContent} can be sent in bulk, delimited by the byte returned by {@link #bulkSeparator()}, or * {@code false} if this {@link XContent} does not support a delimited bulk format (in which case {@link #bulkSeparator()} throws an * exception. * <p> * In practice, this is {@code true} for content with canonical type {@link XContentType#JSON} or {@link XContentType#SMILE} and * {@code false} for content with canonical type {@link XContentType#CBOR} or {@link XContentType#YAML}. */ boolean hasBulkSeparator(); /** * @return a {@link byte} that separates items in a bulk request that uses this {@link XContent}. * @throws RuntimeException if this {@link XContent} does not support a delimited bulk format. See {@link #hasBulkSeparator()}. */ byte bulkSeparator(); @Deprecated boolean detectContent(byte[] bytes, int offset, int length); @Deprecated boolean detectContent(CharSequence chars); /** * Creates a new generator using the provided output stream. */ default XContentGenerator createGenerator(OutputStream os) throws IOException { return createGenerator(os, Collections.emptySet(), Collections.emptySet()); } /** * Creates a new generator using the provided output stream and some inclusive and/or exclusive filters. When both exclusive and * inclusive filters are provided, the underlying generator will first use exclusion filters to remove fields and then will check the * remaining fields against the inclusive filters. * * @param os the output stream * @param includes the inclusive filters: only fields and objects that match the inclusive filters will be written to the output. * @param excludes the exclusive filters: only fields and objects that don't match the exclusive filters will be written to the output. */ XContentGenerator createGenerator(OutputStream os, Set<String> includes, Set<String> excludes) throws IOException; /** * Creates a parser over the provided string content. */ XContentParser createParser(XContentParserConfiguration config, String content) throws IOException; /** * Creates a parser over the provided input stream. */ XContentParser createParser(XContentParserConfiguration config, InputStream is) throws IOException; /** * Creates a parser over the provided input stream. * @deprecated Use {@link #createParser(XContentParserConfiguration, InputStream)} */ @Deprecated default XContentParser createParser(NamedXContentRegistry registry, DeprecationHandler deprecationHandler, InputStream is) throws IOException { return createParser(XContentParserConfiguration.EMPTY.withRegistry(registry).withDeprecationHandler(deprecationHandler), is); } /** * Creates a parser over the provided bytes. */ default XContentParser createParser(XContentParserConfiguration config, byte[] data) throws IOException { return createParser(config, data, 0, data.length); } /** * Creates a parser over the provided bytes. */ XContentParser createParser(XContentParserConfiguration config, byte[] data, int offset, int length) throws IOException; /** * Creates a parser over the provided reader. */ XContentParser createParser(XContentParserConfiguration config, Reader reader) throws IOException; }
XContent
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/common/HdfsServerConstants.java
{ "start": 11324, "end": 13182 }
enum ____ { /** * Block construction completed.<br> * The block has at least the configured minimal replication number * of {@link ReplicaState#FINALIZED} replica(s), and is not going to be * modified. * NOTE, in some special cases, a block may be forced to COMPLETE state, * even if it doesn't have required minimal replications. */ COMPLETE, /** * The block is under construction.<br> * It has been recently allocated for write or append. */ UNDER_CONSTRUCTION, /** * The block is under recovery.<br> * When a file lease expires its last block may not be {@link #COMPLETE} * and needs to go through a recovery procedure, * which synchronizes the existing replicas contents. */ UNDER_RECOVERY, /** * The block is committed.<br> * The client reported that all bytes are written to data-nodes * with the given generation stamp and block length, but no * {@link ReplicaState#FINALIZED} * replicas has yet been reported by data-nodes themselves. */ COMMITTED } String NAMENODE_LEASE_HOLDER = "HDFS_NameNode"; String CRYPTO_XATTR_ENCRYPTION_ZONE = "raw.hdfs.crypto.encryption.zone"; String CRYPTO_XATTR_FILE_ENCRYPTION_INFO = "raw.hdfs.crypto.file.encryption.info"; String SECURITY_XATTR_UNREADABLE_BY_SUPERUSER = "security.hdfs.unreadable.by.superuser"; String XATTR_ERASURECODING_POLICY = "system.hdfs.erasurecoding.policy"; String XATTR_SNAPSHOT_DELETED = "system.hdfs.snapshot.deleted"; String XATTR_SATISFY_STORAGE_POLICY = "user.hdfs.sps"; Path MOVER_ID_PATH = new Path("/system/mover.id"); long BLOCK_GROUP_INDEX_MASK = 15; byte MAX_BLOCKS_IN_GROUP = 16; // maximum bandwidth per datanode 1TB/sec. long MAX_BANDWIDTH_PER_DATANODE = 1099511627776L; }
BlockUCState
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/SealedTypesWithTypedDeserializationTest.java
{ "start": 2723, "end": 2834 }
class ____ no useful info @JsonTypeInfo(use=Id.CLASS, include=As.WRAPPER_ARRAY) static abstract sealed
with
java
micronaut-projects__micronaut-core
inject/src/main/java/io/micronaut/context/event/BeanInitializedEventListener.java
{ "start": 1316, "end": 1871 }
interface ____<T> extends EventListener { /** * <p>Fired when a bean is instantiated but the {@link jakarta.annotation.PostConstruct} initialization hooks have not * yet been called and in this case of bean {@link jakarta.inject.Provider} instances the * {@link jakarta.inject.Provider#get()} method has not yet been invoked.</p> * * @param event The bean initializing event * @return The bean or a replacement bean of the same type */ T onInitialized(BeanInitializingEvent<T> event); }
BeanInitializedEventListener
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/security/RuleBasedLdapGroupsMapping.java
{ "start": 1428, "end": 1860 }
class ____ extends LdapGroupsMapping { public static final String CONVERSION_RULE_KEY = LDAP_CONFIG_PREFIX + ".conversion.rule"; private static final String CONVERSION_RULE_DEFAULT = "none"; private static final Logger LOG = LoggerFactory.getLogger(RuleBasedLdapGroupsMapping.class); private Rule rule; /** * Supported rules applicable for group name modification. */ private
RuleBasedLdapGroupsMapping
java
alibaba__nacos
consistency/src/test/java/com/alibaba/nacos/consistency/snapshot/LocalFileMetaTest.java
{ "start": 910, "end": 1209 }
class ____ { private LocalFileMeta fileMeta; @BeforeEach void setUp() { fileMeta = new LocalFileMeta(); } @Test void testAppendAndGet() { fileMeta.append("key", "value"); assertEquals("value", fileMeta.get("key")); } }
LocalFileMetaTest
java
micronaut-projects__micronaut-core
module-info-runtime/src/test/java/io/micronaut/module/info/runtime/ServiceLoaderDefinedModule.java
{ "start": 756, "end": 1085 }
class ____ extends AbstractMicronautModuleInfo { public ServiceLoaderDefinedModule() { super("io.micronaut:micronaut-dummy", "dummy", "Dummy test module defined as a service", "1.0", null, null, Set.of() ); } }
ServiceLoaderDefinedModule
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/support/jsse/BaseSSLContextParameters.java
{ "start": 35196, "end": 35845 }
interface ____<T> { /** * Configures a {@code T} based on the related configuration options. The return value from this method may be * {@code object} or it may be a decorated instance there of. Consequently, any subsequent actions on * {@code object} must be performed using the returned value. * * @param object the object to configure * @return {@code object} or a decorated instance there of */ T configure(T object); } /** * Makes a decorated {@link SSLContext} appear as a normal {@code SSLContext}. */ protected static final
Configurer
java
apache__flink
flink-datastream/src/main/java/org/apache/flink/datastream/impl/extension/window/context/DefaultOneInputWindowContext.java
{ "start": 2327, "end": 5270 }
class ____<K, IN, W extends Window> implements OneInputWindowContext<IN> { /** * The current processing window. An instance should be set every time before accessing * window-related attributes, data, and state. */ @Nullable private W window; /** Use to retrieve state associated with windows. */ private final WindowStateStore<K, W> windowStateStore; /** The state utilized for storing window data. */ private final AppendingState<IN, StateIterator<IN>, Iterable<IN>> windowState; public DefaultOneInputWindowContext( @Nullable W window, AppendingState<IN, StateIterator<IN>, Iterable<IN>> windowState, WindowProcessFunction windowProcessFunction, AbstractAsyncStateStreamOperator<?> operator, TypeSerializer<W> windowSerializer, boolean isMergingWindow) { this.window = window; this.windowState = windowState; this.windowStateStore = new WindowStateStore<>( windowProcessFunction, operator, windowSerializer, isMergingWindow); } public void setWindow(W window) { this.window = window; } @Override public long getStartTime() { if (window instanceof TimeWindow) { return ((TimeWindow) window).getStart(); } return -1; } @Override public long getEndTime() { if (window instanceof TimeWindow) { return ((TimeWindow) window).getEnd(); } return -1; } @Override public <T> Optional<ListState<T>> getWindowState(ListStateDeclaration<T> stateDeclaration) throws Exception { return windowStateStore.getWindowState(stateDeclaration, window); } @Override public <KEY, V> Optional<MapState<KEY, V>> getWindowState( MapStateDeclaration<KEY, V> stateDeclaration) throws Exception { return windowStateStore.getWindowState(stateDeclaration, window); } @Override public <T> Optional<ValueState<T>> getWindowState(ValueStateDeclaration<T> stateDeclaration) throws Exception { return windowStateStore.getWindowState(stateDeclaration, window); } @Override public <T> Optional<ReducingState<T>> getWindowState( ReducingStateDeclaration<T> stateDeclaration) throws Exception { return windowStateStore.getWindowState(stateDeclaration, window); } @Override public <T, ACC, OUT> Optional<AggregatingState<T, OUT>> getWindowState( AggregatingStateDeclaration<T, ACC, OUT> stateDeclaration) throws Exception { return windowStateStore.getWindowState(stateDeclaration, window); } @Override public void putRecord(IN record) { windowState.add(record); } @Override public Iterable<IN> getAllRecords() { return windowState.get(); } }
DefaultOneInputWindowContext
java
apache__camel
core/camel-console/src/generated/java/org/apache/camel/impl/console/JvmDevConsoleConfigurer.java
{ "start": 707, "end": 2802 }
class ____ extends org.apache.camel.support.component.PropertyConfigurerSupport implements GeneratedPropertyConfigurer, ExtendedPropertyConfigurerGetter { private static final Map<String, Object> ALL_OPTIONS; static { Map<String, Object> map = new CaseInsensitiveMap(); map.put("CamelContext", org.apache.camel.CamelContext.class); map.put("ShowClasspath", boolean.class); ALL_OPTIONS = map; } @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { org.apache.camel.impl.console.JvmDevConsole target = (org.apache.camel.impl.console.JvmDevConsole) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "camelcontext": case "camelContext": target.setCamelContext(property(camelContext, org.apache.camel.CamelContext.class, value)); return true; case "showclasspath": case "showClasspath": target.setShowClasspath(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { return ALL_OPTIONS; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "camelcontext": case "camelContext": return org.apache.camel.CamelContext.class; case "showclasspath": case "showClasspath": return boolean.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { org.apache.camel.impl.console.JvmDevConsole target = (org.apache.camel.impl.console.JvmDevConsole) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "camelcontext": case "camelContext": return target.getCamelContext(); case "showclasspath": case "showClasspath": return target.isShowClasspath(); default: return null; } } }
JvmDevConsoleConfigurer
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/blob/PermanentBlobCache.java
{ "start": 2455, "end": 16125 }
class ____ { /** Number of references to a job. */ public int references = 0; /** * Timestamp in milliseconds when any job data should be cleaned up (no cleanup for * non-positive values). */ public long keepUntil = -1; } private static final int DEFAULT_SIZE_LIMIT_MB = 100; /** Map to store the number of references to a specific job. */ private final Map<JobID, RefCount> jobRefCounters = new HashMap<>(); /** Time interval (ms) to run the cleanup task; also used as the default TTL. */ private final long cleanupInterval; /** Timer task to execute the cleanup at regular intervals. */ private final Timer cleanupTimer; private final BlobCacheSizeTracker blobCacheSizeTracker; @VisibleForTesting public PermanentBlobCache( final Configuration blobClientConfig, final File storageDir, final BlobView blobView, @Nullable final InetSocketAddress serverAddress) throws IOException { this(blobClientConfig, Reference.owned(storageDir), blobView, serverAddress); } @VisibleForTesting public PermanentBlobCache( final Configuration blobClientConfig, final File storageDir, final BlobView blobView, @Nullable final InetSocketAddress serverAddress, BlobCacheSizeTracker blobCacheSizeTracker) throws IOException { this( blobClientConfig, Reference.owned(storageDir), blobView, serverAddress, blobCacheSizeTracker); } /** * Instantiates a new cache for permanent BLOBs which are also available in an HA store. * * @param blobClientConfig global configuration * @param storageDir storage directory for the cached blobs * @param blobView (distributed) HA blob store file system to retrieve files from first * @param serverAddress address of the {@link BlobServer} to use for fetching files from or * {@code null} if none yet * @throws IOException thrown if the (local or distributed) file storage cannot be created or is * not usable */ public PermanentBlobCache( final Configuration blobClientConfig, final Reference<File> storageDir, final BlobView blobView, @Nullable final InetSocketAddress serverAddress) throws IOException { this( blobClientConfig, storageDir, blobView, serverAddress, new BlobCacheSizeTracker(MemorySize.ofMebiBytes(DEFAULT_SIZE_LIMIT_MB).getBytes())); } @VisibleForTesting public PermanentBlobCache( final Configuration blobClientConfig, final Reference<File> storageDir, final BlobView blobView, @Nullable final InetSocketAddress serverAddress, BlobCacheSizeTracker blobCacheSizeTracker) throws IOException { super( blobClientConfig, storageDir, blobView, LoggerFactory.getLogger(PermanentBlobCache.class), serverAddress); // Initializing the clean up task this.cleanupTimer = new Timer(true); this.cleanupInterval = blobClientConfig.get(BlobServerOptions.CLEANUP_INTERVAL) * 1000; this.cleanupTimer.schedule( new PermanentBlobCleanupTask(), cleanupInterval, cleanupInterval); this.blobCacheSizeTracker = blobCacheSizeTracker; registerDetectedJobs(); } private void registerDetectedJobs() throws IOException { if (storageDir.deref().exists()) { final Collection<JobID> jobIds = BlobUtils.listExistingJobs(storageDir.deref().toPath()); final long expiryTimeout = System.currentTimeMillis() + cleanupInterval; for (JobID jobId : jobIds) { registerJobWithExpiry(jobId, expiryTimeout); } } } private void registerJobWithExpiry(JobID jobId, long expiryTimeout) { checkNotNull(jobId); synchronized (jobRefCounters) { final RefCount refCount = jobRefCounters.computeIfAbsent(jobId, ignored -> new RefCount()); refCount.keepUntil = expiryTimeout; } } /** * Registers use of job-related BLOBs. * * <p>Using any other method to access BLOBs, e.g. {@link #getFile}, is only valid within calls * to <tt>registerJob(JobID)</tt> and {@link #releaseJob(JobID)}. * * @param jobId ID of the job this blob belongs to * @see #releaseJob(JobID) */ @Override public void registerJob(JobID jobId) { checkNotNull(jobId); synchronized (jobRefCounters) { RefCount ref = jobRefCounters.get(jobId); if (ref == null) { ref = new RefCount(); jobRefCounters.put(jobId, ref); } else { // reset cleanup timeout ref.keepUntil = -1; } ++ref.references; } } /** * Unregisters use of job-related BLOBs and allow them to be released. * * @param jobId ID of the job this blob belongs to * @see #registerJob(JobID) */ @Override public void releaseJob(JobID jobId) { checkNotNull(jobId); synchronized (jobRefCounters) { RefCount ref = jobRefCounters.get(jobId); if (ref == null || ref.references == 0) { log.warn( "improper use of releaseJob() without a matching number of registerJob() calls for jobId " + jobId); return; } --ref.references; if (ref.references == 0) { ref.keepUntil = System.currentTimeMillis() + cleanupInterval; } } } public int getNumberOfReferenceHolders(JobID jobId) { checkNotNull(jobId); synchronized (jobRefCounters) { RefCount ref = jobRefCounters.get(jobId); if (ref == null) { return 0; } else { return ref.references; } } } /** * Returns the path to a local copy of the file associated with the provided job ID and blob * key. * * <p>We will first attempt to serve the BLOB from the local storage. If the BLOB is not in * there, we will try to download it from the HA store, or directly from the {@link BlobServer}. * * @param jobId ID of the job this blob belongs to * @param key blob key associated with the requested file * @return The path to the file. * @throws java.io.FileNotFoundException if the BLOB does not exist; * @throws IOException if any other error occurs when retrieving the file */ @Override public File getFile(JobID jobId, PermanentBlobKey key) throws IOException { checkNotNull(jobId); return getFileInternal(jobId, key); } /** * Returns the content of the file for the BLOB with the provided job ID the blob key. * * <p>The method will first attempt to serve the BLOB from the local cache. If the BLOB is not * in the cache, the method will try to download it from the HA store, or directly from the * {@link BlobServer}. * * <p>Compared to {@code getFile}, {@code readFile} makes sure that the file is fully read in * the same write lock as the file is accessed. This avoids the scenario that the path is * returned as the file is deleted concurrently by other threads. * * @param jobId ID of the job this blob belongs to * @param blobKey BLOB key associated with the requested file * @return The content of the BLOB. * @throws java.io.FileNotFoundException if the BLOB does not exist; * @throws IOException if any other error occurs when retrieving the file. */ @Override public byte[] readFile(JobID jobId, PermanentBlobKey blobKey) throws IOException { checkNotNull(jobId); checkNotNull(blobKey); final File localFile = BlobUtils.getStorageLocation(storageDir.deref(), jobId, blobKey); readWriteLock.readLock().lock(); try { if (localFile.exists()) { blobCacheSizeTracker.update(jobId, blobKey); return FileUtils.readAllBytes(localFile.toPath()); } } finally { readWriteLock.readLock().unlock(); } // first try the distributed blob store (if available) // use a temporary file (thread-safe without locking) File incomingFile = createTemporaryFilename(); try { try { if (blobView.get(jobId, blobKey, incomingFile)) { // now move the temp file to our local cache atomically readWriteLock.writeLock().lock(); try { checkLimitAndMoveFile(incomingFile, jobId, blobKey, localFile, log, null); return FileUtils.readAllBytes(localFile.toPath()); } finally { readWriteLock.writeLock().unlock(); } } } catch (Exception e) { log.info( "Failed to copy from blob store. Downloading from BLOB server instead.", e); } final InetSocketAddress currentServerAddress = serverAddress; if (currentServerAddress != null) { // fallback: download from the BlobServer BlobClient.downloadFromBlobServer( jobId, blobKey, incomingFile, currentServerAddress, blobClientConfig, numFetchRetries); readWriteLock.writeLock().lock(); try { checkLimitAndMoveFile(incomingFile, jobId, blobKey, localFile, log, null); return FileUtils.readAllBytes(localFile.toPath()); } finally { readWriteLock.writeLock().unlock(); } } else { throw new IOException( "Cannot download from BlobServer, because the server address is unknown."); } } finally { // delete incomingFile from a failed download if (!incomingFile.delete() && incomingFile.exists()) { log.warn( "Could not delete the staging file {} for blob key {} and job {}.", incomingFile, blobKey, jobId); } } } private void checkLimitAndMoveFile( File incomingFile, JobID jobId, BlobKey blobKey, File localFile, Logger log, @Nullable BlobStore blobStore) throws IOException { // Check the size limit and delete the files that exceeds the limit final long sizeOfIncomingFile = incomingFile.length(); final List<Tuple2<JobID, BlobKey>> blobsToDelete = blobCacheSizeTracker.checkLimit(sizeOfIncomingFile); for (Tuple2<JobID, BlobKey> key : blobsToDelete) { if (deleteFile(key.f0, key.f1)) { blobCacheSizeTracker.untrack(key); } } // Move the file and register it to the tracker BlobUtils.moveTempFileToStore(incomingFile, jobId, blobKey, localFile, log, blobStore); blobCacheSizeTracker.track(jobId, blobKey, localFile.length()); } /** * Delete the blob file with the given key. * * @param jobId ID of the job this blob belongs to (or <tt>null</tt> if job-unrelated) * @param blobKey The key of the desired BLOB. */ private boolean deleteFile(JobID jobId, BlobKey blobKey) { final File localFile = new File( BlobUtils.getStorageLocationPath( storageDir.deref().getAbsolutePath(), jobId, blobKey)); if (!localFile.delete() && localFile.exists()) { log.warn( "Failed to delete locally cached BLOB {} at {}", blobKey, localFile.getAbsolutePath()); return false; } return true; } /** * Returns a file handle to the file associated with the given blob key on the blob server. * * @param jobId ID of the job this blob belongs to (or <tt>null</tt> if job-unrelated) * @param key identifying the file * @return file handle to the file * @throws IOException if creating the directory fails */ @VisibleForTesting public File getStorageLocation(JobID jobId, BlobKey key) throws IOException { checkNotNull(jobId); return BlobUtils.getStorageLocation(storageDir.deref(), jobId, key); } /** * Returns the job reference counters - for testing purposes only! * * @return job reference counters (internal state!) */ @VisibleForTesting Map<JobID, RefCount> getJobRefCounters() { return jobRefCounters; } /** * Cleanup task which is executed periodically to delete BLOBs whose ref-counter reached * <tt>0</tt>. */
RefCount
java
qos-ch__slf4j
slf4j-api/src/test/java/org/slf4j/rule/RunInNewThreadRule.java
{ "start": 1647, "end": 2283 }
class ____ implements TestRule { @Override public Statement apply(Statement base, Description description) { RunInNewThread desiredAnnotaton = description.getAnnotation(RunInNewThread.class); if (desiredAnnotaton == null) { System.out.println("test "+ description.getMethodName() +" not annotated"); return base; } else { long timeout = desiredAnnotaton.timeout(); System.out.println("running "+ description.getMethodName() +" in separate tjread"); return new RunInNewThreadStatement(base, timeout); } } }
RunInNewThreadRule
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestLocalDFS.java
{ "start": 1364, "end": 1419 }
interface ____ a single node * mini-cluster. */ public
in
java
apache__maven
impl/maven-xml/src/test/java/org/apache/maven/internal/xml/XmlNodeImplTest.java
{ "start": 1654, "end": 30318 }
class ____ { @Test void testCombineChildrenAppend() throws Exception { String lhs = "<configuration>\n" + " <plugins>\n" + " <plugin>\n" + " <groupId>foo.bar</groupId>\n" + " <artifactId>foo-bar-plugin</artifactId>\n" + " <configuration>\n" + " <plugins>\n" + " <plugin>\n" + " <groupId>org.apache.maven.plugins</groupId>\n" + " <artifactId>maven-compiler-plugin</artifactId>\n" + " </plugin>\n" + " <plugin>\n" + " <groupId>org.apache.maven.plugins</groupId>\n" + " <artifactId>maven-surefire-plugin</artifactId>\n" + " <foo>\n" + " <properties combine.children=\"append\">\n" + " <property>\n" + " <name>prop2</name>\n" + " <value>value2</value>\n" + " </property>\n" + " </properties>\n" + " </foo>\n" + " </plugin>\n" + " </plugins>\n" + " </configuration>\n" + " </plugin>\n" + " </plugins>\n" + "</configuration>"; String rhs = "<configuration>\n" + " <plugins>\n" + " <plugin>\n" + " <groupId>foo.bar</groupId>\n" + " <artifactId>foo-bar-plugin</artifactId>\n" + " <configuration>\n" + " <plugins>\n" + " <plugin>\n" + " <groupId>org.apache.maven.plugins</groupId>\n" + " <artifactId>maven-compiler-plugin</artifactId>\n" + " <bar>\n" + " <value>foo</value>\n" + " </bar>\n" + " </plugin>\n" + " <plugin>\n" + " <groupId>org.apache.maven.plugins</groupId>\n" + " <artifactId>maven-surefire-plugin</artifactId>\n" + " <foo>\n" + " <properties>\n" + " <property>\n" + " <name>prop1</name>\n" + " <value>value1</value>\n" + " </property>\n" + " </properties>\n" + " </foo>\n" + " </plugin>\n" + " </plugins>\n" + " </configuration>\n" + " </plugin>\n" + " </plugins>\n" + "</configuration>"; String result = "<configuration>\n" + " <plugins>\n" + " <plugin>\n" + " <groupId>foo.bar</groupId>\n" + " <artifactId>foo-bar-plugin</artifactId>\n" + " <configuration>\n" + " <plugins>\n" + " <plugin>\n" + " <groupId>org.apache.maven.plugins</groupId>\n" + " <artifactId>maven-compiler-plugin</artifactId>\n" + " <bar>\n" + " <value>foo</value>\n" + " </bar>\n" + " </plugin>\n" + " <plugin>\n" + " <groupId>org.apache.maven.plugins</groupId>\n" + " <artifactId>maven-surefire-plugin</artifactId>\n" + " <foo>\n" + " <properties combine.children=\"append\">\n" + " <property>\n" + " <name>prop1</name>\n" + " <value>value1</value>\n" + " </property>\n" + " <property>\n" + " <name>prop2</name>\n" + " <value>value2</value>\n" + " </property>\n" + " </properties>\n" + " </foo>\n" + " </plugin>\n" + " </plugins>\n" + " </configuration>\n" + " </plugin>\n" + " </plugins>\n" + "</configuration>"; XmlNode leftDom = toXmlNode(lhs); XmlNode rightDom = toXmlNode(rhs); XmlNode mergeResult = XmlService.merge(leftDom, rightDom); assertEquals(toXmlNode(result).toString(), mergeResult.toString()); assertEquals(toXmlNode(result), mergeResult); } @Test void testAppend() throws Exception { String lhs = """ <?xml version="1.0" encoding="UTF-8"?> <compilerArgs combine.children="append"> <arg>-Xmaxerrs</arg> <arg>100</arg> <arg>-Xmaxwarns</arg> <arg>100</arg> </compilerArgs> """; String result = """ <?xml version="1.0" encoding="UTF-8"?> <compilerArgs combine.children="append"> <arg>-Xmaxerrs</arg> <arg>100</arg> <arg>-Xmaxwarns</arg> <arg>100</arg> <arg>-Xmaxerrs</arg> <arg>100</arg> <arg>-Xmaxwarns</arg> <arg>100</arg> </compilerArgs>"""; XmlNode dom = toXmlNode(lhs); XmlNode res = toXmlNode(result); XmlNode mergeResult1 = XmlService.merge(dom, dom, false); assertEquals(res, mergeResult1); XmlNode mergeResult2 = XmlService.merge(dom, dom, (Boolean) null); assertEquals(res, mergeResult2); XmlNode mergeResult3 = XmlService.merge(dom, dom, true); assertEquals(dom, mergeResult3); } /** * <p>testCombineId.</p> * * @throws java.lang.Exception if any. */ @Test void testCombineId() throws Exception { String lhs = "<props>" + "<property combine.id='LHS-ONLY'><name>LHS-ONLY</name><value>LHS</value></property>" + "<property combine.id='TOOVERWRITE'><name>TOOVERWRITE</name><value>LHS</value></property>" + "</props>"; String rhs = "<props>" + "<property combine.id='RHS-ONLY'><name>RHS-ONLY</name><value>RHS</value></property>" + "<property combine.id='TOOVERWRITE'><name>TOOVERWRITE</name><value>RHS</value></property>" + "</props>"; XmlNode leftDom = XmlService.read(new StringReader(lhs), new FixedInputLocationBuilder("left")); XmlNode rightDom = XmlService.read(new StringReader(rhs), new FixedInputLocationBuilder("right")); XmlNode mergeResult = XmlService.merge(leftDom, rightDom, true); assertEquals(3, getChildren(mergeResult, "property").size()); XmlNode p0 = getNthChild(mergeResult, "property", 0); assertEquals("LHS-ONLY", p0.child("name").value()); assertEquals("left", p0.child("name").inputLocation()); assertEquals("LHS", p0.child("value").value()); assertEquals("left", p0.child("value").inputLocation()); XmlNode p1 = getNthChild(mergeResult, "property", 1); assertEquals( "TOOVERWRITE", getNthChild(mergeResult, "property", 1).child("name").value()); assertEquals("left", p1.child("name").inputLocation()); assertEquals( "LHS", getNthChild(mergeResult, "property", 1).child("value").value()); assertEquals("left", p1.child("value").inputLocation()); XmlNode p2 = getNthChild(mergeResult, "property", 2); assertEquals( "RHS-ONLY", getNthChild(mergeResult, "property", 2).child("name").value()); assertEquals("right", p2.child("name").inputLocation()); assertEquals( "RHS", getNthChild(mergeResult, "property", 2).child("value").value()); assertEquals("right", p2.child("value").inputLocation()); } /** * <p>testCombineKeys.</p> * * @throws java.lang.Exception if any. */ @Test void testCombineKeys() throws Exception { String lhs = "<props combine.keys='key'>" + "<property key=\"LHS-ONLY\"><name>LHS-ONLY</name><value>LHS</value></property>" + "<property combine.keys='name'><name>TOOVERWRITE</name><value>LHS</value></property>" + "</props>"; String rhs = "<props combine.keys='key'>" + "<property key=\"RHS-ONLY\"><name>RHS-ONLY</name><value>RHS</value></property>" + "<property combine.keys='name'><name>TOOVERWRITE</name><value>RHS</value></property>" + "</props>"; XmlNode leftDom = XmlService.read(new StringReader(lhs), new FixedInputLocationBuilder("left")); XmlNode rightDom = XmlService.read(new StringReader(rhs), new FixedInputLocationBuilder("right")); XmlNode mergeResult = XmlService.merge(leftDom, rightDom, true); assertEquals(3, getChildren(mergeResult, "property").size()); XmlNode p0 = getNthChild(mergeResult, "property", 0); assertEquals("LHS-ONLY", p0.child("name").value()); assertEquals("left", p0.child("name").inputLocation()); assertEquals("LHS", p0.child("value").value()); assertEquals("left", p0.child("value").inputLocation()); XmlNode p1 = getNthChild(mergeResult, "property", 1); assertEquals( "TOOVERWRITE", getNthChild(mergeResult, "property", 1).child("name").value()); assertEquals("left", p1.child("name").inputLocation()); assertEquals( "LHS", getNthChild(mergeResult, "property", 1).child("value").value()); assertEquals("left", p1.child("value").inputLocation()); XmlNode p2 = getNthChild(mergeResult, "property", 2); assertEquals( "RHS-ONLY", getNthChild(mergeResult, "property", 2).child("name").value()); assertEquals("right", p2.child("name").inputLocation()); assertEquals( "RHS", getNthChild(mergeResult, "property", 2).child("value").value()); assertEquals("right", p2.child("value").inputLocation()); } @Test void testPreserveDominantBlankValue() throws XMLStreamException, IOException { String lhs = "<parameter xml:space=\"preserve\"> </parameter>"; String rhs = "<parameter>recessive</parameter>"; XmlNode leftDom = XmlService.read(new StringReader(lhs), new FixedInputLocationBuilder("left")); XmlNode rightDom = XmlService.read(new StringReader(rhs), new FixedInputLocationBuilder("right")); XmlNode mergeResult = XmlService.merge(leftDom, rightDom, true); assertEquals(" ", mergeResult.value()); } @Test void testPreserveDominantEmptyNode() throws XMLStreamException, IOException { String lhs = "<parameter></parameter>"; String rhs = "<parameter>recessive</parameter>"; XmlNode leftDom = XmlService.read(new StringReader(lhs), new FixedInputLocationBuilder("left")); XmlNode rightDom = XmlService.read(new StringReader(rhs), new FixedInputLocationBuilder("right")); XmlNode mergeResult = XmlService.merge(leftDom, rightDom, true); assertEquals("", mergeResult.value()); } @Test void testPreserveDominantEmptyNode2() throws XMLStreamException, IOException { String lhs = "<parameter/>"; String rhs = "<parameter>recessive</parameter>"; XmlNode leftDom = XmlService.read(new StringReader(lhs), new FixedInputLocationBuilder("left")); XmlNode rightDom = XmlService.read(new StringReader(rhs), new FixedInputLocationBuilder("right")); XmlNode mergeResult = XmlService.merge(leftDom, rightDom, true); assertNull(mergeResult.value()); } /** * <p>testShouldPerformAppendAtFirstSubElementLevel.</p> */ @Test void testShouldPerformAppendAtFirstSubElementLevel() throws XMLStreamException { String lhs = """ <top combine.children="append"> <topsub1>t1s1Value</topsub1> <topsub1>t1s2Value</topsub1> </top> """; String rhs = """ <top> <topsub1>t2s1Value</topsub1> <topsub1>t2s2Value</topsub1> </top> """; XmlNode leftDom = XmlService.read(new StringReader(lhs), new FixedInputLocationBuilder("left")); XmlNode rightDom = XmlService.read(new StringReader(rhs), new FixedInputLocationBuilder("right")); XmlNode result = XmlService.merge(leftDom, rightDom); assertEquals(4, getChildren(result, "topsub1").size()); assertEquals("t2s1Value", getChildren(result, "topsub1").get(0).value()); assertEquals("t2s2Value", getChildren(result, "topsub1").get(1).value()); assertEquals("t1s1Value", getChildren(result, "topsub1").get(2).value()); assertEquals("t1s2Value", getChildren(result, "topsub1").get(3).value()); assertEquals("left", result.inputLocation()); assertEquals("right", getChildren(result, "topsub1").get(0).inputLocation()); assertEquals("right", getChildren(result, "topsub1").get(1).inputLocation()); assertEquals("left", getChildren(result, "topsub1").get(2).inputLocation()); assertEquals("left", getChildren(result, "topsub1").get(3).inputLocation()); } /** * <p>testShouldOverrideAppendAndDeepMerge.</p> */ @Test void testShouldOverrideAppendAndDeepMerge() { // create the dominant DOM Xpp3Dom t1 = new Xpp3Dom("top"); t1.setAttribute(Xpp3Dom.CHILDREN_COMBINATION_MODE_ATTRIBUTE, Xpp3Dom.CHILDREN_COMBINATION_APPEND); t1.setInputLocation("t1top"); Xpp3Dom t1s1 = new Xpp3Dom("topsub1"); t1s1.setValue("t1s1Value"); t1s1.setInputLocation("t1s1"); t1.addChild(t1s1); // create the recessive DOM Xpp3Dom t2 = new Xpp3Dom("top"); t2.setInputLocation("t2top"); Xpp3Dom t2s1 = new Xpp3Dom("topsub1"); t2s1.setValue("t2s1Value"); t2s1.setInputLocation("t2s1"); t2.addChild(t2s1); // merge and check results. Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(t1, t2, Boolean.TRUE); assertEquals(1, result.getChildren("topsub1").length); assertEquals("t1s1Value", result.getChildren("topsub1")[0].getValue()); assertEquals("t1top", result.getInputLocation()); assertEquals("t1s1", result.getChildren("topsub1")[0].getInputLocation()); } /** * <p>testShouldPerformSelfOverrideAtTopLevel.</p> */ @Test void testShouldPerformSelfOverrideAtTopLevel() { // create the dominant DOM Xpp3Dom t1 = new Xpp3Dom("top"); t1.setAttribute("attr", "value"); t1.setInputLocation("t1top"); t1.setAttribute(Xpp3Dom.SELF_COMBINATION_MODE_ATTRIBUTE, Xpp3Dom.SELF_COMBINATION_OVERRIDE); // create the recessive DOM Xpp3Dom t2 = new Xpp3Dom("top"); t2.setAttribute("attr2", "value2"); t2.setValue("t2Value"); t2.setInputLocation("t2top"); // merge and check results. Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(t1, t2); assertEquals(2, result.getAttributeNames().length); assertNull(result.getValue()); assertEquals("t1top", result.getInputLocation()); } /** * <p>testShouldMergeValuesAtTopLevelByDefault.</p> */ @Test void testShouldNotMergeValuesAtTopLevelByDefault() { // create the dominant DOM Xpp3Dom t1 = new Xpp3Dom("top"); t1.setAttribute("attr", "value"); t1.setInputLocation("t1top"); // create the recessive DOM Xpp3Dom t2 = new Xpp3Dom("top"); t2.setAttribute("attr2", "value2"); t2.setValue("t2Value"); t2.setInputLocation("t2top"); // merge and check results. Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(t1, t2); // this is still 2, since we're not using the merge-control attribute. assertEquals(2, result.getAttributeNames().length); assertNull(result.getValue()); assertEquals("t1top", result.getInputLocation()); } /** * <p>testShouldMergeValuesAtTopLevel.</p> */ @Test void testShouldNotMergeValuesAtTopLevel() { // create the dominant DOM Xpp3Dom t1 = new Xpp3Dom("top"); t1.setAttribute("attr", "value"); t1.setAttribute(Xpp3Dom.SELF_COMBINATION_MODE_ATTRIBUTE, Xpp3Dom.SELF_COMBINATION_MERGE); // create the recessive DOM Xpp3Dom t2 = new Xpp3Dom("top"); t2.setAttribute("attr2", "value2"); t2.setValue("t2Value"); // merge and check results. Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(t1, t2); assertEquals(3, result.getAttributeNames().length); assertNull(result.getValue()); } /** * <p>testEquals.</p> */ @Test void testEquals() { XmlNode dom = XmlNode.newInstance("top"); assertEquals(dom, dom); assertNotEquals(dom, null); assertNotEquals(dom, XmlNode.newInstance("")); } /** * <p>testEqualsComplex.</p> */ @Test void testEqualsComplex() throws XMLStreamException, XmlPullParserException, IOException { String testDom = "<configuration><items thing='blah'><item>one</item><item>two</item></items></configuration>"; XmlNode dom1 = XmlService.read(new StringReader(testDom)); XmlNode dom2 = XmlNodeBuilder.build(new StringReader(testDom)); assertEquals(dom1, dom2); } /** * <p>testEqualsWithDifferentStructures.</p> */ @Test void testEqualsWithDifferentStructures() throws XMLStreamException, IOException { String testDom = "<configuration><items thing='blah'><item>one</item><item>two</item></items></configuration>"; XmlNode dom = toXmlNode(testDom); // Create a different DOM structure with different attributes and children Map<String, String> attributes = new HashMap<>(); attributes.put("differentAttribute", "differentValue"); List<XmlNode> childList = new ArrayList<>(); childList.add(XmlNode.newInstance("differentChild", "differentValue", null, null, null)); Xpp3Dom dom2 = new Xpp3Dom(XmlNode.newInstance(dom.name(), "differentValue", attributes, childList, null)); assertNotEquals(dom, dom2); assertNotEquals(dom2, dom); } /** * <p>testShouldOverwritePluginConfigurationSubItemsByDefault.</p> */ @Test void testShouldOverwritePluginConfigurationSubItemsByDefault() throws XMLStreamException, IOException { String parentConfigStr = "<configuration><items><item>one</item><item>two</item></items></configuration>"; XmlNode parentConfig = toXmlNode(parentConfigStr, new FixedInputLocationBuilder("parent")); String childConfigStr = "<configuration><items><item>three</item></items></configuration>"; XmlNode childConfig = toXmlNode(childConfigStr, new FixedInputLocationBuilder("child")); XmlNode result = XmlService.merge(childConfig, parentConfig); XmlNode items = result.child("items"); assertEquals(1, items.children().size()); XmlNode item = items.children().get(0); assertEquals("three", item.value()); assertEquals("child", item.inputLocation()); } /** * <p>testShouldMergePluginConfigurationSubItemsWithMergeAttributeSet.</p> */ @Test void testShouldMergePluginConfigurationSubItemsWithMergeAttributeSet() throws XMLStreamException, IOException { String parentConfigStr = "<configuration><items><item>one</item><item>two</item></items></configuration>"; XmlNode parentConfig = toXmlNode(parentConfigStr, new FixedInputLocationBuilder("parent")); String childConfigStr = "<configuration><items combine.children=\"append\"><item>three</item></items></configuration>"; XmlNode childConfig = toXmlNode(childConfigStr, new FixedInputLocationBuilder("child")); XmlNode result = XmlService.merge(childConfig, parentConfig); assertNotNull(result); XmlNode items = result.child("items"); assertNotNull(result); XmlNode[] item = items.children().toArray(new XmlNode[0]); assertEquals(3, item.length); assertEquals("one", item[0].value()); assertEquals("parent", item[0].inputLocation()); assertEquals("two", item[1].value()); assertEquals("parent", item[1].inputLocation()); assertEquals("three", item[2].value()); assertEquals("child", item[2].inputLocation()); } /** * <p>testShouldNotChangeUponMergeWithItselfWhenFirstOrLastSubItemIsEmpty.</p> * * @throws java.lang.Exception if any. */ @Test void testShouldNotChangeUponMergeWithItselfWhenFirstOrLastSubItemIsEmpty() throws Exception { String configStr = "<configuration><items><item/><item>test</item><item/></items></configuration>"; XmlNode dominantConfig = toXmlNode(configStr); XmlNode recessiveConfig = toXmlNode(configStr); XmlNode result = XmlService.merge(dominantConfig, recessiveConfig); XmlNode items = result.child("items"); assertEquals(3, items.children().size()); assertNull(items.children().get(0).value()); assertEquals("test", items.children().get(1).value()); assertNull(items.children().get(2).value()); } /** * <p>testShouldCopyRecessiveChildrenNotPresentInTarget.</p> * * @throws java.lang.Exception if any. */ @Test void testShouldCopyRecessiveChildrenNotPresentInTarget() throws Exception { String dominantStr = "<configuration><foo>x</foo></configuration>"; String recessiveStr = "<configuration><bar>y</bar></configuration>"; Xpp3Dom dominantConfig = build(new StringReader(dominantStr)); Xpp3Dom recessiveConfig = build(new StringReader(recessiveStr)); Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(dominantConfig, recessiveConfig); assertEquals(2, result.getChildCount()); assertEquals("x", result.getChild("foo").getValue()); assertEquals("y", result.getChild("bar").getValue()); assertNotSame(result.getChild("bar"), recessiveConfig.getChild("bar")); } /** * <p>testDupeChildren.</p> */ @Test void testDupeChildren() throws IOException, XMLStreamException { String dupes = "<configuration><foo>x</foo><foo>y</foo></configuration>"; XmlNode dom = toXmlNode(new StringReader(dupes)); assertNotNull(dom); assertEquals("y", dom.child("foo").value()); } /** * <p>testShouldRemoveEntireElementWithAttributesAndChildren.</p> * * @throws java.lang.Exception if any. */ @Test void testShouldRemoveEntireElementWithAttributesAndChildren() throws Exception { String dominantStr = "<config><service combine.self=\"remove\"/></config>"; String recessiveStr = "<config><service><parameter>parameter</parameter></service></config>"; Xpp3Dom dominantConfig = build(new StringReader(dominantStr)); Xpp3Dom recessiveConfig = build(new StringReader(recessiveStr)); Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(dominantConfig, recessiveConfig); assertEquals(0, result.getChildCount()); assertEquals("config", result.getName()); } /** * <p>testShouldRemoveDoNotRemoveTagWhenSwappedInputDOMs.</p> * * @throws java.lang.Exception if any. */ @Test void testShouldRemoveDoNotRemoveTagWhenSwappedInputDOMs() throws Exception { String dominantStr = "<config><service combine.self=\"remove\"/></config>"; String recessiveStr = "<config><service><parameter>parameter</parameter></service></config>"; Xpp3Dom dominantConfig = build(new StringReader(dominantStr)); Xpp3Dom recessiveConfig = build(new StringReader(recessiveStr)); // same DOMs as testShouldRemoveEntireElementWithAttributesAndChildren(), swapping dominant <--> recessive Xpp3Dom result = Xpp3Dom.mergeXpp3Dom(recessiveConfig, dominantConfig); assertEquals(recessiveConfig.toString(), result.toString()); } @Test void testMergeCombineChildrenAppendOnRecessive() throws XMLStreamException, IOException { String dominant = "<relocations>\n" + " <relocation>\n" + " <pattern>org.apache.shiro.crypto.CipherService</pattern>\n" + " <shadedPattern>org.apache.shiro.crypto.cipher.CipherService</shadedPattern>\n" + " </relocation>\n" + "</relocations>"; String recessive = "<relocations combine.children=\"append\">\n" + " <relocation>\n" + " <pattern>javax.faces</pattern>\n" + " <shadedPattern>jakarta.faces</shadedPattern>\n" + " </relocation>\n" + "</relocations>"; String expected = "<relocations combine.children=\"append\">\n" + " <relocation>\n" + " <pattern>javax.faces</pattern>\n" + " <shadedPattern>jakarta.faces</shadedPattern>\n" + " </relocation>\n" + " <relocation>\n" + " <pattern>org.apache.shiro.crypto.CipherService</pattern>\n" + " <shadedPattern>org.apache.shiro.crypto.cipher.CipherService</shadedPattern>\n" + " </relocation>\n" + "</relocations>"; XmlNode d = toXmlNode(dominant); XmlNode r = toXmlNode(recessive); XmlNode m = XmlService.merge(d, r, null); assertEquals(expected, m.toString().replaceAll("\r\n", "\n")); } private static List<XmlNode> getChildren(XmlNode node, String name) { return node.children().stream().filter(n -> n.name().equals(name)).toList(); } private static XmlNode getNthChild(XmlNode node, String name, int nth) { return node.children().stream() .filter(n -> n.name().equals(name)) .skip(nth) .findFirst() .orElse(null); } private static XmlNode toXmlNode(String xml) throws XMLStreamException, IOException { return toXmlNode(xml, null); } private static XmlNode toXmlNode(String xml, XmlService.InputLocationBuilder locationBuilder) throws XMLStreamException, IOException { return toXmlNode(new StringReader(xml), locationBuilder); } private static XmlNode toXmlNode(Reader reader) throws XMLStreamException, IOException { return toXmlNode(reader, null); } private static XmlNode toXmlNode(Reader reader, XmlService.InputLocationBuilder locationBuilder) throws XMLStreamException, IOException { return XmlService.read(reader, locationBuilder); } private static
XmlNodeImplTest
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/FieldCanBeFinalTest.java
{ "start": 7534, "end": 8015 }
class ____ { int x; B(A a) { x = 42; a.x = 42; } } """) .doTest(); } // don't report an error if the field has an initializer and is also written // in the constructor @Test public void guardInitialization() { compilationHelper .addSourceLines( "Test.java", String.format("import %s;", Var.class.getCanonicalName()), "
B
java
dropwizard__dropwizard
dropwizard-jersey/src/test/java/io/dropwizard/jersey/validation/ConstraintViolationExceptionMapperTest.java
{ "start": 1235, "end": 49774 }
class ____ extends AbstractBinder { @Override protected void configure() { this.bind(new LoggingExceptionMapper<Throwable>() { }).to(ExceptionMapper.class); } } private static final Locale DEFAULT_LOCALE = Locale.getDefault(); @Override protected Application configure() { return DropwizardResourceConfig.forTesting() .packages("io.dropwizard.jersey.validation") .register(new ValidatingResource2()) .register(new LoggingExceptionMapperBinder()) .register(new HibernateValidationBinder(Validators.newValidator())); } @BeforeAll static void init() { // Set default locale to English because some tests assert localized error messages Locale.setDefault(Locale.ENGLISH); } @AfterAll static void shutdown() { Locale.setDefault(DEFAULT_LOCALE); } @Test void postInvalidEntityIs422() { final Response response = target("/valid/foo").request(MediaType.APPLICATION_JSON) .post(Entity.entity("{}", MediaType.APPLICATION_JSON)); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)).isEqualTo("{\"errors\":[\"name must not be empty\"]}"); } @Test void postNullEntityIs422() { final Response response = target("/valid/foo").request(MediaType.APPLICATION_JSON) .post(Entity.entity(null, MediaType.APPLICATION_JSON)); assertThat(response.getStatus()).isEqualTo(422); String ret = "{\"errors\":[\"The request body must not be null\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void postInvalidatedEntityIs422() { final Response response = target("/valid/fooValidated").request(MediaType.APPLICATION_JSON) .post(Entity.entity("{}", MediaType.APPLICATION_JSON)); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)).isEqualTo("{\"errors\":[\"name must not be empty\"]}"); } @Test void postInvalidInterfaceEntityIs422() { final Response response = target("/valid2/repr").request(MediaType.APPLICATION_JSON) .post(Entity.entity("{\"name\": \"a\"}", MediaType.APPLICATION_JSON)); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param interfaceVariable must not be null\"]}"); } @Test void returnInvalidEntityIs500() { final Response response = target("/valid/foo").request(MediaType.APPLICATION_JSON) .post(Entity.entity("{ \"name\": \"Coda\" }", MediaType.APPLICATION_JSON)); assertThat(response.getStatus()).isEqualTo(500); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"server response name must not be empty\"]}"); } @Test void returnInvalidatedEntityIs500() { final Response response = target("/valid/fooValidated").request(MediaType.APPLICATION_JSON) .post(Entity.entity("{ \"name\": \"Coda\" }", MediaType.APPLICATION_JSON)); assertThat(response.getStatus()).isEqualTo(500); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"server response name must not be empty\"]}"); } @Test void getInvalidReturnIs500() { // return value is too long and so will fail validation final Response response = target("/valid/bar") .queryParam("name", "dropwizard").request().get(); assertThat(response.getStatus()).isEqualTo(500); String ret = "{\"errors\":[\"server response length must be between 0 and 3\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void getInvalidQueryParamsIs400() { // query parameter is too short and so will fail validation final Response response = target("/valid/bar") .queryParam("name", "hi").request().get(); assertThat(response.getStatus()).isEqualTo(400); String ret = "{\"errors\":[\"query param name length must be between 3 and 2147483647\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); // Send another request to trigger reflection cache final Response cache = target("/valid/bar") .queryParam("name", "hi").request().get(); assertThat(cache.getStatus()).isEqualTo(400); assertThat(cache.readEntity(String.class)).isEqualTo(ret); } @Test void cacheIsForParamNamesOnly() { // query parameter must not be null, and must be at least 3 final Response response = target("/valid/fhqwhgads") .queryParam("num", 2).request().get(); assertThat(response.getStatus()).isEqualTo(400); String ret = "{\"errors\":[\"query param num must be greater than or equal to 3\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); // Send another request to trigger reflection cache. This one is invalid in a different way // and should get a different message. final Response cache = target("/valid/fhqwhgads").request().get(); assertThat(cache.getStatus()).isEqualTo(400); ret = "{\"errors\":[\"query param num must not be null\"]}"; assertThat(cache.readEntity(String.class)).isEqualTo(ret); } @Test void postInvalidPrimitiveIs422() { // query parameter is too short and so will fail validation final Response response = target("/valid/simpleEntity") .request().post(Entity.json("hi")); assertThat(response.getStatus()).isEqualTo(422); String ret = "{\"errors\":[\"The request body length must be between 3 and 5\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void getInvalidCustomTypeIs400() { // query parameter is too short and so will fail validation final Response response = target("/valid/barter") .queryParam("name", "hi").request().get(); assertThat(response.getStatus()).isEqualTo(400); String ret = "{\"errors\":[\"query param name length must be between 3 and 2147483647\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void getInvalidBeanParamsIs400() { // bean parameter is too short and so will fail validation Response response = target("/valid/zoo") .request().get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("\"name must be Coda\"") .containsOnlyOnce("\"query param name must not be empty\"") .containsOnlyOnce("\"query param choice must not be null\""); } @Test void getInvalidSubBeanParamsIs400() { final Response response = target("/valid/sub-zoo") .queryParam("address", "42 Wallaby Way") .request().get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("query param name must not be empty") .containsOnlyOnce("name must be Coda"); } @Test void getGroupSubBeanParamsIs400() { final Response response = target("/valid/sub-group-zoo") .queryParam("address", "42 WALLABY WAY") .queryParam("name", "Coda") .request().get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("[\"address must not be uppercase\"]"); } @Test void postValidGroupsIs400() { final Response response = target("/valid/sub-valid-group-zoo") .queryParam("address", "42 WALLABY WAY") .queryParam("name", "Coda") .request() .post(Entity.json("{}")); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("[\"address must not be uppercase\"]"); } @Test void getInvalidatedBeanParamsIs400() { // bean parameter is too short and so will fail validation final Response response = target("/valid/zoo2") .request().get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("\"name must be Coda\"") .containsOnlyOnce("\"query param name must not be empty\""); } @Test void getInvalidHeaderParamsIs400() { final Response response = target("/valid/head") .request().get(); assertThat(response.getStatus()).isEqualTo(400); String ret = "{\"errors\":[\"header cheese must not be empty\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void getInvalidCookieParamsIs400() { final Response response = target("/valid/cooks") .request().get(); assertThat(response.getStatus()).isEqualTo(400); String ret = "{\"errors\":[\"cookie user_id must not be empty\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void getInvalidPathParamsIs400() { final Response response = target("/valid/goods/11") .request().get(); assertThat(response.getStatus()).isEqualTo(400); String ret = "{\"errors\":[\"path param id must be a well-formed email address\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void getInvalidFormParamsIs400() { final Response response = target("/valid/form") .request().post(Entity.form(new Form())); assertThat(response.getStatus()).isEqualTo(400); String ret = "{\"errors\":[\"form field username must not be empty\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void postInvalidMethodClassIs422() { final Response response = target("/valid/nothing") .request().post(Entity.entity("{}", MediaType.APPLICATION_JSON_TYPE)); assertThat(response.getStatus()).isEqualTo(422); String ret = "{\"errors\":[\"must have a false thing\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void getInvalidNestedReturnIs500() { final Response response = target("/valid/nested").request().get(); assertThat(response.getStatus()).isEqualTo(500); String ret = "{\"errors\":[\"server response representation.name must not be empty\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void getInvalidNested2ReturnIs500() { final Response response = target("/valid/nested2").request().get(); assertThat(response.getStatus()).isEqualTo(500); String ret = "{\"errors\":[\"server response example must have a false thing\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void getInvalidContextIs400() { final Response response = target("/valid/context").request().get(); assertThat(response.getStatus()).isEqualTo(400); String ret = "{\"errors\":[\"context must not be null\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void getInvalidMatrixParamIs400() { final Response response = target("/valid/matrix") .matrixParam("bob", "").request().get(); assertThat(response.getStatus()).isEqualTo(400); String ret = "{\"errors\":[\"matrix param bob must not be empty\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); } @Test void functionWithSameNameReturnDifferentErrors() { // This test is to make sure that functions with the same name and // number of parameters (but different parameter types), don't return // the same validation error due to any caching effects final Response response = target("/valid/head") .request().get(); String ret = "{\"errors\":[\"header cheese must not be empty\"]}"; assertThat(response.readEntity(String.class)).isEqualTo(ret); final Response response2 = target("/valid/headCopy") .request().get(); assertThat(response2.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param cheese is not a number.\"}"); } @Test void paramsCanBeUnwrappedAndValidated() { final Response response = target("/valid/nullable-int-param") .queryParam("num", 4) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be less than or equal to 3\"]}"); } @Test void returnPartialValidatedRequestEntities() { final Response response = target("/valid/validatedPartialExample") .request().post(Entity.json("{\"id\":1}")); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(PartialExample.class).id) .isEqualTo(1); } @Test void invalidNullPartialValidatedRequestEntities() { final Response response = target("/valid/validatedPartialExample") .request().post(Entity.json(null)); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"The request body must not be null\"]}"); } @Test void invalidEntityExceptionForPartialValidatedRequestEntities() { final Response response = target("/valid/validatedPartialExampleBoth") .request().post(Entity.json("{\"id\":1}")); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"text must not be null\"]}"); } @Test void invalidNullPartialBothValidatedRequestEntities() { final Response response = target("/valid/validatedPartialExampleBoth") .request().post(Entity.json(null)); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"The request body must not be null\"]}"); } @Test void returnPartialBothValidatedRequestEntities() { final Response response = target("/valid/validatedPartialExampleBoth") .request().post(Entity.json("{\"id\":1,\"text\":\"hello Cemo\"}")); assertThat(response.getStatus()).isEqualTo(200); PartialExample ex = response.readEntity(PartialExample.class); assertThat(ex.id).isEqualTo(1); assertThat(ex.text).isEqualTo("hello Cemo"); } @Test void invalidEntityExceptionForInvalidRequestEntities() { final Response response = target("/valid/validExample") .request().post(Entity.json("{\"id\":-1}")); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"id must be greater than or equal to 0\"]}"); } @Test void returnRequestEntities() { final Response response = target("/valid/validExample") .request().post(Entity.json("{\"id\":1}")); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Example.class).id) .isEqualTo(1); } @Test void returnRequestArrayEntities() { final Response response = target("/valid/validExampleArray") .request().post(Entity.json("[{\"id\":1}, {\"id\":2}]")); final Example ex1 = new Example(); final Example ex2 = new Example(); ex1.id = 1; ex2.id = 2; assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Example[].class)) .containsExactly(ex1, ex2); } @Test void invalidRequestCollectionEntities() { final Response response = target("/valid/validExampleCollection") .request().post(Entity.json("[{\"id\":-1}, {\"id\":-2}]")); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .contains("id must be greater than or equal to 0", "id must be greater than or equal to 0"); } @Test void invalidRequestSingleCollectionEntities() { final Response response = target("/valid/validExampleCollection") .request().post(Entity.json("[{\"id\":1}, {\"id\":-2}]")); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .containsOnlyOnce("id must be greater than or equal to 0"); } @Test void returnRequestCollectionEntities() { final Response response = target("/valid/validExampleCollection") .request().post(Entity.json("[{\"id\":1}, {\"id\":2}]")); assertThat(response.getStatus()).isEqualTo(200); final Collection<Example> example = response.readEntity(new GenericType<Collection<Example>>() { }); Example ex1 = new Example(); Example ex2 = new Example(); ex1.id = 1; ex2.id = 2; assertThat(example).containsOnly(ex1, ex2); } @Test void invalidRequestSetEntities() { final Response response = target("/valid/validExampleSet") .request().post(Entity.json("[{\"id\":1}, {\"id\":-2}]")); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .containsOnlyOnce("id must be greater than or equal to 0"); } @Test void invalidRequestListEntities() { final Response response = target("/valid/validExampleList") .request().post(Entity.json("[{\"id\":-1}, {\"id\":-2}]")); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"id must be greater than or equal to 0\"," + "\"id must be greater than or equal to 0\"]}"); } @Test void throwsAConstraintViolationExceptionForEmptyRequestEntities() { final Response response = target("/valid/validExample") .request().post(Entity.json(null)); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"The request body must not be null\"]}"); } @Test void returnsValidatedMapRequestEntities() { final Response response = target("/valid/validExampleMap") .request().post(Entity.json("{\"one\": {\"id\":1}, \"two\": {\"id\":2}}")); assertThat(response.getStatus()).isEqualTo(200); Map<String, Example> map = response.readEntity(new GenericType<Map<String, Example>>() { }); assertThat(requireNonNull(map.get("one")).id).isEqualTo(1); assertThat(requireNonNull(map.get("two")).id).isEqualTo(2); } @Test void invalidMapRequestEntities() { final Response response = target("/valid/validExampleMap") .request().post(Entity.json("{\"one\": {\"id\":-1}, \"two\": {\"id\":-2}}")); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"id must be greater than or equal to 0\"," + "\"id must be greater than or equal to 0\"]}"); } @Test void returnsValidatedEmbeddedListEntities() { final Response response = target("/valid/validExampleEmbeddedList") .request().post(Entity.json("[ {\"examples\": [ {\"id\":1 } ] } ]")); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(new GenericType<List<ListExample>>() { })) .singleElement() .extracting("examples") .asInstanceOf(InstanceOfAssertFactories.LIST) .singleElement() .extracting("id") .isEqualTo(1); } @Test void invalidEmbeddedListEntities() { final Response response = target("/valid/validExampleEmbeddedList") .request().post(Entity.json("[ {\"examples\": [ {\"id\":1 } ] }, { } ]")); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .containsOnlyOnce("examples must not be empty"); } @Test void testInvalidFieldQueryParam() { final Response response = target("/valid/bar") .queryParam("sort", "foo") .request() .get(); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .containsOnlyOnce("sortParam must match \\\"^(asc|desc)$\\\""); } @Test void missingParameterMessageContainsParameterName() { final Response response = target("/valid/paramValidation") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("query param length is not a number."); } @Test void emptyParameterMessageContainsParameterName() { final Response response = target("/valid/paramValidation") .queryParam("length", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param length is not a number.\"}"); } @Test void maxMessageContainsParameterName() { final Response response = target("/valid/paramValidation") .queryParam("length", 50) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("query param length must be less than or equal to 5"); } @Test void minMessageContainsParameterName() { final Response response = target("/valid/paramValidation") .queryParam("length", 1) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("query param length must be greater than or equal to 2"); } @Test void paramClassPassesValidation() { final Response response = target("/valid/paramValidation") .queryParam("length", 3) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); } @Test void minCustomMessage() { final Response response = target("/valid/messageValidation") .queryParam("length", 1) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("query param length The value 1 is less then 2"); final Response response2 = target("/valid/messageValidation") .queryParam("length", 0) .request() .get(); assertThat(response2.getStatus()).isEqualTo(400); assertThat(response2.readEntity(String.class)) .containsOnlyOnce("query param length The value 0 is less then 2"); } @Test void notPresentEnumParameter() { final Response response = target("/valid/enumParam") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("query param choice must not be null"); } @Test void invalidEnumParameter() { final Response response = target("/valid/enumParam") .queryParam("choice", "invalid") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("query param choice must be one of [OptionA, OptionB, OptionC]"); } @Test void invalidBeanParamEnumParameter() { final Response response = target("/valid/zoo") .queryParam("choice", "invalid") .request().get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .containsOnlyOnce("query param choice must be one of [OptionA, OptionB, OptionC]"); } @Test void selfValidatingBeanParamInvalid() { final Response response = target("/valid/selfValidatingBeanParam") .queryParam("answer", 100) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"The answer is 42\"]}"); } @Test void selfValidatingBeanParamSuccess() { final Response response = target("/valid/selfValidatingBeanParam") .queryParam("answer", 42) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(String.class)) .isEqualTo("{\"answer\":42}"); } @Test void selfValidatingPayloadInvalid() { final Response response = target("/valid/selfValidatingPayload") .request() .post(Entity.json("{\"answer\":100}")); assertThat(response.getStatus()).isEqualTo(422); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"The answer is 42\"]}"); } @Test void selfValidatingPayloadSuccess() { final String payload = "{\"answer\":42}"; final Response response = target("/valid/selfValidatingPayload") .request() .post(Entity.json(payload)); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(String.class)) .isEqualTo(payload); } @Test void longParam_fails_with_null() { final Response response = target("/valid/longParam") .queryParam("num") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void longParam_fails_with_emptyString() { final Response response = target("/valid/longParam") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void longParam_fails_with_constraint_violation() { final Response response = target("/valid/longParam") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void longParam_fails_with_string() { final Response response = target("/valid/longParam") .queryParam("num", "string") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void longParam_succeeds() { final Response response = target("/valid/longParam") .queryParam("num", 42) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void longParamNotNull_fails_with_null() { final Response response = target("/valid/longParamNotNull") .queryParam("num") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void longParamNotNull_fails_with_empty_string() { final Response response = target("/valid/longParamNotNull") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void longParamNotNull_fails_with_constraint_violation() { final Response response = target("/valid/longParamNotNull") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void longParamNotNull_fails_with_string() { final Response response = target("/valid/longParamNotNull") .queryParam("num", "test") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void longParamNotNull_succeeds() { final Response response = target("/valid/longParamNotNull") .queryParam("num", 42) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void longParamWithDefault_succeeds_with_null() { final Response response = target("/valid/longParamWithDefault") .queryParam("num") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void longParamWithDefault_fails_with_empty_string() { final Response response = target("/valid/longParamWithDefault") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Long.class)).isEqualTo(42L); } @Test void longParamWithDefault_fails_with_constraint_violation() { final Response response = target("/valid/longParamWithDefault") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void longParamWithDefault_fails_with_string() { final Response response = target("/valid/longParamWithDefault") .queryParam("num", "test") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void longParamWithDefault_succeeds() { final Response response = target("/valid/longParamWithDefault") .queryParam("num", 30) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(30); } @Test void intParam_fails_with_null() { final Response response = target("/valid/intParam") .queryParam("num") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void intParam_fails_with_emptyString() { final Response response = target("/valid/intParam") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void intParam_fails_with_constraint_violation() { final Response response = target("/valid/intParam") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void intParam_fails_with_string() { final Response response = target("/valid/intParam") .queryParam("num", "string") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void intParam_succeeds() { final Response response = target("/valid/intParam") .queryParam("num", 42) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void intParamNotNull_fails_with_null() { final Response response = target("/valid/intParamNotNull") .queryParam("num") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void intParamNotNull_fails_with_empty_string() { final Response response = target("/valid/intParamNotNull") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void intParamNotNull_fails_with_constraint_violation() { final Response response = target("/valid/intParamNotNull") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void intParamNotNull_fails_with_string() { final Response response = target("/valid/intParamNotNull") .queryParam("num", "test") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void intParamNotNull_succeeds() { final Response response = target("/valid/intParamNotNull") .queryParam("num", 42) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void intParamWithDefault_succeeds_with_null() { final Response response = target("/valid/intParamWithDefault") .queryParam("num") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void intParamWithDefault_fails_with_empty_string() { final Response response = target("/valid/intParamWithDefault") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void intParamWithDefault_fails_with_constraint_violation() { final Response response = target("/valid/intParamWithDefault") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void intParamWithDefault_fails_with_string() { final Response response = target("/valid/intParamWithDefault") .queryParam("num", "test") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void intParamWithDefault_succeeds() { final Response response = target("/valid/intParamWithDefault") .queryParam("num", 30) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(30); } @Test void intParamWithOptionalInside_fails_with_missing() { final Response response = target("/valid/intParamWithOptionalInside") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void intParamWithOptionalInside_fails_with_empty_string() { final Response response = target("/valid/intParamWithOptionalInside") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void intParamWithOptionalInside_fails_with_constraint_violation() { final Response response = target("/valid/intParamWithOptionalInside") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void intParamWithOptionalInside_fails_with_string() { final Response response = target("/valid/intParamWithOptionalInside") .queryParam("num", "test") .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":400,\"message\":\"query param num is not a number.\"}"); } @Test void intParamWithOptionalInside_succeeds() { final Response response = target("/valid/intParamWithOptionalInside") .queryParam("num", 30) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(30); } @Test void optionalInt_succeeds_with_missing() { final Response response = target("/valid/optionalInt") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void optionalInt_succeeds_with_empty_string() { final Response response = target("/valid/optionalInt") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void optionalInt_fails_with_constraint_violation() { final Response response = target("/valid/optionalInt") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void optionalInt_fails_with_string() { final Response response = target("/valid/optionalInt") .queryParam("num", "test") .request() .get(); assertThat(response.getStatus()).isEqualTo(404); } @Test void optionalInt_succeeds() { final Response response = target("/valid/optionalInt") .queryParam("num", 30) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(30); } @Test void optionalIntWithDefault_succeeds_with_missing() { final Response response = target("/valid/optionalIntWithDefault") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(23); } @Test void optionalIntWithDefault_succeeds_with_empty_string() { final Response response = target("/valid/optionalIntWithDefault") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void optionalIntWithDefault_fails_with_constraint_violation() { final Response response = target("/valid/optionalIntWithDefault") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void optionalIntWithDefault_fails_with_string() { final Response response = target("/valid/optionalIntWithDefault") .queryParam("num", "test") .request() .get(); assertThat(response.getStatus()).isEqualTo(404); } @Test void optionalIntWithDefault_succeeds() { final Response response = target("/valid/optionalIntWithDefault") .queryParam("num", 30) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(30); } @Test void optionalInteger_succeeds_with_missing() { final Response response = target("/valid/optionalInteger") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void optionalInteger_succeeds_with_empty_string() { final Response response = target("/valid/optionalInteger") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void optionalInteger_fails_with_constraint_violation() { final Response response = target("/valid/optionalInteger") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void optionalInteger_fails_with_string() { final Response response = target("/valid/optionalInteger") .queryParam("num", "test") .request() .get(); assertThat(response.getStatus()).isEqualTo(404); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":404,\"message\":\"HTTP 404 Not Found\"}"); } @Test void optionalInteger_succeeds() { final Response response = target("/valid/optionalInteger") .queryParam("num", 30) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(30); } @Test void optionalIntegerWithDefault_succeeds_with_missing() { final Response response = target("/valid/optionalIntegerWithDefault") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(23); } @Test void optionalIntegerWithDefault_succeeds_with_empty_string() { final Response response = target("/valid/optionalIntegerWithDefault") .queryParam("num", "") .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(42); } @Test void optionalIntegerWithDefault_fails_with_constraint_violation() { final Response response = target("/valid/optionalIntegerWithDefault") .queryParam("num", 5) .request() .get(); assertThat(response.getStatus()).isEqualTo(400); assertThat(response.readEntity(String.class)) .isEqualTo("{\"errors\":[\"query param num must be greater than or equal to 23\"]}"); } @Test void optionalIntegerWithDefault_fails_with_string() { final Response response = target("/valid/optionalIntegerWithDefault") .queryParam("num", "test") .request() .get(); assertThat(response.getStatus()).isEqualTo(404); assertThat(response.readEntity(String.class)) .isEqualTo("{\"code\":404,\"message\":\"HTTP 404 Not Found\"}"); } @Test void optionalIntegerWithDefault_succeeds() { final Response response = target("/valid/optionalIntegerWithDefault") .queryParam("num", 30) .request() .get(); assertThat(response.getStatus()).isEqualTo(200); assertThat(response.readEntity(Integer.class)).isEqualTo(30); } }
LoggingExceptionMapperBinder
java
spring-projects__spring-boot
documentation/spring-boot-docs/src/main/java/org/springframework/boot/docs/actuator/micrometertracing/baggage/CreatingBaggage.java
{ "start": 845, "end": 1104 }
class ____ { private final Tracer tracer; CreatingBaggage(Tracer tracer) { this.tracer = tracer; } void doSomething() { try (BaggageInScope scope = this.tracer.createBaggageInScope("baggage1", "value1")) { // Business logic } } }
CreatingBaggage
java
apache__camel
components/camel-ai/camel-torchserve/src/test/java/org/apache/camel/component/torchserve/it/ManagementIT.java
{ "start": 2157, "end": 4311 }
class ____ { @BeforeEach void registerModel() { try { template.sendBody("direct:register", null); } catch (CamelExecutionException e) { // Ignore if the model is already registered } var mock = getMockEndpoint("mock:result"); mock.reset(); } @Test void testUnregister() throws Exception { var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().body().contains("unregistered"); template.sendBody("direct:unregister", null); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testUnregister_headers() throws Exception { var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().body().contains("unregistered"); template.send("direct:unregister_headers", exchange -> exchange.getMessage().setHeader(TorchServeConstants.MODEL_NAME, ADDED_MODEL)); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testUnregister_version() throws Exception { var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().body().contains("unregistered"); template.sendBody("direct:unregister_version", null); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Test void testUnregister_versionHeaders() throws Exception { var mock = getMockEndpoint("mock:result"); mock.expectedBodyReceived().body().contains("unregistered"); template.send("direct:unregister_headers", exchange -> { exchange.getMessage().setHeader(TorchServeConstants.MODEL_NAME, ADDED_MODEL); exchange.getMessage().setHeader(TorchServeConstants.MODEL_VERSION, ADDED_MODEL_VERSION); }); mock.await(1, TimeUnit.SECONDS); mock.assertIsSatisfied(); } @Nested
AfterRegisteringModel
java
spring-projects__spring-boot
loader/spring-boot-jarmode-tools/src/main/java/org/springframework/boot/jarmode/tools/ToolsJarMode.java
{ "start": 944, "end": 1742 }
class ____ implements JarMode { private final Context context; private final PrintStream out; public ToolsJarMode() { this(null, null); } public ToolsJarMode(@Nullable Context context, @Nullable PrintStream out) { this.context = (context != null) ? context : new Context(); this.out = (out != null) ? out : System.out; } @Override public boolean accepts(String mode) { return "tools".equalsIgnoreCase(mode); } @Override public void run(String mode, String[] args) { try { new Runner(this.out, this.context, getCommands(this.context)).run(args); } catch (Exception ex) { throw new IllegalStateException(ex); } } static List<Command> getCommands(Context context) { return List.of(new ExtractCommand(context), new ListLayersCommand(context)); } }
ToolsJarMode
java
apache__camel
components/camel-aws/camel-aws2-sts/src/generated/java/org/apache/camel/component/aws2/sts/STS2EndpointUriFactory.java
{ "start": 518, "end": 2824 }
class ____ extends org.apache.camel.support.component.EndpointUriFactorySupport implements EndpointUriFactory { private static final String BASE = ":label"; private static final Set<String> PROPERTY_NAMES; private static final Set<String> SECRET_PROPERTY_NAMES; private static final Map<String, String> MULTI_VALUE_PREFIXES; static { Set<String> props = new HashSet<>(17); props.add("accessKey"); props.add("label"); props.add("lazyStartProducer"); props.add("operation"); props.add("overrideEndpoint"); props.add("pojoRequest"); props.add("profileCredentialsName"); props.add("proxyHost"); props.add("proxyPort"); props.add("proxyProtocol"); props.add("region"); props.add("secretKey"); props.add("stsClient"); props.add("trustAllCertificates"); props.add("uriEndpointOverride"); props.add("useDefaultCredentialsProvider"); props.add("useProfileCredentialsProvider"); PROPERTY_NAMES = Collections.unmodifiableSet(props); Set<String> secretProps = new HashSet<>(2); secretProps.add("accessKey"); secretProps.add("secretKey"); SECRET_PROPERTY_NAMES = Collections.unmodifiableSet(secretProps); MULTI_VALUE_PREFIXES = Collections.emptyMap(); } @Override public boolean isEnabled(String scheme) { return "aws2-sts".equals(scheme); } @Override public String buildUri(String scheme, Map<String, Object> properties, boolean encode) throws URISyntaxException { String syntax = scheme + BASE; String uri = syntax; Map<String, Object> copy = new HashMap<>(properties); uri = buildPathParameter(syntax, uri, "label", null, true, copy); uri = buildQueryParameters(uri, copy, encode); return uri; } @Override public Set<String> propertyNames() { return PROPERTY_NAMES; } @Override public Set<String> secretPropertyNames() { return SECRET_PROPERTY_NAMES; } @Override public Map<String, String> multiValuePrefixes() { return MULTI_VALUE_PREFIXES; } @Override public boolean isLenientProperties() { return false; } }
STS2EndpointUriFactory
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/resource/VersionResourceResolver.java
{ "start": 2546, "end": 9476 }
class ____ extends AbstractResourceResolver { private final AntPathMatcher pathMatcher = new AntPathMatcher(); /** Map from path pattern -> VersionStrategy. */ private final Map<String, VersionStrategy> versionStrategyMap = new LinkedHashMap<>(); /** * Set a Map with URL paths as keys and {@code VersionStrategy} as values. * <p>Supports direct URL matches and Ant-style pattern matches. For syntax * details, see the {@link AntPathMatcher} javadoc. * @param map a map with URLs as keys and version strategies as values */ public void setStrategyMap(Map<String, VersionStrategy> map) { this.versionStrategyMap.clear(); this.versionStrategyMap.putAll(map); } /** * Return the map with version strategies keyed by path pattern. */ public Map<String, VersionStrategy> getStrategyMap() { return this.versionStrategyMap; } /** * Insert a content-based version in resource URLs that match the given path * patterns. The version is computed from the content of the file, for example, * {@code "css/main-e36d2e05253c6c7085a91522ce43a0b4.css"}. This is a good * default strategy to use except when it cannot be, for example when using * JavaScript module loaders, use {@link #addFixedVersionStrategy} instead * for serving JavaScript files. * @param pathPatterns one or more resource URL path patterns, * relative to the pattern configured with the resource handler * @return the current instance for chained method invocation * @see ContentVersionStrategy */ public VersionResourceResolver addContentVersionStrategy(String... pathPatterns) { addVersionStrategy(new ContentVersionStrategy(), pathPatterns); return this; } /** * Insert a fixed, prefix-based version in resource URLs that match the given * path patterns, for example: <code>"{version}/js/main.js"</code>. This is useful (vs. * content-based versions) when using JavaScript module loaders. * <p>The version may be a random number, the current date, or a value * fetched from a git commit sha, a property file, or environment variable * and set with SpEL expressions in the configuration (for example, see {@code @Value} * in Java config). * <p>If not done already, variants of the given {@code pathPatterns}, prefixed with * the {@code version} will be also configured. For example, adding a {@code "/js/**"} path pattern * will also configure automatically a {@code "/v1.0.0/js/**"} with {@code "v1.0.0"} the * {@code version} String given as an argument. * @param version a version string * @param pathPatterns one or more resource URL path patterns, * relative to the pattern configured with the resource handler * @return the current instance for chained method invocation * @see FixedVersionStrategy */ public VersionResourceResolver addFixedVersionStrategy(String version, String... pathPatterns) { List<String> patternsList = Arrays.asList(pathPatterns); List<String> prefixedPatterns = new ArrayList<>(pathPatterns.length); String versionPrefix = "/" + version; for (String pattern : patternsList) { prefixedPatterns.add(pattern); if (!pattern.startsWith(versionPrefix) && !patternsList.contains(versionPrefix + pattern)) { prefixedPatterns.add(versionPrefix + pattern); } } return addVersionStrategy(new FixedVersionStrategy(version), StringUtils.toStringArray(prefixedPatterns)); } /** * Register a custom VersionStrategy to apply to resource URLs that match the * given path patterns. * @param strategy the custom strategy * @param pathPatterns one or more resource URL path patterns, * relative to the pattern configured with the resource handler * @return the current instance for chained method invocation * @see VersionStrategy */ public VersionResourceResolver addVersionStrategy(VersionStrategy strategy, String... pathPatterns) { for (String pattern : pathPatterns) { getStrategyMap().put(pattern, strategy); } return this; } @Override protected Mono<Resource> resolveResourceInternal(@Nullable ServerWebExchange exchange, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) { return chain.resolveResource(exchange, requestPath, locations) .switchIfEmpty(Mono.defer(() -> resolveVersionedResource(exchange, requestPath, locations, chain))); } private Mono<Resource> resolveVersionedResource(@Nullable ServerWebExchange exchange, String requestPath, List<? extends Resource> locations, ResourceResolverChain chain) { VersionStrategy versionStrategy = getStrategyForPath(requestPath); if (versionStrategy == null) { return Mono.empty(); } String candidate = versionStrategy.extractVersion(requestPath); if (!StringUtils.hasLength(candidate)) { return Mono.empty(); } String simplePath = versionStrategy.removeVersion(requestPath, candidate); return chain.resolveResource(exchange, simplePath, locations) .filterWhen(resource -> versionStrategy.getResourceVersion(resource) .map(actual -> { if (candidate.equals(actual)) { return true; } else { if (logger.isTraceEnabled()) { String logPrefix = exchange != null ? exchange.getLogPrefix() : ""; logger.trace(logPrefix + "Found resource for \"" + requestPath + "\", but version [" + candidate + "] does not match"); } return false; } })) .map(resource -> new FileNameVersionedResource(resource, candidate)); } @Override protected Mono<String> resolveUrlPathInternal(String resourceUrlPath, List<? extends Resource> locations, ResourceResolverChain chain) { return chain.resolveUrlPath(resourceUrlPath, locations) .flatMap(baseUrl -> { if (StringUtils.hasText(baseUrl)) { VersionStrategy strategy = getStrategyForPath(resourceUrlPath); if (strategy == null) { return Mono.just(baseUrl); } return chain.resolveResource(null, baseUrl, locations) .flatMap(resource -> strategy.getResourceVersion(resource) .map(version -> strategy.addVersion(baseUrl, version))); } return Mono.empty(); }); } /** * Find a {@code VersionStrategy} for the request path of the requested resource. * @return an instance of a {@code VersionStrategy} or null if none matches that request path */ protected @Nullable VersionStrategy getStrategyForPath(String requestPath) { String path = "/".concat(requestPath); List<String> matchingPatterns = new ArrayList<>(); for (String pattern : this.versionStrategyMap.keySet()) { if (this.pathMatcher.match(pattern, path)) { matchingPatterns.add(pattern); } } if (!matchingPatterns.isEmpty()) { Comparator<String> comparator = this.pathMatcher.getPatternComparator(path); matchingPatterns.sort(comparator); return this.versionStrategyMap.get(matchingPatterns.get(0)); } return null; } private static
VersionResourceResolver
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/BasicAnnotationsTest.java
{ "start": 4517, "end": 7038 }
class ____ are used as * expected. */ @Test public void testSetterInheritance() throws Exception { BeanSubClass result = MAPPER.readValue ("{ \"x\":1, \"z\" : 3, \"y\" : 2 }", BeanSubClass.class); assertEquals(1, result._x); assertEquals(2, result._y); assertEquals(3, result._z); } @Test public void testImpliedProperty() throws Exception { BeanWithDeserialize bean = MAPPER.readValue("{\"a\":3}", BeanWithDeserialize.class); assertNotNull(bean); assertEquals(3, bean.a); } // [databind#442] @Test public void testIssue442PrivateUnwrapped() throws Exception { Issue442Bean bean = MAPPER.readValue("{\"i\":5}", Issue442Bean.class); assertEquals(5, bean.w.i); } /* /********************************************************** /* Test methods, annotations disabled /********************************************************** */ @Test public void testAnnotationsDisabled() throws Exception { // first: verify that annotation introspection is enabled by default assertTrue(MAPPER.deserializationConfig().isEnabled(MapperFeature.USE_ANNOTATIONS)); // with annotations, property is renamed AnnoBean bean = MAPPER.readValue("{ \"y\" : 0 }", AnnoBean.class); assertEquals(0, bean.value); ObjectMapper m = jsonMapperBuilder() .disable(MapperFeature.USE_ANNOTATIONS) .build(); // without annotations, should default to default bean-based name... bean = m.readValue("{ \"x\" : 0 }", AnnoBean.class); assertEquals(0, bean.value); } @Test public void testEnumsWhenDisabled() throws Exception { ObjectMapper m = new ObjectMapper(); assertEquals(Alpha.B, m.readValue(q("B"), Alpha.class)); m = jsonMapperBuilder() .disable(MapperFeature.USE_ANNOTATIONS) .build(); // should still use the basic name handling here assertEquals(Alpha.B, m.readValue(q("B"), Alpha.class)); } @Test public void testNoAccessOverrides() throws Exception { ObjectMapper m = jsonMapperBuilder() .disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS) .build(); SimpleBean bean = m.readValue("{\"x\":1,\"y\":2}", SimpleBean.class); assertEquals(1, bean.x); assertEquals(2, bean.y); } }
setters
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_1273/EntityMapperReturnDefault.java
{ "start": 301, "end": 534 }
interface ____ { Dto asTarget(Entity entity); @ObjectFactory default Dto createDto() { Dto result = new Dto(); result.setLongs( new ArrayList<>( ) ); return result; } }
EntityMapperReturnDefault
java
quarkusio__quarkus
extensions/panache/hibernate-orm-rest-data-panache/deployment/src/test/java/io/quarkus/hibernate/orm/rest/data/panache/deployment/security/AuthenticatedClassAnnotationTest.java
{ "start": 382, "end": 533 }
class ____ extends AbstractSecurityAnnotationTest { @ResourceProperties(path = "items") @Authenticated public
AuthenticatedClassAnnotationTest
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxWindowTimeout.java
{ "start": 55957, "end": 56512 }
class ____ implements Runnable { final long index; final WindowTimeoutSubscriber<?> parent; ConsumerIndexHolder(long index, WindowTimeoutSubscriber<?> parent) { this.index = index; this.parent = parent; } @Override public void run() { WindowTimeoutSubscriber<?> p = parent; if (!p.cancelled) { p.queue.offer(this); } else { p.terminated = true; p.timer.dispose(); p.worker.dispose(); } if (p.enter()) { p.drainLoop(); } } } } }
ConsumerIndexHolder
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/streaming/api/operators/StateInitializationContextImplTest.java
{ "start": 4283, "end": 15119 }
class ____ { static final int NUM_HANDLES = 10; private StateInitializationContextImpl initializationContext; private CloseableRegistry closableRegistry; private int writtenKeyGroups; private Set<Integer> writtenOperatorStates; @BeforeEach void setUp() throws Exception { this.writtenKeyGroups = 0; this.writtenOperatorStates = new HashSet<>(); this.closableRegistry = new CloseableRegistry(); ByteArrayOutputStreamWithPos out = new ByteArrayOutputStreamWithPos(64); List<KeyedStateHandle> keyedStateHandles = new ArrayList<>(NUM_HANDLES); int prev = 0; for (int i = 0; i < NUM_HANDLES; ++i) { out.reset(); int size = i % 4; int end = prev + size; DataOutputView dov = new DataOutputViewStreamWrapper(out); KeyGroupRangeOffsets offsets = new KeyGroupRangeOffsets( i == 9 ? KeyGroupRange.EMPTY_KEY_GROUP_RANGE : new KeyGroupRange(prev, end)); prev = end + 1; for (int kg : offsets.getKeyGroupRange()) { offsets.setKeyGroupOffset(kg, out.getPosition()); dov.writeInt(kg); ++writtenKeyGroups; } KeyedStateHandle handle = new KeyGroupsStateHandle( offsets, new ByteStateHandleCloseChecking("kg-" + i, out.toByteArray())); keyedStateHandles.add(handle); } List<OperatorStateHandle> operatorStateHandles = new ArrayList<>(NUM_HANDLES); for (int i = 0; i < NUM_HANDLES; ++i) { int size = i % 4; out.reset(); DataOutputView dov = new DataOutputViewStreamWrapper(out); LongArrayList offsets = new LongArrayList(size); for (int s = 0; s < size; ++s) { offsets.add(out.getPosition()); int val = i * NUM_HANDLES + s; dov.writeInt(val); writtenOperatorStates.add(val); } Map<String, OperatorStateHandle.StateMetaInfo> offsetsMap = new HashMap<>(); offsetsMap.put( DefaultOperatorStateBackend.DEFAULT_OPERATOR_STATE_NAME, new OperatorStateHandle.StateMetaInfo( offsets.toArray(), OperatorStateHandle.Mode.SPLIT_DISTRIBUTE)); OperatorStateHandle operatorStateHandle = new OperatorStreamStateHandle( offsetsMap, new ByteStateHandleCloseChecking("os-" + i, out.toByteArray())); operatorStateHandles.add(operatorStateHandle); } OperatorSubtaskState operatorSubtaskState = OperatorSubtaskState.builder() .setRawOperatorState(new StateObjectCollection<>(operatorStateHandles)) .setRawKeyedState(new StateObjectCollection<>(keyedStateHandles)) .build(); OperatorID operatorID = new OperatorID(); TaskStateSnapshot taskStateSnapshot = new TaskStateSnapshot(); taskStateSnapshot.putSubtaskStateByOperatorID(operatorID, operatorSubtaskState); JobManagerTaskRestore jobManagerTaskRestore = new JobManagerTaskRestore(0L, taskStateSnapshot); TaskStateManager manager = new TaskStateManagerImpl( new JobID(), createExecutionAttemptId(), new TestTaskLocalStateStore(), null, new InMemoryStateChangelogStorage(), new TaskExecutorStateChangelogStoragesManager(), jobManagerTaskRestore, mock(CheckpointResponder.class)); DummyEnvironment environment = new DummyEnvironment("test", 1, 0, prev); environment.setTaskStateManager(manager); StateBackend stateBackend = new HashMapStateBackend(); StreamTaskStateInitializer streamTaskStateManager = new StreamTaskStateInitializerImpl( environment, stateBackend, new SubTaskInitializationMetricsBuilder( SystemClock.getInstance().absoluteTimeMillis()), TtlTimeProvider.DEFAULT, new InternalTimeServiceManager.Provider() { @Override public <K> InternalTimeServiceManager<K> create( TaskIOMetricGroup taskIOMetricGroup, PriorityQueueSetFactory factory, KeyGroupRange keyGroupRange, ClassLoader userClassloader, KeyContext keyContext, ProcessingTimeService processingTimeService, Iterable<KeyGroupStatePartitionStreamProvider> rawKeyedStates, StreamTaskCancellationContext cancellationContext) throws Exception { // We do not initialize a timer service manager here, because it // would already consume the raw keyed // state as part of initialization. For the purpose of this test, we // want an unconsumed raw keyed // stream. return null; } }, StreamTaskCancellationContext.alwaysRunning()); AbstractStreamOperator<?> mockOperator = mock(AbstractStreamOperator.class); when(mockOperator.getOperatorID()).thenReturn(operatorID); StreamOperatorStateContext stateContext = streamTaskStateManager.streamOperatorStateContext( operatorID, "TestOperatorClass", mock(ProcessingTimeService.class), mockOperator, // notice that this essentially disables the previous test of the keyed // stream because it was and is always // consumed by the timer service. IntSerializer.INSTANCE, closableRegistry, new UnregisteredMetricsGroup(), 1.0, false, false); OptionalLong restoredCheckpointId = stateContext.getRestoredCheckpointId(); this.initializationContext = new StateInitializationContextImpl( restoredCheckpointId.isPresent() ? restoredCheckpointId.getAsLong() : null, stateContext.operatorStateBackend(), mock(KeyedStateStore.class), stateContext.rawKeyedStateInputs(), stateContext.rawOperatorStateInputs()); } @Test void getOperatorStateStreams() throws Exception { int i = 0; int s = 0; for (StatePartitionStreamProvider streamProvider : initializationContext.getRawOperatorStateInputs()) { if (0 == i % 4) { ++i; } assertThat(streamProvider).isNotNull(); try (InputStream is = streamProvider.getStream()) { DataInputView div = new DataInputViewStreamWrapper(is); int val = div.readInt(); assertThat(val).isEqualTo(i * NUM_HANDLES + s); } ++s; if (s == i % 4) { s = 0; ++i; } } } @Test void getKeyedStateStreams() throws Exception { int readKeyGroupCount = 0; for (KeyGroupStatePartitionStreamProvider stateStreamProvider : initializationContext.getRawKeyedStateInputs()) { assertThat(stateStreamProvider).isNotNull(); try (InputStream is = stateStreamProvider.getStream()) { DataInputView div = new DataInputViewStreamWrapper(is); int val = div.readInt(); ++readKeyGroupCount; assertThat(val).isEqualTo(stateStreamProvider.getKeyGroupId()); } } assertThat(readKeyGroupCount).isEqualTo(writtenKeyGroups); } @Test void getOperatorStateStore() throws Exception { Set<Integer> readStatesCount = new HashSet<>(); for (StatePartitionStreamProvider statePartitionStreamProvider : initializationContext.getRawOperatorStateInputs()) { assertThat(statePartitionStreamProvider).isNotNull(); try (InputStream is = statePartitionStreamProvider.getStream()) { DataInputView div = new DataInputViewStreamWrapper(is); assertThat(readStatesCount.add(div.readInt())).isTrue(); } } assertThat(readStatesCount).isEqualTo(writtenOperatorStates); } @Test void close() throws Exception { int count = 0; int stopCount = NUM_HANDLES / 2; boolean isClosed = false; try { for (KeyGroupStatePartitionStreamProvider stateStreamProvider : initializationContext.getRawKeyedStateInputs()) { assertThat(stateStreamProvider).isNotNull(); if (count == stopCount) { closableRegistry.close(); isClosed = true; } try (InputStream is = stateStreamProvider.getStream()) { DataInputView div = new DataInputViewStreamWrapper(is); try { int val = div.readInt(); assertThat(val).isEqualTo(stateStreamProvider.getKeyGroupId()); assertThat(isClosed).as("Close was ignored: stream").isFalse(); ++count; } catch (IOException ioex) { if (!isClosed) { throw ioex; } } } } fail("Close was ignored: registry"); } catch (IOException iex) { assertThat(isClosed).isTrue(); assertThat(count).isEqualTo(stopCount); } } static final
StateInitializationContextImplTest
java
quarkusio__quarkus
extensions/spring-data-jpa/deployment/src/test/java/io/quarkus/spring/data/deployment/ModifyingQueryWithFlushAndClearTest.java
{ "start": 513, "end": 3941 }
class ____ { @RegisterExtension static final QuarkusUnitTest config = new QuarkusUnitTest().setArchiveProducer( () -> ShrinkWrap.create(JavaArchive.class) .addAsResource("import_users.sql", "import.sql") .addClasses(User.class, LoginEvent.class, UserRepository.class)) .withConfigurationResource("application.properties"); @Inject UserRepository repo; @BeforeEach @Transactional public void setUp() { final User user = getUser("JOHN"); user.setLoginCounter(0); user.getLoginEvents().clear(); repo.save(user); } @Test @Transactional public void testNoAutoClear() { getUser("JOHN"); // read user to attach it to entity manager repo.incrementLoginCounterPlain("JOHN"); final User userAfterIncrement = getUser("JOHN"); // we get the cached entity // the read doesn't re-read the incremented counter and is therefore equal to the old value assertThat(userAfterIncrement.getLoginCounter()).isEqualTo(0); } @Test @Transactional public void testAutoClear() { getUser("JOHN"); // read user to attach it to entity manager repo.incrementLoginCounterAutoClear("JOHN"); final User userAfterIncrement = getUser("JOHN"); assertThat(userAfterIncrement.getLoginCounter()).isEqualTo(1); } @Test @Transactional public void testNoAutoFlush() { final User user = getUser("JOHN"); createLoginEvent(user); repo.processLoginEventsPlain(); final User verifyUser = getUser("JOHN"); // processLoginEvents did not see the new login event assertThat(verifyUser.getLoginEvents()).hasSize(1); final boolean allProcessed = verifyUser.getLoginEvents().stream() .allMatch(LoginEvent::isProcessed); assertThat(allProcessed).describedAs("all LoginEvents are marked as processed").isFalse(); } @Test @Transactional public void testAutoFlush() { final User user = getUser("JOHN"); createLoginEvent(user); repo.processLoginEventsPlainAutoClearAndFlush(); final User verifyUser = getUser("JOHN"); assertThat(verifyUser.getLoginEvents()).hasSize(1); final boolean allProcessed = verifyUser.getLoginEvents().stream() .allMatch(LoginEvent::isProcessed); assertThat(allProcessed).describedAs("all LoginEvents are marked as processed").isTrue(); } @Test @Transactional public void testNamedQueryOnEntities() { User user = repo.getUserByFullNameUsingNamedQuery("John Doe"); assertThat(user).isNotNull(); } @Test @Transactional public void testNamedQueriesOnEntities() { User user = repo.getUserByFullNameUsingNamedQueries("John Doe"); assertThat(user).isNotNull(); } private LoginEvent createLoginEvent(User user) { final LoginEvent loginEvent = new LoginEvent(); loginEvent.setUser(user); loginEvent.setZonedDateTime(ZonedDateTime.now()); user.addEvent(loginEvent); return loginEvent; } private User getUser(String userId) { final Optional<User> user = repo.findById(userId); assertThat(user).describedAs("user <%s>", userId).isPresent(); return user.get(); } }
ModifyingQueryWithFlushAndClearTest
java
quarkusio__quarkus
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/TemplateRecordEnhancer.java
{ "start": 2155, "end": 5367 }
class ____ extends ClassVisitor { public TemplateRecordClassVisitor(ClassVisitor outputClassVisitor) { super(Gizmo.ASM_API_VERSION, outputClassVisitor); } @Override public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { MethodVisitor ret = super.visitMethod(access, name, descriptor, signature, exceptions); if (name.equals(MethodDescriptor.INIT) && descriptor.equals(canonicalConstructorDescriptor)) { return new TemplateRecordConstructorVisitor(ret); } return ret; } @Override public void visitEnd() { String interfaceName = interfaceToImplement.name().toString(); // private final TemplateInstance qute$templateInstance; FieldDescriptor quteTemplateInstanceDescriptor = FieldDescriptor.of(recordClassName, "qute$templateInstance", interfaceName); FieldVisitor quteTemplateInstance = super.visitField(ACC_PRIVATE | ACC_FINAL, quteTemplateInstanceDescriptor.getName(), quteTemplateInstanceDescriptor.getType(), null, null); quteTemplateInstance.visitEnd(); for (MethodInfo method : interfaceToImplement.methods()) { if (method.isSynthetic() || method.isBridge()) { continue; } MethodDescriptor descriptor = MethodDescriptor.of(method); String[] exceptions = method.exceptions().stream().map(e -> toInternalClassName(e.name().toString())) .toArray(String[]::new); MethodVisitor visitor = super.visitMethod(Opcodes.ACC_PUBLIC, descriptor.getName(), descriptor.getDescriptor(), null, exceptions); visitor.visitCode(); readQuteTemplateInstance(visitor); int idx = 1; for (Type paramType : method.parameterTypes()) { // Load arguments on the stack visitor.visitVarInsn(AsmUtil.getLoadOpcode(paramType), idx++); } invokeInterface(visitor, descriptor); returnAndEnd(visitor, method.returnType()); } super.visitEnd(); } private void readQuteTemplateInstance(MethodVisitor methodVisitor) { FieldDescriptor quteTemplateInstanceDescriptor = FieldDescriptor.of(recordClassName, "qute$templateInstance", interfaceToImplement.name().toString()); methodVisitor.visitVarInsn(Opcodes.ALOAD, 0); methodVisitor.visitFieldInsn(Opcodes.GETFIELD, quteTemplateInstanceDescriptor.getDeclaringClass(), quteTemplateInstanceDescriptor.getName(), quteTemplateInstanceDescriptor.getType()); } private void returnAndEnd(MethodVisitor methodVisitor, Type returnType) { methodVisitor.visitInsn(AsmUtil.getReturnInstruction(returnType)); methodVisitor.visitEnd(); methodVisitor.visitMaxs(-1, -1); } }
TemplateRecordClassVisitor
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/S3ATestUtils.java
{ "start": 11107, "end": 17822 }
class ____ run by default assumeThat(liveTest) .as("No test filesystem in " + TEST_FS_S3A_NAME) .isTrue(); FileContext fc = FileContext.getFileContext(testURI, conf); return fc; } /** * Skip if PathIOE occurred due to exception which contains a message which signals * an incompatibility or throw the PathIOE. * * @param ioe PathIOE being parsed. * @param messages messages found in the PathIOE that trigger a test to skip * @throws PathIOException Throws PathIOE if it doesn't relate to any message in {@code messages}. */ public static void skipIfIOEContainsMessage(PathIOException ioe, String...messages) throws PathIOException { for (String message: messages) { if (ioe.toString().contains(message)) { skip("Skipping because: " + message); } } throw ioe; } /** * Get a long test property. * <ol> * <li>Look up configuration value (which can pick up core-default.xml), * using {@code defVal} as the default value (if conf != null). * </li> * <li>Fetch the system property.</li> * <li>If the system property is not empty or "(unset)": * it overrides the conf value. * </li> * </ol> * This puts the build properties in charge of everything. It's not a * perfect design; having maven set properties based on a file, as ant let * you do, is better for customization. * * As to why there's a special (unset) value, see * {@link http://stackoverflow.com/questions/7773134/null-versus-empty-arguments-in-maven} * @param conf config: may be null * @param key key to look up * @param defVal default value * @return the evaluated test property. */ public static long getTestPropertyLong(Configuration conf, String key, long defVal) { return Long.valueOf( getTestProperty(conf, key, Long.toString(defVal))); } /** * Get a test property value in bytes, using k, m, g, t, p, e suffixes. * {@link org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix#string2long(String)} * <ol> * <li>Look up configuration value (which can pick up core-default.xml), * using {@code defVal} as the default value (if conf != null). * </li> * <li>Fetch the system property.</li> * <li>If the system property is not empty or "(unset)": * it overrides the conf value. * </li> * </ol> * This puts the build properties in charge of everything. It's not a * perfect design; having maven set properties based on a file, as ant let * you do, is better for customization. * * As to why there's a special (unset) value, see * {@link http://stackoverflow.com/questions/7773134/null-versus-empty-arguments-in-maven} * @param conf config: may be null * @param key key to look up * @param defVal default value * @return the evaluated test property. */ public static long getTestPropertyBytes(Configuration conf, String key, String defVal) { return org.apache.hadoop.util.StringUtils.TraditionalBinaryPrefix .string2long(getTestProperty(conf, key, defVal)); } /** * Get an integer test property; algorithm described in * {@link #getTestPropertyLong(Configuration, String, long)}. * @param key key to look up * @param defVal default value * @return the evaluated test property. */ public static int getTestPropertyInt(Configuration conf, String key, int defVal) { return (int) getTestPropertyLong(conf, key, defVal); } /** * Get a boolean test property; algorithm described in * {@link #getTestPropertyLong(Configuration, String, long)}. * @param key key to look up * @param defVal default value * @return the evaluated test property. */ public static boolean getTestPropertyBool(Configuration conf, String key, boolean defVal) { return Boolean.valueOf( getTestProperty(conf, key, Boolean.toString(defVal))); } /** * Get a string test property. * <ol> * <li>Look up configuration value (which can pick up core-default.xml), * using {@code defVal} as the default value (if conf != null). * </li> * <li>Fetch the system property.</li> * <li>If the system property is not empty or "(unset)": * it overrides the conf value. * </li> * </ol> * This puts the build properties in charge of everything. It's not a * perfect design; having maven set properties based on a file, as ant let * you do, is better for customization. * * As to why there's a special (unset) value, see * @see <a href="http://stackoverflow.com/questions/7773134/null-versus-empty-arguments-in-maven"> * Stack Overflow</a> * @param conf config: may be null * @param key key to look up * @param defVal default value * @return the evaluated test property. */ public static String getTestProperty(Configuration conf, String key, String defVal) { String confVal = conf != null ? conf.getTrimmed(key, defVal) : defVal; String propval = System.getProperty(key); return isNotEmpty(propval) && !UNSET_PROPERTY.equals(propval) ? propval : confVal; } /** * Get the test CSV file; assume() that it is not empty. * @param conf test configuration * @return test file. * @deprecated Retained only to assist cherrypicking patches */ @Deprecated public static String getCSVTestFile(Configuration conf) { return getExternalData(conf).toUri().toString(); } /** * Get the test CSV path; assume() that it is not empty. * @param conf test configuration * @return test file as a path. * @deprecated Retained only to assist cherrypicking patches */ @Deprecated public static Path getCSVTestPath(Configuration conf) { return getExternalData(conf); } /** * Get the test CSV file; assume() that it is not modified (i.e. we haven't * switched to a new storage infrastructure where the bucket is no longer * read only). * @return test file. * @param conf test configuration * @deprecated Retained only to assist cherrypicking patches */ @Deprecated public static String getLandsatCSVFile(Configuration conf) { return requireDefaultExternalDataFile(conf); } /** * Get the test CSV file; assume() that it is not modified (i.e. we haven't * switched to a new storage infrastructure where the bucket is no longer * read only). * @param conf test configuration * @return test file as a path. * @deprecated Retained only to assist cherrypicking patches */ @Deprecated public static Path getLandsatCSVPath(Configuration conf) { return getExternalData(conf); } /** * Verify the
not
java
quarkusio__quarkus
extensions/hibernate-search-standalone-elasticsearch/runtime-dev/src/main/java/io/quarkus/hibernate/search/standalone/elasticsearch/runtime/dev/HibernateSearchStandaloneDevInfo.java
{ "start": 310, "end": 749 }
class ____ { private final List<IndexedEntity> indexedEntities; public HibernateSearchStandaloneDevInfo(List<IndexedEntity> indexedEntities) { this.indexedEntities = indexedEntities; } public List<IndexedEntity> getIndexedEntities() { return indexedEntities; } public int getNumberOfIndexedEntities() { return indexedEntities.size(); } public static
HibernateSearchStandaloneDevInfo
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/blockloader/docvalues/fn/MvMinBooleansBlockLoader.java
{ "start": 931, "end": 1488 }
class ____ extends AbstractBooleansBlockLoader { public MvMinBooleansBlockLoader(String fieldName) { super(fieldName); } @Override protected AllReader singletonReader(NumericDocValues docValues) { return new Singleton(docValues); } @Override protected AllReader sortedReader(SortedNumericDocValues docValues) { return new MvMinSorted(docValues); } @Override public String toString() { return "BooleansFromDocValues[" + fieldName + "]"; } private static
MvMinBooleansBlockLoader
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableForEachTest.java
{ "start": 946, "end": 2514 }
class ____ extends RxJavaTest { @Test public void forEachWile() { final List<Object> list = new ArrayList<>(); Flowable.range(1, 5) .doOnNext(new Consumer<Integer>() { @Override public void accept(Integer v) throws Exception { list.add(v); } }) .forEachWhile(new Predicate<Integer>() { @Override public boolean test(Integer v) throws Exception { return v < 3; } }); assertEquals(Arrays.asList(1, 2, 3), list); } @Test public void forEachWileWithError() { final List<Object> list = new ArrayList<>(); Flowable.range(1, 5).concatWith(Flowable.<Integer>error(new TestException())) .doOnNext(new Consumer<Integer>() { @Override public void accept(Integer v) throws Exception { list.add(v); } }) .forEachWhile(new Predicate<Integer>() { @Override public boolean test(Integer v) throws Exception { return true; } }, new Consumer<Throwable>() { @Override public void accept(Throwable e) throws Exception { list.add(100); } }); assertEquals(Arrays.asList(1, 2, 3, 4, 5, 100), list); } @Test public void dispose() { TestHelper.checkDisposed( Flowable.never() .forEachWhile(v -> true) ); } }
FlowableForEachTest
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/CaffeineLoadCacheEndpointBuilderFactory.java
{ "start": 21960, "end": 25048 }
class ____ { /** * The internal instance of the builder used to access to all the * methods representing the name of headers. */ private static final CaffeineLoadCacheHeaderNameBuilder INSTANCE = new CaffeineLoadCacheHeaderNameBuilder(); /** * The action to execute. Possible values: CLEANUP PUT PUT_ALL GET * GET_ALL INVALIDATE INVALIDATE_ALL AS_MAP. * * The option is a: {@code String} type. * * Group: producer * * @return the name of the header {@code CaffeineAction}. */ public String caffeineAction() { return "CamelCaffeineAction"; } /** * The flag indicating whether the action has a result or not. * * The option is a: {@code Boolean} type. * * Group: producer * * @return the name of the header {@code CaffeineActionHasResult}. */ public String caffeineActionHasResult() { return "CamelCaffeineActionHasResult"; } /** * The flag indicating whether the action was successful or not. * * The option is a: {@code Boolean} type. * * Group: producer * * @return the name of the header {@code CaffeineActionSucceeded}. */ public String caffeineActionSucceeded() { return "CamelCaffeineActionSucceeded"; } /** * The key for all actions on a single entry. * * The option is a: {@code } type. * * Group: producer * * @return the name of the header {@code CaffeineKey}. */ public String caffeineKey() { return "CamelCaffeineKey"; } /** * The keys to get (GET_ALL), to invalidate (INVALIDATE_ALL) or existing * (AS_MAP) according to the action. * * The option is a: {@code Set} type. * * Group: producer * * @return the name of the header {@code CaffeineKeys}. */ public String caffeineKeys() { return "CamelCaffeineKeys"; } /** * The value of key for all put actions (PUT or PUT_ALL). * * The option is a: {@code } type. * * Group: producer * * @return the name of the header {@code CaffeineValue}. */ public String caffeineValue() { return "CamelCaffeineValue"; } /** * The old value returned according to the action. * * The option is a: {@code } type. * * Group: producer * * @return the name of the header {@code CaffeineOldValue}. */ public String caffeineOldValue() { return "CamelCaffeineOldValue"; } } static CaffeineLoadCacheEndpointBuilder endpointBuilder(String componentName, String path) {
CaffeineLoadCacheHeaderNameBuilder
java
micronaut-projects__micronaut-core
benchmarks/src/jmh/java/io/micronaut/core/CopyOnWriteMapBenchmark.java
{ "start": 1652, "end": 2367 }
class ____ { @Param({"CHM", "COW"}) Type type; @Param({"1", "2", "5", "10"}) int load; private Map<String, String> map; private Function<String, String> ciaUpdate; @Setup public void setUp() { map = switch (type) { case CHM -> new ConcurrentHashMap<>(16, 0.75f, 1); case COW -> CopyOnWriteMap.create(16); }; // doesn't really stress the collision avoidance algorithm but oh well map.put("foo", "bar"); for (int i = 0; i < load; i++) { map.put("f" + i, "b" + i); } ciaUpdate = m -> "buzz" + m; } } public
S
java
apache__hadoop
hadoop-common-project/hadoop-common/src/main/java/org/apache/hadoop/io/file/tfile/TFile.java
{ "start": 73969, "end": 74070 }
class ____ /** * Data structure representing "TFile.index" meta block. */ static
MetaTFileMeta
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/validation/SimpleErrors.java
{ "start": 2289, "end": 5803 }
class ____ the object name. * @param target the target to wrap */ public SimpleErrors(Object target) { Assert.notNull(target, "Target must not be null"); this.target = target; this.objectName = this.target.getClass().getSimpleName(); } /** * Create a new {@link SimpleErrors} holder for the given target. * @param target the target to wrap * @param objectName the name of the target object for error reporting */ public SimpleErrors(Object target, String objectName) { Assert.notNull(target, "Target must not be null"); this.target = target; this.objectName = objectName; } @Override public String getObjectName() { return this.objectName; } @Override public void reject(String errorCode, Object @Nullable [] errorArgs, @Nullable String defaultMessage) { this.globalErrors.add(new ObjectError(getObjectName(), new String[] {errorCode}, errorArgs, defaultMessage)); } @Override public void rejectValue(@Nullable String field, String errorCode, Object @Nullable [] errorArgs, @Nullable String defaultMessage) { if (!StringUtils.hasLength(field)) { reject(errorCode, errorArgs, defaultMessage); return; } Object newVal = getFieldValue(field); this.fieldErrors.add(new FieldError(getObjectName(), field, newVal, false, new String[] {errorCode}, errorArgs, defaultMessage)); } @Override public void addAllErrors(Errors errors) { this.globalErrors.addAll(errors.getGlobalErrors()); this.fieldErrors.addAll(errors.getFieldErrors()); } @Override public List<ObjectError> getGlobalErrors() { return this.globalErrors; } @Override public List<FieldError> getFieldErrors() { return this.fieldErrors; } @Override public @Nullable Object getFieldValue(String field) { FieldError fieldError = getFieldError(field); if (fieldError != null) { return fieldError.getRejectedValue(); } PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(this.target.getClass(), field); if (pd != null && pd.getReadMethod() != null) { ReflectionUtils.makeAccessible(pd.getReadMethod()); return ReflectionUtils.invokeMethod(pd.getReadMethod(), this.target); } Field rawField = ReflectionUtils.findField(this.target.getClass(), field); if (rawField != null) { ReflectionUtils.makeAccessible(rawField); return ReflectionUtils.getField(rawField, this.target); } throw new IllegalArgumentException("Cannot retrieve value for field '" + field + "' - neither a getter method nor a raw field found"); } @Override public @Nullable Class<?> getFieldType(String field) { PropertyDescriptor pd = BeanUtils.getPropertyDescriptor(this.target.getClass(), field); if (pd != null) { return pd.getPropertyType(); } Field rawField = ReflectionUtils.findField(this.target.getClass(), field); if (rawField != null) { return rawField.getType(); } return null; } @Override public boolean equals(@Nullable Object other) { return (this == other || (other instanceof SimpleErrors that && ObjectUtils.nullSafeEquals(this.target, that.target) && this.globalErrors.equals(that.globalErrors) && this.fieldErrors.equals(that.fieldErrors))); } @Override public int hashCode() { return this.target.hashCode(); } @Override public String toString() { StringBuilder sb = new StringBuilder(); for (ObjectError error : this.globalErrors) { sb.append('\n').append(error); } for (ObjectError error : this.fieldErrors) { sb.append('\n').append(error); } return sb.toString(); } }
as
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxConcatArray.java
{ "start": 3850, "end": 3926 }
interface ____ { Subscription upstream(); } static final
SubscriptionAware
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/inlineme/SuggesterTest.java
{ "start": 21688, "end": 22050 }
class ____ { @Deprecated public Duration getDeadline(Duration deadline) { return (deadline.compareTo(Duration.ZERO) > 0 ? Duration.ofSeconds(42) : Duration.ZERO); } } """) .addOutputLines( "Client.java", """ package com.google.frobber; import com.google.errorprone.annotations.InlineMe; import java.time.Duration; public final
Client
java
quarkusio__quarkus
integration-tests/jaxb/src/main/java/io/quarkus/it/jaxb/Response.java
{ "start": 633, "end": 1369 }
class ____ FurtherExtensionOfBaseObj complex type. * * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="FurtherExtensionOfBaseObj"&gt; * &lt;complexContent&gt; * &lt;extension base="{http://acme.org/beans}ExtensionOfBaseObj"&gt; * &lt;sequence&gt; * &lt;element name="evenMoreZeep" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;/sequence&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "FurtherExtensionOfBaseObj", propOrder = { "evenMoreZeep" }) @XmlRootElement(name = "response") public
for
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng6173GetProjectsAndDependencyGraphTest.java
{ "start": 1090, "end": 2570 }
class ____ extends AbstractMavenIntegrationTestCase { /** * Verifies that {@code MavenSession#getProjects()} returns the projects being built and that * {@code MavenSession#getDependencyGraph()} returns the dependency graph. * * @throws Exception in case of failure */ @Test public void testitShouldReturnProjectsAndProjectDependencyGraph() throws Exception { File testDir = extractResources("/mng-6173-get-projects-and-dependency-graph"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.setAutoclean(false); verifier.deleteDirectory("target"); verifier.deleteDirectory("module-1/target"); verifier.deleteDirectory("module-2/target"); verifier.addCliArgument("-pl"); verifier.addCliArgument("module-1"); verifier.addCliArgument("validate"); verifier.execute(); verifier.verifyErrorFreeLog(); Properties properties = verifier.loadProperties("module-1/target/session.properties"); assertEquals("1", properties.getProperty("session.projects.size")); assertEquals("module-1", properties.getProperty("session.projects.0.artifactId")); assertEquals("1", properties.getProperty("session.projectDependencyGraph.sortedProjects.size")); assertEquals("module-1", properties.getProperty("session.projectDependencyGraph.sortedProjects.0.artifactId")); } }
MavenITmng6173GetProjectsAndDependencyGraphTest
java
quarkusio__quarkus
extensions/reactive-mssql-client/runtime/src/main/java/io/quarkus/reactive/mssql/client/runtime/health/ReactiveMSSQLDataSourcesHealthCheck.java
{ "start": 698, "end": 1834 }
class ____ extends ReactiveDatasourceHealthCheck { public ReactiveMSSQLDataSourcesHealthCheck() { super("Reactive MS SQL connections health check", "SELECT 1"); } @PostConstruct protected void init() { ArcContainer container = Arc.container(); DataSourceSupport dataSourceSupport = container.instance(DataSourceSupport.class).get(); Set<String> excludedNames = dataSourceSupport.getHealthCheckExcludedNames(); MSSQLPoolSupport msSQLPoolSupport = container.instance(MSSQLPoolSupport.class).get(); Set<String> msSQLPoolNames = msSQLPoolSupport.getMSSQLPoolNames(); for (InstanceHandle<Pool> handle : container.select(Pool.class, Any.Literal.INSTANCE).handles()) { if (!handle.getBean().isActive()) { continue; } String poolName = ReactiveDataSourceUtil.dataSourceName(handle.getBean()); if (!msSQLPoolNames.contains(poolName) || excludedNames.contains(poolName)) { continue; } addPool(poolName, handle.get()); } } }
ReactiveMSSQLDataSourcesHealthCheck
java
elastic__elasticsearch
x-pack/plugin/security/qa/multi-cluster/src/javaRestTest/java/org/elasticsearch/xpack/remotecluster/RemoteClusterSecurityMutualTlsIT.java
{ "start": 1200, "end": 6902 }
class ____ extends AbstractRemoteClusterSecurityTestCase { private static final AtomicReference<Map<String, Object>> API_KEY_MAP_REF = new AtomicReference<>(); private static final AtomicReference<String> VERIFICATION_MODE = new AtomicReference<>(); static { fulfillingCluster = ElasticsearchCluster.local() .name("fulfilling-cluster") .apply(commonClusterConfig) .setting("remote_cluster_server.enabled", "true") .setting("remote_cluster.port", "0") .setting("xpack.security.remote_cluster_server.ssl.enabled", "true") .setting("xpack.security.remote_cluster_server.ssl.key", "remote-cluster.key") .setting("xpack.security.remote_cluster_server.ssl.certificate", "remote-cluster.crt") .setting("xpack.security.remote_cluster_server.ssl.client_authentication", "required") .setting("xpack.security.remote_cluster_server.ssl.verification_mode", () -> String.valueOf(VERIFICATION_MODE.get())) .setting("xpack.security.remote_cluster_server.ssl.certificate_authorities", "remote-cluster-client-ca.crt") .keystore("xpack.security.remote_cluster_server.ssl.secure_key_passphrase", "remote-cluster-password") .build(); queryCluster = ElasticsearchCluster.local() .name("query-cluster") .apply(commonClusterConfig) .setting("xpack.security.remote_cluster_client.ssl.enabled", "true") .setting("xpack.security.remote_cluster_client.ssl.key", "remote-cluster-client.key") .setting("xpack.security.remote_cluster_client.ssl.certificate", "remote-cluster-client.crt") .setting("xpack.security.remote_cluster_client.ssl.client_authentication", "required") // no actual effect .setting("xpack.security.remote_cluster_client.ssl.verification_mode", () -> String.valueOf(VERIFICATION_MODE.get())) .setting("xpack.security.remote_cluster_client.ssl.certificate_authorities", "remote-cluster-ca.crt") .keystore("xpack.security.remote_cluster_client.ssl.secure_key_passphrase", "remote-cluster-client-password") .keystore("cluster.remote.my_remote_cluster.credentials", () -> { if (API_KEY_MAP_REF.get() == null) { final Map<String, Object> apiKeyMap = createCrossClusterAccessApiKey(""" { "search": [ { "names": ["shared-metrics"] } ] }"""); API_KEY_MAP_REF.set(apiKeyMap); } return (String) API_KEY_MAP_REF.get().get("encoded"); }) .rolesFile(Resource.fromClasspath("roles.yml")) .user(REMOTE_METRIC_USER, PASS.toString(), "read_remote_shared_metrics", false) .build(); } @ClassRule // Use a RuleChain to ensure that fulfilling cluster is started before query cluster // `SSL_ENABLED_REF` is used to control the SSL-enabled setting on the test clusters // We set it here, since randomization methods are not available in the static initialize context above public static TestRule clusterRule = RuleChain.outerRule(new RunnableTestRuleAdapter(() -> { VERIFICATION_MODE.set(randomFrom("full", "certificate", "none")); })).around(fulfillingCluster).around(queryCluster); public void testCrossClusterSearch() throws Exception { configureRemoteCluster(); // Fulfilling cluster { // Index some documents, so we can attempt to search them from the querying cluster final Request bulkRequest = new Request("POST", "/_bulk?refresh=true"); bulkRequest.setJsonEntity(Strings.format(""" { "index": { "_index": "shared-metrics" } } { "name": "metric1" } { "index": { "_index": "shared-metrics" } } { "name": "metric2" } { "index": { "_index": "shared-metrics" } } { "name": "metric3" } { "index": { "_index": "shared-metrics" } } { "name": "metric4" } """)); assertOK(performRequestAgainstFulfillingCluster(bulkRequest)); } // Query cluster { // Check remote metric users can search shared-metrics final var metricSearchRequest = new Request( "GET", String.format(Locale.ROOT, "/my_remote_cluster:*/_search?ccs_minimize_roundtrips=%s", randomBoolean()) ); final SearchResponse metricSearchResponse = SearchResponseUtils.parseSearchResponse( responseAsParser(performRequestWithRemoteMetricUser(metricSearchRequest)) ); try { assertThat(metricSearchResponse.getHits().getTotalHits().value(), equalTo(4L)); assertThat( Arrays.stream(metricSearchResponse.getHits().getHits()).map(SearchHit::getIndex).collect(Collectors.toSet()), containsInAnyOrder("shared-metrics") ); } finally { metricSearchResponse.decRef(); } } } private Response performRequestWithRemoteMetricUser(final Request request) throws IOException { request.setOptions( RequestOptions.DEFAULT.toBuilder().addHeader("Authorization", headerFromRandomAuthMethod(REMOTE_METRIC_USER, PASS)) ); return client().performRequest(request); } }
RemoteClusterSecurityMutualTlsIT
java
apache__camel
components/camel-resilience4j/src/main/java/org/apache/camel/component/resilience4j/ResilienceConstants.java
{ "start": 860, "end": 975 }
interface ____ { String DEFAULT_RESILIENCE_CONFIGURATION_ID = "resilience4j-configuration"; }
ResilienceConstants
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/UnsafeReflectiveConstructionCastTest.java
{ "start": 3908, "end": 4471 }
interface ____ {} ; private Fn newInstanceOnGetDeclaredConstructorChained() throws Exception { return (Serializable & Fn) Class.forName("Fn").getDeclaredConstructor().newInstance(); } } """) .doTest(); } @Test public void negativeCase() { compilationHelper .addSourceLines( "UnsafeReflectiveConstructionCastNegativeCases.java", """ package com.google.errorprone.bugpatterns.testdata; /** * Negative cases for {@link UnsafeReflectiveConstructionCast}. * * @author bhagwani@google.com (Sumit Bhagwani) */ public
Fn
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassPostProcessorTests.java
{ "start": 65220, "end": 65326 }
class ____ { @Autowired public ITestBean testBean; } @Configuration public static
ScopedProxyConsumer
java
spring-projects__spring-framework
spring-context-support/src/test/java/org/springframework/scheduling/quartz/SimpleTriggerFactoryBeanTests.java
{ "start": 1811, "end": 4320 }
class ____ { private final SimpleTriggerFactoryBean factory = new SimpleTriggerFactoryBean(); @Test void createWithoutJobDetail() { factory.setName("myTrigger"); factory.setRepeatCount(5); factory.setRepeatInterval(1000L); factory.afterPropertiesSet(); SimpleTrigger trigger = factory.getObject(); assertThat(trigger.getRepeatCount()).isEqualTo(5); assertThat(trigger.getRepeatInterval()).isEqualTo(1000L); } @Test void setMisfireInstructionNameToUnsupportedValues() { assertThatIllegalArgumentException().isThrownBy(() -> factory.setMisfireInstructionName(null)); assertThatIllegalArgumentException().isThrownBy(() -> factory.setMisfireInstructionName(" ")); assertThatIllegalArgumentException().isThrownBy(() -> factory.setMisfireInstructionName("bogus")); } /** * This test effectively verifies that the internal 'constants' map is properly * configured for all MISFIRE_INSTRUCTION_ constants defined in {@link SimpleTrigger}. */ @Test void setMisfireInstructionNameToAllSupportedValues() { streamMisfireInstructionConstants() .map(Field::getName) .forEach(name -> assertThatNoException().as(name).isThrownBy(() -> factory.setMisfireInstructionName(name))); } @Test void setMisfireInstruction() { assertThatIllegalArgumentException().isThrownBy(() -> factory.setMisfireInstruction(999)); assertThatNoException().isThrownBy(() -> factory.setMisfireInstruction(MISFIRE_INSTRUCTION_SMART_POLICY)); assertThatNoException().isThrownBy(() -> factory.setMisfireInstruction(MISFIRE_INSTRUCTION_IGNORE_MISFIRE_POLICY)); assertThatNoException().isThrownBy(() -> factory.setMisfireInstruction(MISFIRE_INSTRUCTION_FIRE_NOW)); assertThatNoException().isThrownBy(() -> factory.setMisfireInstruction(MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_EXISTING_COUNT)); assertThatNoException().isThrownBy(() -> factory.setMisfireInstruction(MISFIRE_INSTRUCTION_RESCHEDULE_NEXT_WITH_REMAINING_COUNT)); assertThatNoException().isThrownBy(() -> factory.setMisfireInstruction(MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_EXISTING_REPEAT_COUNT)); assertThatNoException().isThrownBy(() -> factory.setMisfireInstruction(MISFIRE_INSTRUCTION_RESCHEDULE_NOW_WITH_REMAINING_REPEAT_COUNT)); } private static Stream<Field> streamMisfireInstructionConstants() { return Arrays.stream(SimpleTrigger.class.getFields()) .filter(ReflectionUtils::isPublicStaticFinal) .filter(field -> field.getName().startsWith("MISFIRE_INSTRUCTION_")); } }
SimpleTriggerFactoryBeanTests
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/protocol/LayoutVersion.java
{ "start": 2121, "end": 2206 }
interface ____ be implemented by NameNode and DataNode layout features */ public
to
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/tools/ECAdmin.java
{ "start": 6925, "end": 8649 }
class ____ implements AdminHelper.Command { @Override public String getName() { return "-getPolicy"; } @Override public String getShortUsage() { return "[" + getName() + " -path <path>]\n"; } @Override public String getLongUsage() { final TableListing listing = AdminHelper.getOptionDescriptionListing(); listing.addRow("<path>", "The path of the file/directory for getting the erasure coding " + "policy"); return getShortUsage() + "\n" + "Get the erasure coding policy of a file/directory.\n\n" + listing.toString(); } @Override public int run(Configuration conf, List<String> args) throws IOException { final String path = StringUtils.popOptionWithArgument("-path", args); if (path == null) { System.err.println("Please specify the path with -path.\nUsage: " + getLongUsage()); return 1; } if (args.size() > 0) { System.err.println(getName() + ": Too many arguments"); return 1; } final Path p = new Path(path); final DistributedFileSystem dfs = AdminHelper.getDFS(p.toUri(), conf); try { ErasureCodingPolicy ecPolicy = dfs.getErasureCodingPolicy(p); if (ecPolicy != null) { System.out.println(ecPolicy.getName()); } else { System.out.println("The erasure coding policy of " + path + " is " + "unspecified"); } } catch (Exception e) { System.err.println(AdminHelper.prettifyException(e)); return 2; } return 0; } } /** Command to remove an erasure coding policy. */ private static
GetECPolicyCommand
java
elastic__elasticsearch
x-pack/plugin/watcher/src/test/java/org/elasticsearch/xpack/watcher/trigger/schedule/DailyScheduleTests.java
{ "start": 1137, "end": 9377 }
class ____ extends ScheduleTestCase { public void testDefault() throws Exception { DailySchedule schedule = new DailySchedule(); String[] crons = expressions(schedule.crons()); assertThat(crons, arrayWithSize(1)); assertThat(crons, arrayContaining("0 0 0 * * ?")); } public void testSingleTime() throws Exception { DayTimes time = validDayTime(); DailySchedule schedule = new DailySchedule(time); String[] crons = expressions(schedule); assertThat(crons, arrayWithSize(1)); assertThat(crons, arrayContaining("0 " + join(",", time.minute()) + " " + join(",", time.hour()) + " * * ?")); } public void testSingleTimeInvalid() throws Exception { HourAndMinute ham = invalidDayTime(); try { new DayTimes(ham.hour, ham.minute); fail("expected an illegal argument exception on invalid time input"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString("invalid time [")); assertThat(e.getMessage(), either(containsString("invalid time hour value")).or(containsString("invalid time minute value"))); } } public void testMultipleTimes() throws Exception { DayTimes[] times = validDayTimes(); DailySchedule schedule = new DailySchedule(times); String[] crons = expressions(schedule); assertThat(crons, arrayWithSize(times.length)); for (DayTimes time : times) { assertThat(crons, hasItemInArray("0 " + join(",", time.minute()) + " " + join(",", time.hour()) + " * * ?")); } } public void testParserEmpty() throws Exception { XContentBuilder builder = jsonBuilder().startObject().endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); // advancing to the start object DailySchedule schedule = new DailySchedule.Parser().parse(parser); assertThat(schedule, notNullValue()); assertThat(schedule.times().length, is(1)); assertThat(schedule.times()[0], is(new DayTimes(0, 0))); } public void testParserSingleTimeObject() throws Exception { DayTimes time = validDayTime(); XContentBuilder builder = jsonBuilder().startObject() .startObject("at") .array("hour", time.hour()) .array("minute", time.minute()) .endObject() .endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); // advancing to the start object DailySchedule schedule = new DailySchedule.Parser().parse(parser); assertThat(schedule, notNullValue()); assertThat(schedule.times().length, is(1)); assertThat(schedule.times()[0], is(time)); } public void testParserSingleTimeObjectInvalid() throws Exception { HourAndMinute time = invalidDayTime(); XContentBuilder builder = jsonBuilder().startObject() .startObject("at") .field("hour", time.hour) .field("minute", time.minute) .endObject() .endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); // advancing to the start object try { new DailySchedule.Parser().parse(parser); fail("Expected ElasticsearchParseException"); } catch (ElasticsearchParseException e) { assertThat(e.getMessage(), is("could not parse [daily] schedule. invalid time value for field [at] - [START_OBJECT]")); } } public void testParserSingleTimeString() throws Exception { String timeStr = validDayTimeStr(); XContentBuilder builder = jsonBuilder().startObject().field("at", timeStr).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); // advancing to the start object DailySchedule schedule = new DailySchedule.Parser().parse(parser); assertThat(schedule, notNullValue()); assertThat(schedule.times().length, is(1)); assertThat(schedule.times()[0], is(DayTimes.parse(timeStr))); } public void testParserSingleTimeStringInvalid() throws Exception { XContentBuilder builder = jsonBuilder().startObject().field("at", invalidDayTimeStr()).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); // advancing to the start object try { new DailySchedule.Parser().parse(parser); fail("Expected ElasticsearchParseException"); } catch (ElasticsearchParseException e) { assertThat(e.getMessage(), is("could not parse [daily] schedule. invalid time value for field [at] - [VALUE_STRING]")); } } public void testParserMultipleTimesObjects() throws Exception { DayTimes[] times = validDayTimesFromNumbers(); XContentBuilder builder = jsonBuilder().startObject().array("at", (Object[]) times).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); // advancing to the start object DailySchedule schedule = new DailySchedule.Parser().parse(parser); assertThat(schedule, notNullValue()); assertThat(schedule.times().length, is(times.length)); for (int i = 0; i < times.length; i++) { assertThat(schedule.times(), hasItemInArray(times[i])); } } public void testParserMultipleTimesObjectsInvalid() throws Exception { HourAndMinute[] times = invalidDayTimes(); XContentBuilder builder = jsonBuilder().startObject().array("at", (Object[]) times).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); // advancing to the start object try { new DailySchedule.Parser().parse(parser); fail("Expected ElasticsearchParseException"); } catch (ElasticsearchParseException e) { assertThat(e.getMessage(), is("could not parse [daily] schedule. invalid time value for field [at] - [START_OBJECT]")); } } public void testParserMultipleTimesStrings() throws Exception { DayTimes[] times = validDayTimesFromStrings(); XContentBuilder builder = jsonBuilder().startObject().array("at", (Object[]) times).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); // advancing to the start object DailySchedule schedule = new DailySchedule.Parser().parse(parser); assertThat(schedule, notNullValue()); assertThat(schedule.times().length, is(times.length)); for (int i = 0; i < times.length; i++) { assertThat(schedule.times(), hasItemInArray(times[i])); } } public void testParserMultipleTimesStringsInvalid() throws Exception { String[] times = invalidDayTimesAsStrings(); XContentBuilder builder = jsonBuilder().startObject().array("at", times).endObject(); BytesReference bytes = BytesReference.bytes(builder); XContentParser parser = createParser(JsonXContent.jsonXContent, bytes); parser.nextToken(); // advancing to the start object try { new DailySchedule.Parser().parse(parser); fail("Expected ElasticsearchParseException"); } catch (ElasticsearchParseException e) { assertThat(e.getMessage(), is("could not parse [daily] schedule. invalid time value for field [at] - [VALUE_STRING]")); } } }
DailyScheduleTests
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/SaslAuthenticateResponse.java
{ "start": 1233, "end": 2843 }
class ____ extends AbstractResponse { private final SaslAuthenticateResponseData data; public SaslAuthenticateResponse(SaslAuthenticateResponseData data) { super(ApiKeys.SASL_AUTHENTICATE); this.data = data; } /** * Possible error codes: * SASL_AUTHENTICATION_FAILED(57) : Authentication failed */ public Errors error() { return Errors.forCode(data.errorCode()); } @Override public Map<Errors, Integer> errorCounts() { return errorCounts(Errors.forCode(data.errorCode())); } public String errorMessage() { return data.errorMessage(); } public long sessionLifetimeMs() { return data.sessionLifetimeMs(); } public byte[] saslAuthBytes() { return data.authBytes(); } @Override public int throttleTimeMs() { return DEFAULT_THROTTLE_TIME; } @Override public void maybeSetThrottleTimeMs(int throttleTimeMs) { // Not supported by the response schema } @Override public SaslAuthenticateResponseData data() { return data; } public static SaslAuthenticateResponse parse(Readable readable, short version) { return new SaslAuthenticateResponse(new SaslAuthenticateResponseData(readable, version)); } // Do not print authBytes, overwrite a temp copy of the data with empty bytes @Override public String toString() { SaslAuthenticateResponseData tempData = data.duplicate(); tempData.setAuthBytes(new byte[0]); return tempData.toString(); } }
SaslAuthenticateResponse
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/api/async/RedisFunctionAsyncCommands.java
{ "start": 597, "end": 3968 }
interface ____<K, V> { /** * Invoke a function. * * @param function the function name. * @param type output type. * @param keys key names. * @param <T> expected return type. * @return function result. */ <T> RedisFuture<T> fcall(String function, ScriptOutputType type, K... keys); /** * Invoke a function. * * @param function the function name. * @param type output type. * @param keys the keys. * @param values the values (arguments). * @param <T> expected return type. * @return function result. */ <T> RedisFuture<T> fcall(String function, ScriptOutputType type, K[] keys, V... values); /** * Invoke a function in read-only mode. * * @param function the function name. * @param type output type. * @param keys key names. * @param <T> expected return type. * @return function result. */ <T> RedisFuture<T> fcallReadOnly(String function, ScriptOutputType type, K... keys); /** * Invoke a function in read-only mode. * * @param function the function name. * @param type output type. * @param keys the keys. * @param values the values (arguments). * @param <T> expected return type. * @return function result. */ <T> RedisFuture<T> fcallReadOnly(String function, ScriptOutputType type, K[] keys, V... values); /** * Load a library to Redis. * * @param functionCode code of the function. * @return name of the library. */ RedisFuture<String> functionLoad(String functionCode); /** * Load a library to Redis. * * @param functionCode code of the function. * @param replace whether to replace an existing function. * @return name of the library. */ RedisFuture<String> functionLoad(String functionCode, boolean replace); /** * Return the serialized payload of loaded libraries. You can restore the dump through {@link #functionRestore(byte[])}. * * @return the serialized payload. */ RedisFuture<byte[]> functionDump(); /** * You can restore the dumped payload of loaded libraries. * * @return Simple string reply */ RedisFuture<String> functionRestore(byte[] dump); /** * You can restore the dumped payload of loaded libraries. * * @return Simple string reply */ RedisFuture<String> functionRestore(byte[] dump, FunctionRestoreMode mode); /** * Deletes all the libraries using the specified {@link FlushMode}. * * @param flushMode the flush mode (sync/async). * @return String simple-string-reply. */ RedisFuture<String> functionFlush(FlushMode flushMode); /** * Kill a function that is currently executing. * * @return String simple-string-reply. */ RedisFuture<String> functionKill(); /** * Return information about the functions and libraries. * * @return Array reply. */ RedisFuture<List<Map<String, Object>>> functionList(); /** * Return information about the functions and libraries. * * @param libraryName specify a pattern for matching library names. * @return Array reply. */ RedisFuture<List<Map<String, Object>>> functionList(String libraryName); }
RedisFunctionAsyncCommands
java
quarkusio__quarkus
integration-tests/jpa-mysql/src/main/java/io/quarkus/it/jpa/mysql/XaConnectionsEndpoint.java
{ "start": 499, "end": 1514 }
class ____ { @Inject @DataSource("samebutxa") AgroalDataSource xaDatasource; @GET public String test() throws IOException { // Test 1# // Verify that the connection can be obtained try (Connection connection = xaDatasource.getConnection()) { //The main goal is to check that the connection could be opened } catch (SQLException e) { throw new RuntimeException(e); } // Test 2# // Check it's of the expected configuration AgroalConnectionFactoryConfiguration cfg = xaDatasource.getConfiguration().connectionPoolConfiguration() .connectionFactoryConfiguration(); Class<?> connectionProviderClass = cfg.connectionProviderClass(); if (connectionProviderClass.equals(com.mysql.cj.jdbc.MysqlXADataSource.class)) { return "OK"; } else { return "Unexpected Driver class: " + connectionProviderClass.getName(); } } }
XaConnectionsEndpoint
java
google__dagger
javatests/dagger/functional/subcomponent/StaticChildModule.java
{ "start": 706, "end": 845 }
class ____ { private StaticChildModule() {} @Provides static Object provideStaticObject() { return "static"; } }
StaticChildModule
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/idgen/identity/IdentityInsertSoleColumnTest.java
{ "start": 2523, "end": 2727 }
class ____ { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } } }
Animal
java
google__dagger
javatests/dagger/hilt/android/ViewModelWithBaseTest.java
{ "start": 2133, "end": 2462 }
class ____ extends Hilt_ViewModelWithBaseTest_TestActivity { MyViewModel myViewModel; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); myViewModel = new ViewModelProvider(this).get(MyViewModel.class); } } @HiltViewModel static
TestActivity
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/orm/junit/DialectFeatureChecks.java
{ "start": 35174, "end": 35358 }
class ____ implements DialectFeatureCheck { public boolean apply(Dialect dialect) { return definesFunction( dialect, "array_positions" ); } } public static
SupportsArrayPositions
java
apache__hadoop
hadoop-cloud-storage-project/hadoop-cos/src/main/java/org/apache/hadoop/fs/cosn/CosNFileSystem.java
{ "start": 2260, "end": 26767 }
class ____ extends FileSystem { static final Logger LOG = LoggerFactory.getLogger(CosNFileSystem.class); public static final String SCHEME = "cosn"; public static final String PATH_DELIMITER = Path.SEPARATOR; private URI uri; private String bucket; private NativeFileSystemStore store; private Path workingDir; private String owner = "Unknown"; private String group = "Unknown"; private ExecutorService boundedIOThreadPool; private ExecutorService boundedCopyThreadPool; public CosNFileSystem() { } public CosNFileSystem(NativeFileSystemStore store) { this.store = store; } /** * Return the protocol scheme for the FileSystem. * * @return <code>cosn</code> */ @Override public String getScheme() { return CosNFileSystem.SCHEME; } @Override public void initialize(URI name, Configuration conf) throws IOException { super.initialize(name, conf); this.bucket = name.getHost(); if (this.store == null) { this.store = createDefaultStore(conf); } this.store.initialize(name, conf); setConf(conf); this.uri = URI.create(name.getScheme() + "://" + name.getAuthority()); this.workingDir = new Path("/user", System.getProperty("user.name")).makeQualified( this.uri, this.getWorkingDirectory()); this.owner = getOwnerId(); this.group = getGroupId(); LOG.debug("owner:" + owner + ", group:" + group); BufferPool.getInstance().initialize(this.getConf()); // initialize the thread pool int uploadThreadPoolSize = this.getConf().getInt( CosNConfigKeys.UPLOAD_THREAD_POOL_SIZE_KEY, CosNConfigKeys.DEFAULT_UPLOAD_THREAD_POOL_SIZE ); int readAheadPoolSize = this.getConf().getInt( CosNConfigKeys.READ_AHEAD_QUEUE_SIZE, CosNConfigKeys.DEFAULT_READ_AHEAD_QUEUE_SIZE ); int ioThreadPoolSize = uploadThreadPoolSize + readAheadPoolSize / 3; long threadKeepAlive = this.getConf().getLong( CosNConfigKeys.THREAD_KEEP_ALIVE_TIME_KEY, CosNConfigKeys.DEFAULT_THREAD_KEEP_ALIVE_TIME ); this.boundedIOThreadPool = BlockingThreadPoolExecutorService.newInstance( ioThreadPoolSize / 2, ioThreadPoolSize, threadKeepAlive, TimeUnit.SECONDS, "cos-transfer-thread-pool"); int copyThreadPoolSize = this.getConf().getInt( CosNConfigKeys.COPY_THREAD_POOL_SIZE_KEY, CosNConfigKeys.DEFAULT_COPY_THREAD_POOL_SIZE ); this.boundedCopyThreadPool = BlockingThreadPoolExecutorService.newInstance( CosNConfigKeys.DEFAULT_COPY_THREAD_POOL_SIZE, copyThreadPoolSize, 60L, TimeUnit.SECONDS, "cos-copy-thread-pool"); } private static NativeFileSystemStore createDefaultStore(Configuration conf) { NativeFileSystemStore store = new CosNativeFileSystemStore(); RetryPolicy basePolicy = RetryPolicies.retryUpToMaximumCountWithFixedSleep( conf.getInt(CosNConfigKeys.COSN_MAX_RETRIES_KEY, CosNConfigKeys.DEFAULT_MAX_RETRIES), conf.getLong(CosNConfigKeys.COSN_RETRY_INTERVAL_KEY, CosNConfigKeys.DEFAULT_RETRY_INTERVAL), TimeUnit.SECONDS); Map<Class<? extends Exception>, RetryPolicy> exceptionToPolicyMap = new HashMap<>(); exceptionToPolicyMap.put(IOException.class, basePolicy); RetryPolicy methodPolicy = RetryPolicies.retryByException( RetryPolicies.TRY_ONCE_THEN_FAIL, exceptionToPolicyMap); Map<String, RetryPolicy> methodNameToPolicyMap = new HashMap<>(); methodNameToPolicyMap.put("storeFile", methodPolicy); methodNameToPolicyMap.put("rename", methodPolicy); return (NativeFileSystemStore) RetryProxy.create( NativeFileSystemStore.class, store, methodNameToPolicyMap); } private String getOwnerId() { return System.getProperty("user.name"); } private String getGroupId() { return System.getProperty("user.name"); } private String getOwnerInfo(boolean getOwnerId) { String ownerInfoId = ""; try { String userName = System.getProperty("user.name"); String command = "id -u " + userName; if (!getOwnerId) { command = "id -g " + userName; } Process child = Runtime.getRuntime().exec(command); child.waitFor(); // Get the input stream and read from it InputStream in = child.getInputStream(); StringBuilder strBuffer = new StringBuilder(); int c; while ((c = in.read()) != -1) { strBuffer.append((char) c); } in.close(); ownerInfoId = strBuffer.toString(); } catch (IOException | InterruptedException e) { LOG.error("Getting owner info occurs a exception", e); } return ownerInfoId; } private static String pathToKey(Path path) { if (path.toUri().getScheme() != null && path.toUri().getPath().isEmpty()) { // allow uris without trailing slash after bucket to refer to root, // like cosn://mybucket return ""; } if (!path.isAbsolute()) { throw new IllegalArgumentException("Path must be absolute: " + path); } String ret = path.toUri().getPath(); if (ret.endsWith("/") && (ret.indexOf("/") != ret.length() - 1)) { ret = ret.substring(0, ret.length() - 1); } return ret; } private static Path keyToPath(String key) { if (!key.startsWith(PATH_DELIMITER)) { return new Path("/" + key); } else { return new Path(key); } } private Path makeAbsolute(Path path) { if (path.isAbsolute()) { return path; } return new Path(workingDir, path); } /** * This optional operation is not yet supported. */ @Override public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException { throw new IOException("Not supported"); } @Override public FSDataOutputStream create(Path f, FsPermission permission, boolean overwrite, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { FileStatus fileStatus; try { fileStatus = getFileStatus(f); if (fileStatus.isDirectory()) { throw new FileAlreadyExistsException(f + " is a directory"); } if (!overwrite) { // path references a file and overwrite is disabled throw new FileAlreadyExistsException(f + " already exists"); } } catch (FileNotFoundException e) { LOG.debug("Creating a new file: [{}] in COS.", f); } Path absolutePath = makeAbsolute(f); String key = pathToKey(absolutePath); return new FSDataOutputStream( new CosNOutputStream(getConf(), store, key, blockSize, this.boundedIOThreadPool), statistics); } private boolean rejectRootDirectoryDelete(boolean isEmptyDir, boolean recursive) throws PathIOException { if (isEmptyDir) { return true; } if (recursive) { return false; } else { throw new PathIOException(this.bucket, "Can not delete root path"); } } @Override public FSDataOutputStream createNonRecursive(Path f, FsPermission permission, EnumSet<CreateFlag> flags, int bufferSize, short replication, long blockSize, Progressable progress) throws IOException { Path parent = f.getParent(); if (null != parent) { if (!getFileStatus(parent).isDirectory()) { throw new FileAlreadyExistsException("Not a directory: " + parent); } } return create(f, permission, flags.contains(CreateFlag.OVERWRITE), bufferSize, replication, blockSize, progress); } @Override public boolean delete(Path f, boolean recursive) throws IOException { LOG.debug("Ready to delete path: [{}]. recursive: [{}].", f, recursive); FileStatus status; try { status = getFileStatus(f); } catch (FileNotFoundException e) { LOG.debug("Ready to delete the file: [{}], but it does not exist.", f); return false; } Path absolutePath = makeAbsolute(f); String key = pathToKey(absolutePath); if (key.compareToIgnoreCase("/") == 0) { FileStatus[] fileStatuses = listStatus(f); return this.rejectRootDirectoryDelete( fileStatuses.length == 0, recursive); } if (status.isDirectory()) { if (!key.endsWith(PATH_DELIMITER)) { key += PATH_DELIMITER; } if (!recursive && listStatus(f).length > 0) { String errMsg = String.format("Can not delete the directory: [%s], as" + " it is not empty and option recursive is false.", f); throw new IOException(errMsg); } createParent(f); String priorLastKey = null; do { PartialListing listing = store.list( key, Constants.COS_MAX_LISTING_LENGTH, priorLastKey, true); for (FileMetadata file : listing.getFiles()) { store.delete(file.getKey()); } for (FileMetadata commonPrefix : listing.getCommonPrefixes()) { store.delete(commonPrefix.getKey()); } priorLastKey = listing.getPriorLastKey(); } while (priorLastKey != null); try { store.delete(key); } catch (Exception e) { LOG.error("Deleting the COS key: [{}] occurs an exception.", key, e); } } else { LOG.debug("Delete the file: {}", f); createParent(f); store.delete(key); } return true; } @Override public FileStatus getFileStatus(Path f) throws IOException { Path absolutePath = makeAbsolute(f); String key = pathToKey(absolutePath); if (key.length() == 0) { // root always exists return newDirectory(absolutePath); } LOG.debug("Call the getFileStatus to obtain the metadata for " + "the file: [{}].", f); FileMetadata meta = store.retrieveMetadata(key); if (meta != null) { if (meta.isFile()) { LOG.debug("Path: [{}] is a file. COS key: [{}]", f, key); return newFile(meta, absolutePath); } else { LOG.debug("Path: [{}] is a dir. COS key: [{}]", f, key); return newDirectory(meta, absolutePath); } } if (!key.endsWith(PATH_DELIMITER)) { key += PATH_DELIMITER; } // Considering that the object store's directory is a common prefix in // the object key, it needs to check the existence of the path by listing // the COS key. LOG.debug("List COS key: [{}] to check the existence of the path.", key); PartialListing listing = store.list(key, 1); if (listing.getFiles().length > 0 || listing.getCommonPrefixes().length > 0) { if (LOG.isDebugEnabled()) { LOG.debug("Path: [{}] is a directory. COS key: [{}]", f, key); } return newDirectory(absolutePath); } throw new FileNotFoundException( "No such file or directory '" + absolutePath + "'"); } @Override public URI getUri() { return uri; } /** * <p> * If <code>f</code> is a file, this method will make a single call to COS. * If <code>f</code> is a directory, * this method will make a maximum of ( <i>n</i> / 199) + 2 calls to cos, * where <i>n</i> is the total number of files * and directories contained directly in <code>f</code>. * </p> */ @Override public FileStatus[] listStatus(Path f) throws IOException { Path absolutePath = makeAbsolute(f); String key = pathToKey(absolutePath); if (key.length() > 0) { FileStatus fileStatus = this.getFileStatus(f); if (fileStatus.isFile()) { return new FileStatus[]{fileStatus}; } } if (!key.endsWith(PATH_DELIMITER)) { key += PATH_DELIMITER; } URI pathUri = absolutePath.toUri(); Set<FileStatus> status = new TreeSet<>(); String priorLastKey = null; do { PartialListing listing = store.list( key, Constants.COS_MAX_LISTING_LENGTH, priorLastKey, false); for (FileMetadata fileMetadata : listing.getFiles()) { Path subPath = keyToPath(fileMetadata.getKey()); if (fileMetadata.getKey().equals(key)) { // this is just the directory we have been asked to list. LOG.debug("The file list contains the COS key [{}] to be listed.", key); } else { status.add(newFile(fileMetadata, subPath)); } } for (FileMetadata commonPrefix : listing.getCommonPrefixes()) { Path subPath = keyToPath(commonPrefix.getKey()); String relativePath = pathUri.relativize(subPath.toUri()).getPath(); status.add( newDirectory(commonPrefix, new Path(absolutePath, relativePath))); } priorLastKey = listing.getPriorLastKey(); } while (priorLastKey != null); return status.toArray(new FileStatus[status.size()]); } private FileStatus newFile(FileMetadata meta, Path path) { return new FileStatus(meta.getLength(), false, 1, getDefaultBlockSize(), meta.getLastModified(), 0, null, this.owner, this.group, path.makeQualified(this.getUri(), this.getWorkingDirectory())); } private FileStatus newDirectory(Path path) { return new FileStatus(0, true, 1, 0, 0, 0, null, this.owner, this.group, path.makeQualified(this.getUri(), this.getWorkingDirectory())); } private FileStatus newDirectory(FileMetadata meta, Path path) { if (meta == null) { return newDirectory(path); } return new FileStatus(0, true, 1, 0, meta.getLastModified(), 0, null, this.owner, this.group, path.makeQualified(this.getUri(), this.getWorkingDirectory())); } /** * Validate the path from the bottom up. * * @param path The path to be validated * @throws FileAlreadyExistsException The specified path is an existing file * @throws IOException Getting the file status of the * specified path occurs * an IOException. */ private void validatePath(Path path) throws IOException { Path parent = path.getParent(); do { try { FileStatus fileStatus = getFileStatus(parent); if (fileStatus.isDirectory()) { break; } else { throw new FileAlreadyExistsException(String.format( "Can't make directory for path '%s', it is a file.", parent)); } } catch (FileNotFoundException e) { LOG.debug("The Path: [{}] does not exist.", path); } parent = parent.getParent(); } while (parent != null); } @Override public boolean mkdirs(Path f, FsPermission permission) throws IOException { try { FileStatus fileStatus = getFileStatus(f); if (fileStatus.isDirectory()) { return true; } else { throw new FileAlreadyExistsException("Path is a file: " + f); } } catch (FileNotFoundException e) { validatePath(f); } return mkDirRecursively(f, permission); } /** * Recursively create a directory. * * @param f Absolute path to the directory. * @param permission Directory permissions. Permission does not work for * the CosN filesystem currently. * @return Return true if the creation was successful, throw a IOException. * @throws IOException The specified path already exists or an error * creating the path. */ public boolean mkDirRecursively(Path f, FsPermission permission) throws IOException { Path absolutePath = makeAbsolute(f); List<Path> paths = new ArrayList<>(); do { paths.add(absolutePath); absolutePath = absolutePath.getParent(); } while (absolutePath != null); for (Path path : paths) { if (path.equals(new Path(CosNFileSystem.PATH_DELIMITER))) { break; } try { FileStatus fileStatus = getFileStatus(path); if (fileStatus.isFile()) { throw new FileAlreadyExistsException( String.format("Can't make directory for path: %s, " + "since it is a file.", f)); } if (fileStatus.isDirectory()) { break; } } catch (FileNotFoundException e) { LOG.debug("Making dir: [{}] in COS", f); String folderPath = pathToKey(makeAbsolute(f)); if (!folderPath.endsWith(PATH_DELIMITER)) { folderPath += PATH_DELIMITER; } store.storeEmptyFile(folderPath); } } return true; } private boolean mkdir(Path f) throws IOException { try { FileStatus fileStatus = getFileStatus(f); if (fileStatus.isFile()) { throw new FileAlreadyExistsException( String.format( "Can't make directory for path '%s' since it is a file.", f)); } } catch (FileNotFoundException e) { if (LOG.isDebugEnabled()) { LOG.debug("Make directory: [{}] in COS.", f); } String folderPath = pathToKey(makeAbsolute(f)); if (!folderPath.endsWith(PATH_DELIMITER)) { folderPath += PATH_DELIMITER; } store.storeEmptyFile(folderPath); } return true; } @Override public FSDataInputStream open(Path f, int bufferSize) throws IOException { FileStatus fs = getFileStatus(f); // will throw if the file doesn't // exist if (fs.isDirectory()) { throw new FileNotFoundException("'" + f + "' is a directory"); } LOG.info("Open the file: [{}] for reading.", f); Path absolutePath = makeAbsolute(f); String key = pathToKey(absolutePath); long fileSize = store.getFileLength(key); return new FSDataInputStream(new BufferedFSInputStream( new CosNInputStream(this.getConf(), store, statistics, key, fileSize, this.boundedIOThreadPool), bufferSize)); } @Override public boolean rename(Path src, Path dst) throws IOException { LOG.debug("Rename source path: [{}] to dest path: [{}].", src, dst); // Renaming the root directory is not allowed if (src.isRoot()) { LOG.debug("Cannot rename the root directory of a filesystem."); return false; } // check the source path whether exists or not FileStatus srcFileStatus = this.getFileStatus(src); // Source path and destination path are not allowed to be the same if (src.equals(dst)) { LOG.debug("Source path and dest path refer to " + "the same file or directory: [{}].", dst); throw new IOException("Source path and dest path refer " + "the same file or directory"); } // It is not allowed to rename a parent directory to its subdirectory Path dstParentPath; for (dstParentPath = dst.getParent(); null != dstParentPath && !src.equals(dstParentPath); dstParentPath = dstParentPath.getParent()) { // Recursively find the common parent path of the source and // destination paths. LOG.debug("Recursively find the common parent directory of the source " + "and destination paths. The currently found parent path: {}", dstParentPath); } if (null != dstParentPath) { LOG.debug("It is not allowed to rename a parent directory:[{}] " + "to its subdirectory:[{}].", src, dst); throw new IOException(String.format( "It is not allowed to rename a parent directory: %s " + "to its subdirectory: %s", src, dst)); } FileStatus dstFileStatus; try { dstFileStatus = this.getFileStatus(dst); // The destination path exists and is a file, // and the rename operation is not allowed. if (dstFileStatus.isFile()) { throw new FileAlreadyExistsException(String.format( "File: %s already exists", dstFileStatus.getPath())); } else { // The destination path is an existing directory, // and it is checked whether there is a file or directory // with the same name as the source path under the destination path dst = new Path(dst, src.getName()); FileStatus[] statuses; try { statuses = this.listStatus(dst); } catch (FileNotFoundException e) { statuses = null; } if (null != statuses && statuses.length > 0) { LOG.debug("Cannot rename source file: [{}] to dest file: [{}], " + "because the file already exists.", src, dst); throw new FileAlreadyExistsException( String.format( "File: %s already exists", dst ) ); } } } catch (FileNotFoundException e) { // destination path not exists Path tempDstParentPath = dst.getParent(); FileStatus dstParentStatus = this.getFileStatus(tempDstParentPath); if (!dstParentStatus.isDirectory()) { throw new IOException(String.format( "Cannot rename %s to %s, %s is a file", src, dst, dst.getParent() )); } // The default root directory is definitely there. } boolean result; if (srcFileStatus.isDirectory()) { result = this.copyDirectory(src, dst); } else { result = this.copyFile(src, dst); } if (!result) { //Since rename is a non-atomic operation, after copy fails, // it is not allowed to delete the data of the original path. return false; } else { return this.delete(src, true); } } private boolean copyFile(Path srcPath, Path dstPath) throws IOException { String srcKey = pathToKey(srcPath); String dstKey = pathToKey(dstPath); this.store.copy(srcKey, dstKey); return true; } private boolean copyDirectory(Path srcPath, Path dstPath) throws IOException { String srcKey = pathToKey(srcPath); if (!srcKey.endsWith(PATH_DELIMITER)) { srcKey += PATH_DELIMITER; } String dstKey = pathToKey(dstPath); if (!dstKey.endsWith(PATH_DELIMITER)) { dstKey += PATH_DELIMITER; } if (dstKey.startsWith(srcKey)) { throw new IOException( "can not copy a directory to a subdirectory of self"); } this.store.storeEmptyFile(dstKey); CosNCopyFileContext copyFileContext = new CosNCopyFileContext(); int copiesToFinishes = 0; String priorLastKey = null; do { PartialListing objectList = this.store.list( srcKey, Constants.COS_MAX_LISTING_LENGTH, priorLastKey, true); for (FileMetadata file : objectList.getFiles()) { this.boundedCopyThreadPool.execute(new CosNCopyFileTask( this.store, file.getKey(), dstKey.concat(file.getKey().substring(srcKey.length())), copyFileContext)); copiesToFinishes++; if (!copyFileContext.isCopySuccess()) { break; } } priorLastKey = objectList.getPriorLastKey(); } while (null != priorLastKey); copyFileContext.lock(); try { copyFileContext.awaitAllFinish(copiesToFinishes); } catch (InterruptedException e) { LOG.warn("interrupted when wait copies to finish"); } finally { copyFileContext.lock(); } return copyFileContext.isCopySuccess(); } private void createParent(Path path) throws IOException { Path parent = path.getParent(); if (parent != null) { String parentKey = pathToKey(parent); LOG.debug("Create parent key: {}", parentKey); if (!parentKey.equals(PATH_DELIMITER)) { String key = pathToKey(makeAbsolute(parent)); if (key.length() > 0) { try { store.storeEmptyFile(key + PATH_DELIMITER); } catch (IOException e) { LOG.debug("Store a empty file in COS failed.", e); throw e; } } } } } @Override @SuppressWarnings("deprecation") public long getDefaultBlockSize() { return getConf().getLong( CosNConfigKeys.COSN_BLOCK_SIZE_KEY, CosNConfigKeys.DEFAULT_BLOCK_SIZE); } /** * Set the working directory to the given directory. */ @Override public void setWorkingDirectory(Path newDir) { workingDir = newDir; } @Override public Path getWorkingDirectory() { return workingDir; } @Override public String getCanonicalServiceName() { // Does not support Token return null; } @Override public void close() throws IOException { try { this.store.close(); this.boundedIOThreadPool.shutdown(); this.boundedCopyThreadPool.shutdown(); } finally { super.close(); } } }
CosNFileSystem
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/multitenancy/SchemaBasedMultitenancyTest.java
{ "start": 3166, "end": 3243 }
class ____ { @Id String ssn; private String name; } public static
Person
java
quarkusio__quarkus
integration-tests/maven/src/test/resources-filtered/projects/test-source-sets/src/test/java/org/acme/GreetingResourceTest.java
{ "start": 103, "end": 295 }
class ____ { @Test void shouldReturnExpectedValue() { String actual = new GreetingResource().hello(); Assertions.assertEquals(actual, GreetingResource.HELLO); } }
GreetingResourceTest
java
grpc__grpc-java
interop-testing/src/test/java/io/grpc/testing/integration/TransportCompressionTest.java
{ "start": 6667, "end": 7866 }
class ____ implements Codec { volatile boolean anyRead; volatile boolean anyWritten; volatile Codec delegate; private final String actualName; public Fzip(String actualName, Codec delegate) { this.actualName = actualName; this.delegate = delegate; } @Override public String getMessageEncoding() { return actualName; } @Override public OutputStream compress(OutputStream os) throws IOException { return new FilterOutputStream(delegate.compress(os)) { @Override public void write(int b) throws IOException { super.write(b); anyWritten = true; } }; } @Override public InputStream decompress(InputStream is) throws IOException { return new FilterInputStream(delegate.decompress(is)) { @Override public int read() throws IOException { int val = super.read(); anyRead = true; return val; } @Override public int read(byte[] b, int off, int len) throws IOException { int total = super.read(b, off, len); anyRead = true; return total; } }; } } }
Fzip
java
apache__maven
compat/maven-compat/src/main/java/org/apache/maven/profiles/activation/FileProfileActivator.java
{ "start": 1430, "end": 3723 }
class ____ extends DetectedProfileActivator implements LogEnabled { private Logger logger; @Override protected boolean canDetectActivation(Profile profile) { return profile.getActivation() != null && profile.getActivation().getFile() != null; } @Override public boolean isActive(Profile profile) { Activation activation = profile.getActivation(); ActivationFile actFile = activation.getFile(); if (actFile != null) { // check if the file exists, if it does then the profile will be active String fileString = actFile.getExists(); RegexBasedInterpolator interpolator = new RegexBasedInterpolator(); try { interpolator.addValueSource(new EnvarBasedValueSource()); } catch (IOException e) { // ignored } interpolator.addValueSource(new MapBasedValueSource(System.getProperties())); try { if (fileString != null && !fileString.isEmpty()) { fileString = interpolator.interpolate(fileString, "").replace("\\", "/"); File file = new File(fileString); return file.exists(); } // check if the file is missing, if it is then the profile will be active fileString = actFile.getMissing(); if (fileString != null && !fileString.isEmpty()) { fileString = interpolator.interpolate(fileString, "").replace("\\", "/"); File file = new File(fileString); return !file.exists(); } } catch (InterpolationException e) { if (logger.isDebugEnabled()) { logger.debug("Failed to interpolate missing file location for profile activator: " + fileString, e); } else { logger.warn("Failed to interpolate missing file location for profile activator: " + fileString + ", enable verbose output (-X) for more details"); } } } return false; } @Override public void enableLogging(Logger logger) { this.logger = logger; } }
FileProfileActivator
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/misc/GenericTypeInfoTest.java
{ "start": 1211, "end": 3529 }
class ____ { @Test public void testSerializerTree() { @SuppressWarnings("unchecked") TypeInformation<CollectionDataStreams.PojoWithCollectionGeneric> ti = (TypeInformation<CollectionDataStreams.PojoWithCollectionGeneric>) TypeExtractor.createTypeInfo( CollectionDataStreams.PojoWithCollectionGeneric.class); final String serTree = Utils.getSerializerTree(ti) // normalize String/BigInteger representations as they vary across java // versions // do 2 passes for BigInteger since they occur at different indentations .replaceAll("(java\\.lang\\.String\\R)( {12}\\S*\\R)+", "$1") .replaceAll( "( {4}[a-zA-Z]+:java\\.math\\.BigInteger\\R)( {8}\\S*\\R)+", "$1") .replaceAll( "( {8}[a-zA-Z]+:java\\.math\\.BigInteger\\R)( {12}\\S*\\R)+", "$1"); Assert.assertThat( serTree, equalTo( "GenericTypeInfo (PojoWithCollectionGeneric)\n" + " pojos:java.util.List\n" + " key:int\n" + " sqlDate:java.sql.Date\n" + " bigInt:java.math.BigInteger\n" + " bigDecimalKeepItNull:java.math.BigDecimal\n" + " intVal:java.math.BigInteger\n" + " scale:int\n" + " scalaBigInt:scala.math.BigInt\n" + " bigInteger:java.math.BigInteger\n" + " mixed:java.util.List\n" + " makeMeGeneric:org.apache.flink.test.operators.util.CollectionDataStreams$PojoWithDateAndEnum\n" + " group:java.lang.String\n" + " date:java.util.Date\n" + " cat:org.apache.flink.test.operators.util.CollectionDataStreams$Category (is enum)\n")); } }
GenericTypeInfoTest
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/IfThenElseFunctionITCase.java
{ "start": 1226, "end": 2552 }
class ____ extends BuiltInFunctionTestBase { @Override Stream<TestSetSpec> getTestSetSpecs() { return Stream.of( TestSetSpec.forFunction(BuiltInFunctionDefinitions.IF) .onFieldsWithData(2) .andDataTypes(DataTypes.INT()) .testResult( Expressions.ifThenElse( $("f0").isGreater(lit(0)), lit("GREATER"), lit("SMALLER")), "CASE WHEN f0 > 0 THEN 'GREATER' ELSE 'SMALLER' END", "GREATER", DataTypes.CHAR(7).notNull()) .testResult( Expressions.ifThenElse( $("f0").isGreater(lit(0)), lit("GREATER"), Expressions.ifThenElse( $("f0").isEqual(0), lit("EQUAL"), lit("SMALLER"))), "CASE WHEN f0 > 0 THEN 'GREATER' ELSE CASE WHEN f0 = 0 THEN 'EQUAL' ELSE 'SMALLER' END END", "GREATER", DataTypes.VARCHAR(7).notNull())); } }
IfThenElseFunctionITCase
java
quarkusio__quarkus
extensions/hibernate-validator/deployment/src/test/java/io/quarkus/hibernate/validator/test/FailFastTest.java
{ "start": 1419, "end": 1641 }
class ____ { @NotNull String b; @NotNull @Email String c; @Pattern(regexp = ".*\\.txt$") String file; @Valid Set<B> bs = new HashSet<B>(); }
A
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/flogger/FloggerWithCause.java
{ "start": 2483, "end": 7185 }
class ____ extends BugChecker implements MethodInvocationTreeMatcher { private static final String STACK_SIZE_MEDIUM_IMPORT = "com.google.common.flogger.StackSize.MEDIUM"; private static final Matcher<ExpressionTree> WITH_CAUSE_MATCHER = instanceMethod().onDescendantOf("com.google.common.flogger.LoggingApi").named("withCause"); private static final Matcher<ExpressionTree> FIXABLE_THROWABLE_MATCHER = constructor() .forClass( TypePredicates.isExactTypeAny( ImmutableList.of( "java.lang.AssertionError", "java.lang.Error", "java.lang.Exception", "java.lang.IllegalArgumentException", "java.lang.IllegalStateException", "java.lang.RuntimeException", "java.lang.Throwable", "com.google.photos.be.util.StackTraceLoggerException"))) .withParameters(ImmutableList.of()); private static final Matcher<Tree> THROWABLE_MATCHER = isSubtypeOf("java.lang.Throwable"); private static final Matcher<ExpressionTree> THROWABLE_STRING_MATCHER = Matchers.anyOf( instanceMethod().onDescendantOf("java.lang.Throwable").named("getMessage"), instanceMethod().onDescendantOf("java.lang.Throwable").named("toString")); @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (!WITH_CAUSE_MATCHER.matches(tree, state)) { return Description.NO_MATCH; } ExpressionTree cause = Iterables.getOnlyElement(tree.getArguments()); if (cause instanceof NewClassTree) { Optional<ExpressionTree> throwableArgument = getThrowableArgument(cause, state); if (throwableArgument.isPresent() || FIXABLE_THROWABLE_MATCHER.matches(cause, state)) { List<Fix> fixes = getFixes(tree, state, throwableArgument.orElse(null)); return getDescription(tree, fixes); } } return Description.NO_MATCH; } private Description getDescription(MethodInvocationTree tree, List<Fix> fixes) { Description.Builder description = buildDescription(tree); for (Fix fix : fixes) { description.addFix(fix); } return description.build(); } private static List<Fix> getFixes( MethodInvocationTree tree, VisitorState state, ExpressionTree throwableArgument) { if (throwableArgument != null) { String withCauseReplacement = ".withCause(" + state.getSourceForNode(throwableArgument) + ")"; String withStackTraceAndWithCauseReplacement = ".withStackTrace(MEDIUM)" + withCauseReplacement; return Arrays.asList( getFix(tree, state, withCauseReplacement), getFix(tree, state, withStackTraceAndWithCauseReplacement, STACK_SIZE_MEDIUM_IMPORT)); } return Collections.singletonList( getFix(tree, state, ".withStackTrace(MEDIUM)", STACK_SIZE_MEDIUM_IMPORT)); } private static Optional<ExpressionTree> getThrowableArgument( ExpressionTree cause, VisitorState state) { for (ExpressionTree argument : ((JCNewClass) cause).getArguments()) { if (THROWABLE_MATCHER.matches(argument, state)) { return Optional.of(argument); } if (THROWABLE_STRING_MATCHER.matches(argument, state)) { return Optional.ofNullable(ASTHelpers.getReceiver(argument)); } } return Optional.empty(); } /** * Returns fix that has current method replaced with provided method replacement string and * provided static import added to it */ private static Fix getFix( MethodInvocationTree tree, VisitorState state, String replacement, String importString) { return getFixBuilder(tree, state, replacement).addStaticImport(importString).build(); } /** Returns fix that has current method replaced with provided method replacement string */ private static Fix getFix(MethodInvocationTree tree, VisitorState state, String replacement) { return getFixBuilder(tree, state, replacement).build(); } private static SuggestedFix.Builder getFixBuilder( MethodInvocationTree tree, VisitorState state, String methodReplacement) { int methodStart = getMethodStart(tree, state); int methodEnd = getMethodEnd(tree, state); return SuggestedFix.builder().replace(methodStart, methodEnd, methodReplacement); } private static int getMethodStart(MethodInvocationTree tree, VisitorState state) { return state.getEndPosition(ASTHelpers.getReceiver(tree)); } private static int getMethodEnd(MethodInvocationTree tree, VisitorState state) { return state.getEndPosition(tree); } }
FloggerWithCause
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/webapp/dao/ResourceUtilizationInfo.java
{ "start": 1294, "end": 3002 }
class ____ { protected int nodePhysicalMemoryMB; protected int nodeVirtualMemoryMB; protected double nodeCPUUsage; protected int aggregatedContainersPhysicalMemoryMB; protected int aggregatedContainersVirtualMemoryMB; protected double containersCPUUsage; public ResourceUtilizationInfo() { } // JAXB needs this public ResourceUtilizationInfo(RMNode ni) { // update node and containers resource utilization ResourceUtilization nodeUtilization = ni.getNodeUtilization(); if (nodeUtilization != null) { this.nodePhysicalMemoryMB = nodeUtilization.getPhysicalMemory(); this.nodeVirtualMemoryMB = nodeUtilization.getVirtualMemory(); this.nodeCPUUsage = nodeUtilization.getCPU(); } ResourceUtilization containerAggrUtilization = ni .getAggregatedContainersUtilization(); if (containerAggrUtilization != null) { this.aggregatedContainersPhysicalMemoryMB = containerAggrUtilization .getPhysicalMemory(); this.aggregatedContainersVirtualMemoryMB = containerAggrUtilization .getVirtualMemory(); this.containersCPUUsage = containerAggrUtilization.getCPU(); } } public int getNodePhysicalMemoryMB() { return nodePhysicalMemoryMB; } public int getNodeVirtualMemoryMB() { return nodeVirtualMemoryMB; } public int getAggregatedContainersPhysicalMemoryMB() { return aggregatedContainersPhysicalMemoryMB; } public int getAggregatedContainersVirtualMemoryMB() { return aggregatedContainersVirtualMemoryMB; } public double getNodeCPUUsage() { return nodeCPUUsage; } public double getContainersCPUUsage() { return containersCPUUsage; } }
ResourceUtilizationInfo
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/injection/guice/Scopes.java
{ "start": 861, "end": 2328 }
class ____ { private Scopes() {} /** * Scopes an internal factory. */ static <T> InternalFactory<? extends T> scope(InjectorImpl injector, InternalFactory<? extends T> creator, Scoping scoping) { return switch (scoping) { case UNSCOPED -> creator; case EAGER_SINGLETON -> new InternalFactoryToProviderAdapter<>(Initializables.of(new Provider<>() { private volatile T instance; @Override public T get() { if (instance == null) { /* * Use a pretty coarse lock. We don't want to run into deadlocks * when two threads try to load circularly-dependent objects. * Maybe one of these days we will identify independent graphs of * objects and offer to load them in parallel. */ synchronized (injector) { if (instance == null) { instance = new ProviderToInternalFactoryAdapter<>(injector, creator).get(); } } } return instance; } @Override public String toString() { return creator + "[SINGLETON]"; } })); }; } }
Scopes
java
spring-projects__spring-framework
spring-webmvc/src/test/java/org/springframework/web/servlet/function/DefaultServerRequestTests.java
{ "start": 23439, "end": 23535 }
interface ____ { } @SuppressWarnings("unused") private static final
ParameterizedHttpMethodTest
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/authz/accesscontrol/OptOutQueryCache.java
{ "start": 1130, "end": 4099 }
class ____ extends IndexQueryCache { private static final Logger logger = LogManager.getLogger(IndexQueryCache.class); private final ThreadContext context; public OptOutQueryCache(final Index index, final IndicesQueryCache indicesQueryCache, final ThreadContext context) { super(index, indicesQueryCache); this.context = Objects.requireNonNull(context, "threadContext must not be null"); } @Override public Weight doCache(Weight weight, QueryCachingPolicy policy) { IndicesAccessControl indicesAccessControl = AuthorizationServiceField.INDICES_PERMISSIONS_VALUE.get(context); if (indicesAccessControl == null) { logger.debug("opting out of the query cache for index [{}]. current request doesn't hold indices permissions", index); return weight; } IndicesAccessControl.IndexAccessControl indexAccessControl = indicesAccessControl.getIndexPermissions(index.getName()); if (indexAccessControl != null && indexAccessControl.getFieldPermissions().hasFieldLevelSecurity()) { if (cachingIsSafe(weight, indexAccessControl)) { logger.trace("not opting out of the query cache. request for index [{}] is safe to cache", index); return super.doCache(weight, policy); } else { logger.trace("opting out of the query cache. request for index [{}] is unsafe to cache", index); return weight; } } else { logger.trace("not opting out of the query cache. request for index [{}] has field level security disabled", index); return super.doCache(weight, policy); } } /** * Returns true if its safe to use the query cache for this query. */ static boolean cachingIsSafe(Weight weight, IndicesAccessControl.IndexAccessControl permissions) { // support caching for common queries, by inspecting the field try { weight.getQuery().visit(new QueryVisitor() { @Override public QueryVisitor getSubVisitor(BooleanClause.Occur occur, org.apache.lucene.search.Query parent) { return this; // we want to use the same visitor for must_not clauses too } @Override public boolean acceptField(String field) { // don't cache any internal fields (e.g. _field_names), these are complicated. if (field.startsWith("_") || permissions.getFieldPermissions().grantsAccessTo(field) == false) { throw new FLSQueryNotCacheable("Query field has FLS permissions"); } return super.acceptField(field); } }); } catch (FLSQueryNotCacheable e) { return false; } // we can cache, all fields are ok return true; } private static
OptOutQueryCache
java
apache__spark
core/src/test/java/test/org/apache/spark/JavaTaskContextCompileCheck.java
{ "start": 1954, "end": 2459 }
class ____ implements TaskCompletionListener { @Override public void onTaskCompletion(TaskContext context) { context.isCompleted(); context.isInterrupted(); context.stageId(); context.stageAttemptNumber(); context.partitionId(); context.addTaskCompletionListener(this); } } /** * A simple implementation of TaskCompletionListener that makes sure TaskCompletionListener and * TaskContext is Java friendly. */ static
JavaTaskCompletionListenerImpl
java
quarkusio__quarkus
extensions/vertx/deployment/src/test/java/io/quarkus/vertx/verticles/MyBeanVerticle.java
{ "start": 267, "end": 569 }
class ____ extends AbstractVerticle { @ConfigProperty(name = "address") String address; @Override public Uni<Void> asyncStart() { return vertx.eventBus().consumer(address) .handler(m -> m.reply("hello")) .completionHandler(); } }
MyBeanVerticle
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/impl/engine/DefaultSupervisingRouteControllerTest.java
{ "start": 8946, "end": 9201 }
class ____ extends SedaComponent { @Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) { return new MyJmsEndpoint(remaining); } } private static
MyJmsComponent
java
micronaut-projects__micronaut-core
core-processor/src/main/java/io/micronaut/expressions/EvaluatedExpressionWriter.java
{ "start": 2206, "end": 6440 }
class ____ implements ClassOutputWriter { private static final Method DO_EVALUATE_METHOD = ReflectionUtils.getRequiredMethod(AbstractEvaluatedExpression.class, "doEvaluate", ExpressionEvaluationContext.class); private final ExpressionWithContext expressionMetadata; private final VisitorContext visitorContext; private final Element originatingElement; private byte[] output; public EvaluatedExpressionWriter(ExpressionWithContext expressionMetadata, VisitorContext visitorContext, Element originatingElement) { this.visitorContext = visitorContext; this.expressionMetadata = expressionMetadata; this.originatingElement = originatingElement; } /** * Finish generating the expression class. */ public void finish() { String expressionClassName = expressionMetadata.expressionClassName(); ClassDef objectDef = generateClassDef(expressionClassName); output = ByteCodeWriterUtils.writeByteCode( objectDef, visitorContext ); } @Override public void accept(ClassWriterOutputVisitor outputVisitor) throws IOException { try (OutputStream outputStream = outputVisitor.visitClass(expressionMetadata.expressionClassName(), originatingElement)) { outputStream.write(output); } output = null; } private ClassDef generateClassDef(String expressionClassName) { return ClassDef.builder(expressionClassName) .synthetic() .addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addAnnotation(Generated.class) .superclass(ClassTypeDef.of(AbstractEvaluatedExpression.class)) .addMethod(MethodDef.constructor() .addModifiers(Modifier.PUBLIC) .addParameter(Object.class) .build((aThis, methodParameters) -> aThis.superRef().invokeConstructor(methodParameters.get(0))) ) .addMethod(MethodDef.override(DO_EVALUATE_METHOD) .build((aThis, methodParameters) -> { List<StatementDef> statements = new ArrayList<>(); ExpressionCompilationContext ctx = new ExpressionCompilationContext( new ExpressionVisitorContext(expressionMetadata.evaluationContext(), visitorContext), methodParameters.get(0), statements ); Object annotationValue = expressionMetadata.annotationValue(); try { statements.add( new CompoundEvaluatedExpressionParser(annotationValue) .parse() .compile(ctx) .returning() ); } catch (ExpressionParsingException | ExpressionCompilationException ex) { throw failCompilation(ex, annotationValue); } return StatementDef.multi(statements); })) .build(); } private ProcessingException failCompilation(Throwable ex, Object initialAnnotationValue) { String strRepresentation = null; if (initialAnnotationValue instanceof String str) { strRepresentation = str; } else if (initialAnnotationValue instanceof String[] strArray) { strRepresentation = Arrays.toString(strArray); } String message = null; if (ex instanceof ExpressionParsingException parsingException) { message = "Failed to parse evaluated expression [" + strRepresentation + "]. " + "Cause: " + parsingException.getMessage(); } else if (ex instanceof ExpressionCompilationException compilationException) { message = "Failed to compile evaluated expression [" + strRepresentation + "]. " + "Cause: " + compilationException.getMessage(); } return new ProcessingException(originatingElement, message, ex); } }
EvaluatedExpressionWriter
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/placement/csmappingrule/MappingRuleConditionalVariables.java
{ "start": 1962, "end": 4930 }
class ____ implements MappingRuleConditionalVariable { /** * This is the name of the variable we are replacing. */ public final static String VARIABLE_NAME = "%secondary_group"; /** * We need an instance of queue manager in order to look for queues under * the parent path. */ private CapacitySchedulerQueueManager queueManager; /** * We store the potential secondary_groups candidates in this list, it must * not contain the primary group. */ private List<String> potentialGroups; /** * Constructor requires a queue manager instance and a list of potential * secondary groups. * @param qm The queue manager which will be used to check which potential * secondary group should be used. * @param groups List of potential secondary groups. */ public SecondaryGroupVariable(CapacitySchedulerQueueManager qm, List<String> groups) { queueManager = qm; potentialGroups = groups; } /** * Method used to evaluate the variable when used in a path. * @param parts Split representation of the path. * @param currentIndex The index of the evaluation in the path. This shows * which part is currently being evaluated. * @return Substituted queue path part, this method will only return the * value of the conditional variable, not the whole path. */ public String evaluateInPath(String[] parts, int currentIndex) { //First we need to determine the parent path (if any) StringBuilder parentBuilder = new StringBuilder(); //Building the parent prefix, if we don't have any parent path //in case of currentIndex == 0 we will have an empty prefix. for (int i = 0; i < currentIndex; i++) { parentBuilder.append(parts[i]); //Generally this is not a good idea, we would need a condition, to not //append a '.' after the last part, however we are generating parent //prefix paths, so we need paths prefixes, like 'root.group.something.' parentBuilder.append("."); } //We'll use this prefix to lookup the groups, when we have a parent //provided we need to find a queue under that parent, which matches the //name of the secondaryGroup, if we don't have a parent the prefix is //empty String lookupPrefix = parentBuilder.toString(); //Going through the potential groups to check if there is a matching queue for (String group : potentialGroups) { String path = lookupPrefix + group; if (queueManager.getQueue(path) != null) { return group; } } //No valid group found return ""; } @Override public String toString() { return "SecondaryGroupVariable{" + "variableName='" + VARIABLE_NAME + "'," + "groups=" + potentialGroups + "}"; } } }
SecondaryGroupVariable
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/ml/action/GetDatafeedsAction.java
{ "start": 1537, "end": 3667 }
class ____ extends MasterNodeReadRequest<Request> { public static final String ALLOW_NO_MATCH = "allow_no_match"; private String datafeedId; private boolean allowNoMatch = true; public Request(String datafeedId) { this(); this.datafeedId = ExceptionsHelper.requireNonNull(datafeedId, DatafeedConfig.ID.getPreferredName()); } public Request() { super(TRAPPY_IMPLICIT_DEFAULT_MASTER_NODE_TIMEOUT); local(true); } public Request(StreamInput in) throws IOException { super(in); datafeedId = in.readString(); allowNoMatch = in.readBoolean(); } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeString(datafeedId); out.writeBoolean(allowNoMatch); } public String getDatafeedId() { return datafeedId; } public boolean allowNoMatch() { return allowNoMatch; } public void setAllowNoMatch(boolean allowNoMatch) { this.allowNoMatch = allowNoMatch; } @Override public ActionRequestValidationException validate() { return null; } @Override public int hashCode() { return Objects.hash(datafeedId, allowNoMatch); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Request other = (Request) obj; return Objects.equals(datafeedId, other.datafeedId) && Objects.equals(allowNoMatch, other.allowNoMatch); } @Override public Task createTask(long id, String type, String action, TaskId parentTaskId, Map<String, String> headers) { return new CancellableTask(id, type, action, format("get_datafeeds[%s]", datafeedId), parentTaskId, headers); } } public static
Request
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/function/scalar/convert/ToBooleanFromUnsignedLongEvaluator.java
{ "start": 1055, "end": 3892 }
class ____ extends AbstractConvertFunction.AbstractEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(ToBooleanFromUnsignedLongEvaluator.class); private final EvalOperator.ExpressionEvaluator ul; public ToBooleanFromUnsignedLongEvaluator(Source source, EvalOperator.ExpressionEvaluator ul, DriverContext driverContext) { super(driverContext, source); this.ul = ul; } @Override public EvalOperator.ExpressionEvaluator next() { return ul; } @Override public Block evalVector(Vector v) { LongVector vector = (LongVector) v; int positionCount = v.getPositionCount(); if (vector.isConstant()) { return driverContext.blockFactory().newConstantBooleanBlockWith(evalValue(vector, 0), positionCount); } try (BooleanBlock.Builder builder = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) { for (int p = 0; p < positionCount; p++) { builder.appendBoolean(evalValue(vector, p)); } return builder.build(); } } private boolean evalValue(LongVector container, int index) { long value = container.getLong(index); return ToBoolean.fromUnsignedLong(value); } @Override public Block evalBlock(Block b) { LongBlock block = (LongBlock) b; int positionCount = block.getPositionCount(); try (BooleanBlock.Builder builder = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) { for (int p = 0; p < positionCount; p++) { int valueCount = block.getValueCount(p); int start = block.getFirstValueIndex(p); int end = start + valueCount; boolean positionOpened = false; boolean valuesAppended = false; for (int i = start; i < end; i++) { boolean value = evalValue(block, i); if (positionOpened == false && valueCount > 1) { builder.beginPositionEntry(); positionOpened = true; } builder.appendBoolean(value); valuesAppended = true; } if (valuesAppended == false) { builder.appendNull(); } else if (positionOpened) { builder.endPositionEntry(); } } return builder.build(); } } private boolean evalValue(LongBlock container, int index) { long value = container.getLong(index); return ToBoolean.fromUnsignedLong(value); } @Override public String toString() { return "ToBooleanFromUnsignedLongEvaluator[" + "ul=" + ul + "]"; } @Override public void close() { Releasables.closeExpectNoException(ul); } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += ul.baseRamBytesUsed(); return baseRamBytesUsed; } public static
ToBooleanFromUnsignedLongEvaluator
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/phoenix/PhoenixUpsertTest_1.java
{ "start": 458, "end": 2089 }
class ____ extends TestCase { public void test_0() throws Exception { String sql = "upsert into t_1 (a BIGINT,b,c) values (?,?,?)"; List<SQLStatement> statementList = SQLUtils.parseStatements(sql, JdbcConstants.PHOENIX); SQLStatement stmt = statementList.get(0); assertEquals(1, statementList.size()); SchemaStatVisitor visitor = new PhoenixSchemaStatVisitor(); stmt.accept(visitor); // System.out.println("Tables : " + visitor.getTables()); // System.out.println("fields : " + visitor.getColumns()); // System.out.println("coditions : " + visitor.getConditions()); // System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertEquals(3, visitor.getColumns().size()); assertEquals(0, visitor.getConditions().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("t_1"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("t_1", "a"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("t_1", "b"))); assertTrue(visitor.getColumns().contains(new TableStat.Column("t_1", "c"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "first_name"))); // assertTrue(visitor.getColumns().contains(new Column("mytable", "full_name"))); String output = SQLUtils.toSQLString(stmt, JdbcConstants.PHOENIX); assertEquals("UPSERT INTO t_1 (a BIGINT, b, c)\n" + "VALUES (?, ?, ?)", // output); } }
PhoenixUpsertTest_1
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/webapp/hamlet2/HamletSpec.java
{ "start": 52909, "end": 53249 }
interface ____ extends _Child { /** * Add a OPTION element. * @return a new OPTION element builder */ OPTION option(); /** * Add a complete OPTION element. * @param cdata the content * @return the current element builder */ _Option option(String cdata); } /** * */ public
_Option