language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
apache__flink
flink-runtime/src/test/java/org/apache/flink/runtime/checkpoint/hooks/MasterHooksTest.java
{ "start": 1338, "end": 7475 }
class ____ { // ------------------------------------------------------------------------ // hook management // ------------------------------------------------------------------------ @Test void wrapHook() throws Exception { final String id = "id"; Thread thread = Thread.currentThread(); final ClassLoader originalClassLoader = thread.getContextClassLoader(); final ClassLoader userClassLoader = new URLClassLoader(new URL[0]); final CompletableFuture<Void> onceRunnableFuture = new CompletableFuture<>(); final Runnable onceRunnable = () -> { assertThat(Thread.currentThread().getContextClassLoader()) .isEqualTo(userClassLoader); assertThat(onceRunnableFuture) .withFailMessage("The runnable shouldn't be called multiple times.") .isNotDone(); onceRunnableFuture.complete(null); }; final CompletableFuture<Void> getIdentifierFuture = new CompletableFuture<>(); final CompletableFuture<Void> closeFuture = new CompletableFuture<>(); final CompletableFuture<Void> restoreCheckpointFuture = new CompletableFuture<>(); final CompletableFuture<Void> createCheckpointDataSerializerFuture = new CompletableFuture<>(); MasterTriggerRestoreHook<String> hook = new MasterTriggerRestoreHook<String>() { @Override public String getIdentifier() { assertThat(Thread.currentThread().getContextClassLoader()) .isEqualTo(userClassLoader); assertThat(getIdentifierFuture) .withFailMessage("The method shouldn't be called multiple times.") .isNotDone(); getIdentifierFuture.complete(null); return id; } @Override public void reset() { assertThat(Thread.currentThread().getContextClassLoader()) .isEqualTo(userClassLoader); } @Override public void close() { assertThat(Thread.currentThread().getContextClassLoader()) .isEqualTo(userClassLoader); assertThat(closeFuture) .withFailMessage("The method shouldn't be called multiple times.") .isNotDone(); closeFuture.complete(null); } @Nullable @Override public CompletableFuture<String> triggerCheckpoint( long checkpointId, long timestamp, Executor executor) { assertThat(Thread.currentThread().getContextClassLoader()) .isEqualTo(userClassLoader); executor.execute(onceRunnable); return null; } @Override public void restoreCheckpoint( long checkpointId, @Nullable String checkpointData) { assertThat(Thread.currentThread().getContextClassLoader()) .isEqualTo(userClassLoader); assertThat(checkpointId).isZero(); assertThat(checkpointData).isEmpty(); assertThat(restoreCheckpointFuture) .withFailMessage("The method shouldn't be called multiple times.") .isNotDone(); restoreCheckpointFuture.complete(null); } @Nullable @Override public SimpleVersionedSerializer<String> createCheckpointDataSerializer() { assertThat(Thread.currentThread().getContextClassLoader()) .isEqualTo(userClassLoader); assertThat(createCheckpointDataSerializerFuture) .withFailMessage("The method shouldn't be called multiple times.") .isNotDone(); createCheckpointDataSerializerFuture.complete(null); return null; } }; MasterTriggerRestoreHook<String> wrapped = MasterHooks.wrapHook(hook, userClassLoader); // verify getIdentifier wrapped.getIdentifier(); assertThat(getIdentifierFuture).isCompleted(); assertThat(thread.getContextClassLoader()).isEqualTo(originalClassLoader); // verify triggerCheckpoint and its wrapped executor TestExecutor testExecutor = new TestExecutor(); wrapped.triggerCheckpoint(0L, 0, testExecutor); assertThat(thread.getContextClassLoader()).isEqualTo(originalClassLoader); assertThat(testExecutor.command).isNotNull(); testExecutor.command.run(); assertThat(onceRunnableFuture).isCompleted(); assertThat(thread.getContextClassLoader()).isEqualTo(originalClassLoader); // verify restoreCheckpoint wrapped.restoreCheckpoint(0L, ""); assertThat(restoreCheckpointFuture).isCompleted(); assertThat(thread.getContextClassLoader()).isEqualTo(originalClassLoader); // verify createCheckpointDataSerializer wrapped.createCheckpointDataSerializer(); assertThat(createCheckpointDataSerializerFuture).isCompleted(); assertThat(thread.getContextClassLoader()).isEqualTo(originalClassLoader); // verify close wrapped.close(); assertThat(closeFuture).isCompleted(); assertThat(thread.getContextClassLoader()).isEqualTo(originalClassLoader); } private static
MasterHooksTest
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/server/header/XXssProtectionServerHttpHeadersWriterTests.java
{ "start": 1155, "end": 3473 }
class ____ { ServerWebExchange exchange = MockServerWebExchange.from(MockServerHttpRequest.get("/").build()); HttpHeaders headers = this.exchange.getResponse().getHeaders(); XXssProtectionServerHttpHeadersWriter writer = new XXssProtectionServerHttpHeadersWriter(); @Test void setHeaderValueNullThenThrowsIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.writer.setHeaderValue(null)) .withMessage("headerValue cannot be null"); } @Test public void writeHeadersWhenNoHeadersThenWriteHeaders() { this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers.headerNames()).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("0"); } @Test public void writeHeadersWhenHeaderWrittenThenDoesNotOverride() { String headerValue = "value"; this.headers.set(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION, headerValue); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers.headerNames()).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly(headerValue); } @Test void writeHeadersWhenDisabledThenWriteHeaders() { this.writer.setHeaderValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.DISABLED); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers.headerNames()).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("0"); } @Test void writeHeadersWhenEnabledThenWriteHeaders() { this.writer.setHeaderValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.ENABLED); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers.headerNames()).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)).containsOnly("1"); } @Test void writeHeadersWhenEnabledModeBlockThenWriteHeaders() { this.writer.setHeaderValue(XXssProtectionServerHttpHeadersWriter.HeaderValue.ENABLED_MODE_BLOCK); this.writer.writeHttpHeaders(this.exchange); assertThat(this.headers.headerNames()).hasSize(1); assertThat(this.headers.get(XXssProtectionServerHttpHeadersWriter.X_XSS_PROTECTION)) .containsOnly("1; mode=block"); } }
XXssProtectionServerHttpHeadersWriterTests
java
elastic__elasticsearch
x-pack/plugin/src/test/java/org/elasticsearch/xpack/test/rest/AbstractXPackRestTest.java
{ "start": 2135, "end": 8344 }
class ____ extends ESClientYamlSuiteTestCase { private static final String BASIC_AUTH_VALUE = basicAuthHeaderValue( "x_pack_rest_user", SecuritySettingsSourceField.TEST_PASSWORD_SECURE_STRING ); @ClassRule public static MlModelServer mlModelServer = new MlModelServer(); @Before public void setMlModelRepository() throws IOException { assertOK(mlModelServer.setMlModelRepository(adminClient())); } public AbstractXPackRestTest(ClientYamlTestCandidate testCandidate) { super(testCandidate); } @ParametersFactory public static Iterable<Object[]> parameters() throws Exception { return createParameters(); } @Override protected Settings restClientSettings() { return Settings.builder().put(ThreadContext.PREFIX + ".Authorization", BASIC_AUTH_VALUE).build(); } @Before public void setupForTests() throws Exception { waitForTemplates(); } /** * Waits for Machine Learning templates to be created by the {@link MetadataUpgrader} */ private void waitForTemplates() { if (installTemplates()) { List<String> templates = Arrays.asList( NotificationsIndex.NOTIFICATIONS_INDEX, AnomalyDetectorsIndexFields.STATE_INDEX_PREFIX, AnomalyDetectorsIndex.jobResultsIndexPrefix() ); for (String template : templates) { awaitCallApi( "indices.exists_index_template", singletonMap("name", template), emptyList(), response -> true, () -> "Exception when waiting for [" + template + "] template to be created" ); } } } /** * Waits for the cluster's self-generated license to be created and installed */ protected void waitForLicense() { // GET _licence returns a 404 status up until the license exists awaitCallApi( "license.get", Map.of(), List.of(), response -> true, () -> "Exception when waiting for initial license to be generated", 30 // longer wait time to accommodate slow-running CI release builds ); } /** * Cleanup after tests. * * Feature-specific cleanup methods should be called from here rather than using * separate @After annotated methods to ensure there is a well-defined cleanup order. */ @After public void cleanup() throws Exception { clearMlState(); if (isWaitForPendingTasks()) { // This waits for pending tasks to complete, so must go last (otherwise // it could be waiting for pending tasks while monitoring is still running). waitForPendingTasks(adminClient(), waitForPendingTasksFilter()); } } protected Predicate<String> waitForPendingTasksFilter() { return task -> { // Don't check rollup jobs or data stream reindex tasks because we clear them in the superclass. return task.contains(RollupJob.NAME) || task.contains("reindex-data-stream"); }; } /** * Delete any left over machine learning datafeeds and jobs. */ private void clearMlState() throws Exception { if (isMachineLearningTest()) { new MlRestTestStateCleaner(logger, adminClient()).resetFeatures(); } } /** * Executes an API call using the admin context, waiting for it to succeed. */ private void awaitCallApi( String apiName, Map<String, String> params, List<Map<String, Object>> bodies, CheckedFunction<ClientYamlTestResponse, Boolean, IOException> success, Supplier<String> error ) { awaitCallApi(apiName, params, bodies, success, error, 10); } private void awaitCallApi( String apiName, Map<String, String> params, List<Map<String, Object>> bodies, CheckedFunction<ClientYamlTestResponse, Boolean, IOException> success, Supplier<String> error, long maxWaitTimeInSeconds ) { try { final AtomicReference<ClientYamlTestResponse> response = new AtomicReference<>(); assertBusy(() -> { try { // The actual method call that sends the API requests returns a Future, but we immediately // call .get() on it so there's no need for this method to do any other awaiting. response.set(callApi(apiName, params, bodies, getApiCallHeaders())); assertEquals(HttpStatus.SC_OK, response.get().getStatusCode()); } catch (ClientYamlTestResponseException e) { // Convert to an AssertionError so that "assertBusy" treats it as a failed assertion (and tries again) // rather than a runtime failure (which terminates the loop) throw new AssertionError("Failed to call API " + apiName, e); } }, maxWaitTimeInSeconds, TimeUnit.SECONDS); success.apply(response.get()); } catch (Exception e) { throw new IllegalStateException(error.get(), e); } } private ClientYamlTestResponse callApi( String apiName, Map<String, String> params, List<Map<String, Object>> bodies, Map<String, String> headers ) throws IOException { return getAdminExecutionContext().callApi(apiName, params, bodies, headers); } protected Map<String, String> getApiCallHeaders() { return Collections.emptyMap(); } protected boolean installTemplates() { return true; } protected boolean isMachineLearningTest() { String testName = getTestName(); return testName != null && (testName.contains("=ml/") || testName.contains("=ml\\")); } /** * Should each test wait for pending tasks to finish after execution? * @return Wait for pending tasks */ protected boolean isWaitForPendingTasks() { return true; } }
AbstractXPackRestTest
java
spring-projects__spring-security
web/src/test/java/org/springframework/security/web/authentication/HttpMessageConverterAuthenticationSuccessHandlerTests.java
{ "start": 1700, "end": 4301 }
class ____ { @Mock private HttpMessageConverter converter; @Mock private RequestCache requestCache; private HttpMessageConverterAuthenticationSuccessHandler handler = new HttpMessageConverterAuthenticationSuccessHandler(); private MockHttpServletRequest request = new MockHttpServletRequest(); private MockHttpServletResponse response = new MockHttpServletResponse(); private Authentication authentication = new TestingAuthenticationToken("user", "password", "ROLE_USER"); @Test void setConverterWhenNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setConverter(null)); } @Test void setRequestCacheWhenNullThenThrowIllegalArgumentException() { assertThatIllegalArgumentException().isThrownBy(() -> this.handler.setRequestCache(null)); } @Test void onAuthenticationSuccessWhenDefaultsThenContextRoot() throws Exception { this.handler.onAuthenticationSuccess(this.request, this.response, this.authentication); String body = this.response.getContentAsString(); JSONAssert.assertEquals(""" { "redirectUrl" : "/", "authenticated": true }""", body, false); } @Test void onAuthenticationSuccessWhenSavedRequestThenInResponse() throws Exception { SimpleSavedRequest savedRequest = new SimpleSavedRequest("/redirect"); given(this.requestCache.getRequest(this.request, this.response)).willReturn(savedRequest); this.handler.setRequestCache(this.requestCache); this.handler.onAuthenticationSuccess(this.request, this.response, this.authentication); verify(this.requestCache).removeRequest(this.request, this.response); String body = this.response.getContentAsString(); JSONAssert.assertEquals(""" { "redirectUrl" : "/redirect", "authenticated": true }""", body, false); } @Test void onAuthenticationSuccessWhenCustomConverterThenInResponse() throws Exception { SimpleSavedRequest savedRequest = new SimpleSavedRequest("/redirect"); given(this.requestCache.getRequest(this.request, this.response)).willReturn(savedRequest); String expectedBody = "Custom!"; BDDMockito.doAnswer((invocation) -> { this.response.getWriter().write(expectedBody); return null; }).when(this.converter).write(any(), any(), any()); this.handler.setRequestCache(this.requestCache); this.handler.setConverter(this.converter); this.handler.onAuthenticationSuccess(this.request, this.response, this.authentication); String body = this.response.getContentAsString(); assertThat(body).isEqualTo(expectedBody); } }
HttpMessageConverterAuthenticationSuccessHandlerTests
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/ingest/IngestDocument.java
{ "start": 65267, "end": 74568 }
class ____ { /** * A compound cache key for tracking previously parsed field paths * @param path The field path as given by the caller * @param accessPattern The access pattern used to parse the field path */ private record CacheKey(String path, IngestPipelineFieldAccessPattern accessPattern) {} private static final int MAX_SIZE = 512; private static final Map<CacheKey, FieldPath> CACHE = ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency(); // constructing a new FieldPath requires that we parse a String (e.g. "foo.bar.baz") into an array // of path elements (e.g. ["foo", "bar", "baz"]). Calling String#split results in the allocation // of an ArrayList to hold the results, then a new String is created for each path element, and // then finally a String[] is allocated to hold the actual result -- in addition to all that, we // do some processing ourselves on the path and path elements to validate and prepare them. // the above CACHE and the below 'FieldPath.of' method allow us to almost always avoid this work. static FieldPath of(String path, IngestPipelineFieldAccessPattern accessPattern) { if (Strings.isEmpty(path)) { throw new IllegalArgumentException("path cannot be null nor empty"); } CacheKey cacheKey = new CacheKey(path, accessPattern); FieldPath res = CACHE.get(cacheKey); if (res != null) { return res; } res = new FieldPath(path, accessPattern); if (CACHE.size() > MAX_SIZE) { CACHE.clear(); } CACHE.put(cacheKey, res); return res; } private final String[] pathElements; private final boolean useIngestContext; // you shouldn't call this directly, use the FieldPath.of method above instead! private FieldPath(String path, IngestPipelineFieldAccessPattern accessPattern) { String newPath; if (path.startsWith(INGEST_KEY_PREFIX)) { useIngestContext = true; newPath = path.substring(INGEST_KEY_PREFIX.length()); } else { useIngestContext = false; if (path.startsWith(SOURCE_PREFIX)) { newPath = path.substring(SOURCE_PREFIX.length()); } else { newPath = path; } } String[] pathParts = newPath.split("\\."); this.pathElements = processPathParts(path, pathParts, accessPattern); } private static String[] processPathParts(String fullPath, String[] pathParts, IngestPipelineFieldAccessPattern accessPattern) { return switch (accessPattern) { case CLASSIC -> validateClassicFields(fullPath, pathParts); case FLEXIBLE -> parseFlexibleFields(fullPath, pathParts); }; } /** * Parses path syntax that is specific to the {@link IngestPipelineFieldAccessPattern#CLASSIC} ingest doc access pattern. Supports * syntax like context aware array access. * @param fullPath The un-split path to use for error messages * @param pathParts The tokenized field path to parse * @return An array of Strings */ private static String[] validateClassicFields(String fullPath, String[] pathParts) { for (String pathPart : pathParts) { if (pathPart.isEmpty()) { throw new IllegalArgumentException("path [" + fullPath + "] is not valid"); } } return pathParts; } /** * Parses path syntax that is specific to the {@link IngestPipelineFieldAccessPattern#FLEXIBLE} ingest doc access pattern. Supports * syntax like square bracket array access, which is the only way to index arrays in flexible mode. * @param fullPath The un-split path to use for error messages * @param pathParts The tokenized field path to parse * @return An array of Strings */ private static String[] parseFlexibleFields(String fullPath, String[] pathParts) { for (String pathPart : pathParts) { if (pathPart.isEmpty() || pathPart.contains("[") || pathPart.contains("]")) { throw new IllegalArgumentException("path [" + fullPath + "] is not valid"); } } return pathParts; } public Object initialContext(IngestDocument document) { return useIngestContext ? document.getIngestMetadata() : document.getCtxMap(); } } private record ResolveResult(boolean wasSuccessful, Object resolvedObject, String errorMessage, String missingFields) { /** * The resolve operation ended with a successful result, locating the resolved object at the given path location * @param resolvedObject The resolved object * @return Successful result */ static ResolveResult success(Object resolvedObject) { return new ResolveResult(true, resolvedObject, null, null); } /** * Due to the access pattern, the resolve operation was only partially completed. The last resolved context object is returned, * along with the fields that have been tried up until running into the field limit. The result's success flag is set to false, * but it contains additional information about further resolving the operation. * @param lastResolvedObject The last successfully resolved context object from the document * @param missingFields The fields from the given path that have not been located yet * @return Incomplete result */ static ResolveResult incomplete(Object lastResolvedObject, String missingFields) { return new ResolveResult(false, lastResolvedObject, null, missingFields); } /** * The resolve operation ended with an error. The object at the given path location could not be resolved, either due to it * being missing, or the path being invalid. * @param errorMessage The error message to be returned. * @return Error result */ static ResolveResult error(String errorMessage) { return new ResolveResult(false, null, errorMessage, null); } } /** * Provides a shallowly read-only, very limited, map-like view of two maps. The only methods that are implemented are * {@link Map#get(Object)} and {@link Map#containsKey(Object)}, everything else throws UnsupportedOperationException. * <p> * The overrides map has higher priority than the primary map -- values in that map under some key will take priority over values * in the primary map under the same key. * * @param primary the primary map * @param overrides the overrides map */ private record DelegatingMapView(Map<String, Object> primary, Map<String, Object> overrides) implements Map<String, Object> { @Override public boolean containsKey(Object key) { // most normal uses of this in practice will end up passing in keys that match the primary, rather than the overrides, // in which case we can shortcut by checking the primary first return primary.containsKey(key) || overrides.containsKey(key); } @Override public Object get(Object key) { // null values in the overrides map are treated as *key not present*, so we don't have to do a containsKey check here -- // if the overrides map returns null we can simply delegate to the primary Object result = overrides.get(key); return result != null ? result : primary.get(key); } @Override public int size() { throw new UnsupportedOperationException(); } @Override public boolean isEmpty() { throw new UnsupportedOperationException(); } @Override public boolean containsValue(Object value) { throw new UnsupportedOperationException(); } @Override public Object put(String key, Object value) { throw new UnsupportedOperationException(); } @Override public Object remove(Object key) { throw new UnsupportedOperationException(); } @Override public void putAll(Map<? extends String, ?> m) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Set<String> keySet() { throw new UnsupportedOperationException(); } @Override public Collection<Object> values() { throw new UnsupportedOperationException(); } @Override public Set<Entry<String, Object>> entrySet() { throw new UnsupportedOperationException(); } } private static final
FieldPath
java
spring-projects__spring-framework
framework-docs/src/main/java/org/springframework/docs/web/websocket/stomp/websocketstompauthenticationtokenbased/WebSocketConfiguration.java
{ "start": 1461, "end": 2072 }
class ____ implements WebSocketMessageBrokerConfigurer { @Override public void configureClientInboundChannel(ChannelRegistration registration) { registration.interceptors(new ChannelInterceptor() { @Override public Message<?> preSend(Message<?> message, MessageChannel channel) { StompHeaderAccessor accessor = MessageHeaderAccessor.getAccessor(message, StompHeaderAccessor.class); if (StompCommand.CONNECT.equals(accessor.getCommand())) { // Access authentication header(s) and invoke accessor.setUser(user) } return message; } }); } } // end::snippet[]
WebSocketConfiguration
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/test/java/io/quarkus/vertx/http/runtime/PathMatcherTest.java
{ "start": 571, "end": 28226 }
class ____ { private static final Object HANDLER = new Object(); @Test public void testPrefixPathWithEndingWildcard() { ImmutablePathMatcher<Object> matcher = ImmutablePathMatcher.builder().addPath("/one/two/*", HANDLER).build(); assertMatched(matcher, "/one/two"); assertMatched(matcher, "/one/two/"); assertMatched(matcher, "/one/two/three"); assertNotMatched(matcher, "/one/twothree"); assertNotMatched(matcher, "/one/tw"); assertNotMatched(matcher, "/one"); assertNotMatched(matcher, "/"); assertNotMatched(matcher, ""); final Object exactPathMatcher1 = new Object(); final Object exactPathMatcher2 = new Object(); final Object exactPathMatcher3 = new Object(); final Object prefixPathMatcher1 = new Object(); final Object prefixPathMatcher2 = new Object(); matcher = ImmutablePathMatcher.builder().addPath("/one/two/*", prefixPathMatcher1) .addPath("/one/two/three", exactPathMatcher1).addPath("/one/two", exactPathMatcher2) .addPath("/one/two/", prefixPathMatcher1).addPath("/one/two/three/", prefixPathMatcher2) .addPath("/one/two/three*", prefixPathMatcher2).addPath("/one/two/three/four/", prefixPathMatcher2) .addPath("/one/two/three/four", exactPathMatcher3).build(); assertMatched(matcher, "/one/two/three", exactPathMatcher1); assertMatched(matcher, "/one/two", exactPathMatcher2); assertMatched(matcher, "/one/two/three/four", exactPathMatcher3); assertMatched(matcher, "/one/two/three/fou", prefixPathMatcher2); assertMatched(matcher, "/one/two/three/four/", prefixPathMatcher2); assertMatched(matcher, "/one/two/three/five", prefixPathMatcher2); assertMatched(matcher, "/one/two/three/", prefixPathMatcher2); assertMatched(matcher, "/one/two/thre", prefixPathMatcher1); assertMatched(matcher, "/one/two/", prefixPathMatcher1); assertNotMatched(matcher, "/one/tw"); assertNotMatched(matcher, "/one/"); assertNotMatched(matcher, "/"); assertNotMatched(matcher, ""); } @Test public void testPrefixPathDefaultHandler() { final Object defaultHandler = new Object(); ImmutablePathMatcher<Object> matcher = ImmutablePathMatcher.builder().addPath("/one/two*", HANDLER) .addPath("/*", defaultHandler).addPath("/q*", HANDLER).build(); assertMatched(matcher, "/", defaultHandler); assertMatched(matcher, "", defaultHandler); assertMatched(matcher, "0", defaultHandler); assertMatched(matcher, "/q"); assertMatched(matcher, "/q/dev-ui"); assertMatched(matcher, "/qE", defaultHandler); assertMatched(matcher, "/one/two"); assertMatched(matcher, "/one/two/three"); assertMatched(matcher, "/one/twothree", defaultHandler); final Object exactPathMatcher1 = new Object(); final Object exactPathMatcher2 = new Object(); final Object exactPathMatcher3 = new Object(); final Object prefixPathMatcher1 = new Object(); final Object prefixPathMatcher2 = new Object(); matcher = ImmutablePathMatcher.builder().addPath("/one/two/*", prefixPathMatcher1).addPath("/*", defaultHandler) .addPath("/one/two/three", exactPathMatcher1).addPath("/one/two/three/", prefixPathMatcher2) .addPath("/one/two", exactPathMatcher2).addPath("/one/two/", prefixPathMatcher1) .addPath("/one/two/three*", prefixPathMatcher2).addPath("/one/two/three/four", exactPathMatcher3) .addPath("/one/two/three/four/", prefixPathMatcher2).build(); assertMatched(matcher, "/one/two/three", exactPathMatcher1); assertMatched(matcher, "/one/two", exactPathMatcher2); assertMatched(matcher, "/one/two/three/four", exactPathMatcher3); assertMatched(matcher, "/one/two/three/fou", prefixPathMatcher2); assertMatched(matcher, "/one/two/three/four/", prefixPathMatcher2); assertMatched(matcher, "/one/two/three/five", prefixPathMatcher2); assertMatched(matcher, "/one/two/three/", prefixPathMatcher2); assertMatched(matcher, "/one/two/thre", prefixPathMatcher1); assertMatched(matcher, "/one/two/", prefixPathMatcher1); assertMatched(matcher, "/one/tw", defaultHandler); assertMatched(matcher, "/one/", defaultHandler); assertMatched(matcher, "/", defaultHandler); assertMatched(matcher, "", defaultHandler); } @Test public void testPrefixPathsNoDefaultHandlerNoExactPath() { final Object handler1 = new Object(); final Object handler2 = new Object(); final ImmutablePathMatcher<Object> matcher = ImmutablePathMatcher.builder().addPath("/one/two*", handler1) .addPath("/q*", handler2).build(); assertNotMatched(matcher, "/"); assertNotMatched(matcher, ""); assertNotMatched(matcher, "0"); assertMatched(matcher, "/q", handler2); assertMatched(matcher, "/q/dev-ui", handler2); assertNotMatched(matcher, "/qE"); assertMatched(matcher, "/one/two", handler1); assertMatched(matcher, "/one/two/three", handler1); assertMatched(matcher, "/one/two/", handler1); assertNotMatched(matcher, "/one/twothree"); } @Test public void testSpecialChars() { // strictly speaking query params are not part of request path passed to the matcher // but here they are treated like any other character different from path separator final Object handler1 = new Object(); final Object handler2 = new Object(); final Object handler3 = new Object(); final Object handler4 = new Object(); final Object handler5 = new Object(); // with default handler ImmutablePathMatcher<Object> matcher = ImmutablePathMatcher.builder().addPath("/one/two#three", handler2) .addPath("/one/two?three=four", handler1).addPath("/one/*/three?one\\\\\\=two", handler3) .addPath("/one/two#three*", handler4).addPath("/*/two#three*", handler5).addPath("/*", HANDLER) .addPath("/one/two#three/", handler4).build(); assertMatched(matcher, "/one/two#three", handler2); assertMatched(matcher, "/one/two?three=four", handler1); assertMatched(matcher, "/one/any-value/three?one\\\\\\=two", handler3); assertMatched(matcher, "/one/two/three?one\\\\\\=two", handler3); assertMatched(matcher, "/one/two/three?one\\=two"); assertMatched(matcher, "/one/two/three?one\\\\\\=two-three"); assertMatched(matcher, "/one/two/three?one"); assertMatched(matcher, "/one/two/three?"); assertMatched(matcher, "/one/two#three?"); assertMatched(matcher, "/one/two#thre"); assertMatched(matcher, "/one/two"); assertMatched(matcher, "/one/two?three=four#"); assertMatched(matcher, "/one/two?three=fou"); assertMatched(matcher, "/one/two#three/", handler4); assertMatched(matcher, "/one/two#three/christmas!", handler4); assertMatched(matcher, "/one/two#thre"); assertMatched(matcher, "/one1/two#three", handler5); assertMatched(matcher, "/one1/two#three/", handler5); assertMatched(matcher, "/one1/two#three/christmas!", handler5); assertMatched(matcher, "/one1/two#thre"); // no default handler matcher = ImmutablePathMatcher.builder().addPath("/one/two#three", handler2).addPath("/one/two#three/", handler4) .addPath("/one/two?three=four", handler1).addPath("/one/*/three?one\\\\\\=two", handler3) .addPath("/one/two#three*", handler4).addPath("/*/two#three*", handler5).build(); assertMatched(matcher, "/one/two#three", handler2); assertMatched(matcher, "/one/two?three=four", handler1); assertMatched(matcher, "/one/any-value/three?one\\\\\\=two", handler3); assertMatched(matcher, "/one/two/three?one\\\\\\=two", handler3); assertNotMatched(matcher, "/one/two/three?one\\=two"); assertNotMatched(matcher, "/one/two/three?one\\\\\\=two-three"); assertNotMatched(matcher, "/one/two/three?one"); assertNotMatched(matcher, "/one/two/three?"); assertNotMatched(matcher, "/one/two#three?"); assertNotMatched(matcher, "/one/two#thre"); assertNotMatched(matcher, "/one/two"); assertNotMatched(matcher, "/one/two?three=four#"); assertNotMatched(matcher, "/one/two?three=fou"); assertMatched(matcher, "/one/two#three/", handler4); assertMatched(matcher, "/one/two#three/christmas!", handler4); assertNotMatched(matcher, "/one/two#thre"); assertMatched(matcher, "/one1/two#three", handler5); assertMatched(matcher, "/one1/two#three/", handler5); assertMatched(matcher, "/one1/two#three/christmas!", handler5); assertNotMatched(matcher, "/one1/two#thre"); } @Test public void testInnerWildcardsWithExactMatches() { final Object handler1 = new Object(); final Object handler2 = new Object(); final Object handler3 = new Object(); final Object handler4 = new Object(); final Object handler5 = new Object(); final Object handler6 = new Object(); final Object handler7 = new Object(); final Object handler8 = new Object(); final ImmutablePathMatcher<Object> matcher = ImmutablePathMatcher.builder().addPath("/one/two", handler1) .addPath("/one/two/three", handler2).addPath("/one/two/three/four", handler3) .addPath("/", handler4).addPath("/*", HANDLER).addPath("/one/two/*/four", handler5) .addPath("/one/*/three/four", handler6).addPath("/*/two/three/four", handler7) .addPath("/*/two", handler8).addPath("/*/two/three/four/", HANDLER).build(); assertMatched(matcher, "/one/two", handler1); assertMatched(matcher, "/one/two/three", handler2); assertMatched(matcher, "/one/two/three/four", handler3); assertMatched(matcher, "/", handler4); assertMatched(matcher, ""); assertMatched(matcher, "no-one-likes-us"); assertMatched(matcher, "/one/two/we-do-not-care/four", handler5); assertMatched(matcher, "/one/two/we-do-not-care/four/4"); assertMatched(matcher, "/one/we-are-millwall/three/four", handler6); assertMatched(matcher, "/1-one/we-are-millwall/three/four"); assertMatched(matcher, "/super-millwall/two/three/four", handler7); assertMatched(matcher, "/super-millwall/two/three/four/"); assertMatched(matcher, "/super-millwall/two/three/four/1"); assertMatched(matcher, "/from-the-den/two", handler8); assertMatched(matcher, "/from-the-den/two2"); } @Test public void testInnerWildcardsOnly() { final Object handler1 = new Object(); final Object handler2 = new Object(); final Object handler3 = new Object(); final Object handler4 = new Object(); final Object handler5 = new Object(); // with default path handler ImmutablePathMatcher<Object> matcher = ImmutablePathMatcher.builder().addPath("/*/two", handler2) .addPath("/*/*/three", handler1).addPath("/one/*/three", handler3) .addPath("/one/two/*/four", handler4).addPath("/one/two/three/*/five", handler5) .addPath("/*", HANDLER).build(); assertMatched(matcher, "/any-value"); assertMatched(matcher, "/one/two/three/four/five", handler5); assertMatched(matcher, "/one/two/three/4/five", handler5); assertMatched(matcher, "/one/two/three/sergey/five", handler5); assertMatched(matcher, "/one/two/three/sergey/five-ish"); assertMatched(matcher, "/one/two/three/sergey/five/", handler5); assertMatched(matcher, "/one/two/three/four", handler4); assertMatched(matcher, "/one/two/3/four", handler4); assertMatched(matcher, "/one/two/three", handler3); assertMatched(matcher, "/one/2/three", handler3); assertMatched(matcher, "/one/some-very-long-text/three", handler3); assertMatched(matcher, "/two"); assertMatched(matcher, "/two/two", handler2); assertMatched(matcher, "/2/two", handler2); assertMatched(matcher, "/ho-hey/two", handler2); assertMatched(matcher, "/ho-hey/two2"); assertMatched(matcher, "/ho-hey/two2/"); assertMatched(matcher, "/ho-hey/two/", handler2); assertMatched(matcher, "/ho-hey/hey-ho/three", handler1); assertMatched(matcher, "/1/2/three", handler1); assertMatched(matcher, "/1/two/three", handler1); assertMatched(matcher, "/1/two/three/", handler1); assertMatched(matcher, "/1/two/three/f"); // no default path handler matcher = ImmutablePathMatcher.builder().addPath("/*/two", handler2) .addPath("/*/*/three", handler1).addPath("/one/*/three", handler3) .addPath("/one/two/*/four", handler4).addPath("/one/two/three/*/five", handler5).build(); assertNotMatched(matcher, "/any-value"); assertMatched(matcher, "/one/two/three/four/five", handler5); assertMatched(matcher, "/one/two/three/4/five", handler5); assertMatched(matcher, "/one/two/three/sergey/five", handler5); assertMatched(matcher, "/one/two/three/sergey/five/", handler5); assertNotMatched(matcher, "/one/two/three/sergey/five-ish"); assertMatched(matcher, "/one/two/three/four", handler4); assertMatched(matcher, "/one/two/3/four", handler4); assertMatched(matcher, "/one/two/three", handler3); assertMatched(matcher, "/one/2/three", handler3); assertMatched(matcher, "/one/some-very-long-text/three", handler3); assertNotMatched(matcher, "/two"); assertMatched(matcher, "/two/two", handler2); assertMatched(matcher, "/2/two", handler2); assertMatched(matcher, "/ho-hey/two", handler2); assertMatched(matcher, "/ho-hey/two/", handler2); assertNotMatched(matcher, "/ho-hey/two2"); assertNotMatched(matcher, "/ho-hey/two2/"); assertMatched(matcher, "/ho-hey/hey-ho/three", handler1); assertMatched(matcher, "/1/2/three", handler1); assertMatched(matcher, "/1/two/three", handler1); assertMatched(matcher, "/1/two/three/", handler1); assertNotMatched(matcher, "/1/two/three/f"); } @Test public void testInnerWildcardWithEndingWildcard() { final Object handler1 = new Object(); final Object handler2 = new Object(); final Object handler3 = new Object(); final Object handler4 = new Object(); final Object handler5 = new Object(); // with default handler ImmutablePathMatcher<Object> matcher = ImmutablePathMatcher.builder().addPath("/*/two/*", handler1) .addPath("/one/*/*", handler2).addPath("/one/two/*/four*", handler3) .addPath("/one/*/three/*", handler4).addPath("/one/two/*/*", handler5) .addPath("/*", HANDLER).build(); assertMatched(matcher, "/one/two/three/four/five/six", handler3); assertMatched(matcher, "/one/two/three/four/five", handler3); assertMatched(matcher, "/one/two/three/four/", handler3); assertMatched(matcher, "/one/two/three/four", handler3); assertMatched(matcher, "/one/two/3/four", handler3); assertMatched(matcher, "/one/two/three/4", handler5); assertMatched(matcher, "/one/two/three/4/", handler5); assertMatched(matcher, "/one/two/three/4/five", handler5); assertMatched(matcher, "/one/2/three/four/five", handler4); assertMatched(matcher, "/one/2/3/four/five", handler2); assertMatched(matcher, "/1/two/three/four/five", handler1); assertMatched(matcher, "/1/2/three/four/five"); } @Test public void testInnerWildcardsDefaultHandler() { final Object handler1 = new Object(); final Object handler2 = new Object(); final Object handler3 = new Object(); // both default root path handler and sub-path handler ImmutablePathMatcher<Object> matcher = ImmutablePathMatcher.builder().addPath("/*/*", handler1) .addPath("/*/*/three", handler3).addPath("/*", handler2).build(); assertMatched(matcher, "/one/two/three", handler3); assertMatched(matcher, "/one/two/four", handler1); assertMatched(matcher, "/one/two", handler1); assertMatched(matcher, "/one", handler2); assertMatched(matcher, "/", handler2); } @Test public void testInvalidPathPattern() { // path must start with a path separator assertThrows(IllegalArgumentException.class, () -> ImmutablePathMatcher.builder().addPath("one", HANDLER).build()); // inner wildcard must always be only path segment character assertThrows(ConfigurationException.class, () -> ImmutablePathMatcher.builder().addPath("/one*/", HANDLER).build()); assertThrows(ConfigurationException.class, () -> ImmutablePathMatcher.builder().addPath("/*one/", HANDLER).build()); assertThrows(ConfigurationException.class, () -> ImmutablePathMatcher.builder().addPath("/o*ne/", HANDLER).build()); assertThrows(ConfigurationException.class, () -> ImmutablePathMatcher.builder().addPath("/one/*two/", HANDLER).build()); assertThrows(ConfigurationException.class, () -> ImmutablePathMatcher.builder().addPath("/one/*two/", HANDLER).build()); assertThrows(ConfigurationException.class, () -> ImmutablePathMatcher.builder().addPath("/one/two*/", HANDLER).build()); assertThrows(ConfigurationException.class, () -> ImmutablePathMatcher.builder().addPath("/one/*two*/", HANDLER).build()); } @Test public void testExactPathHandlerMerging() { List<String> handler1 = new ArrayList<>(); handler1.add("Neo"); List<String> handler2 = new ArrayList<>(); handler2.add("Trinity"); List<String> handler3 = new ArrayList<>(); handler3.add("Morpheus"); var matcher = ImmutablePathMatcher.<List<String>> builder().handlerAccumulator(List::addAll) .addPath("/exact-path", handler1).addPath("/exact-path", handler2) .addPath("/exact-not-matched", handler3).build(); var handler = matcher.match("/exact-path").getValue(); assertNotNull(handler); assertTrue(handler.contains("Neo")); assertTrue(handler.contains("Trinity")); assertEquals(2, handler.size()); handler = matcher.match("/exact-not-matched").getValue(); assertNotNull(handler); assertEquals(1, handler.size()); } @Test public void testDefaultHandlerMerging() { List<String> handler1 = new ArrayList<>(); handler1.add("Neo"); List<String> handler2 = new ArrayList<>(); handler2.add("Trinity"); List<String> handler3 = new ArrayList<>(); handler3.add("Morpheus"); var matcher = ImmutablePathMatcher.<List<String>> builder().handlerAccumulator(List::addAll) .addPath("/*", handler1).addPath("/*", handler2) .addPath("/", handler3).build(); var handler = matcher.match("/default-path-handler").getValue(); assertNotNull(handler); assertTrue(handler.contains("Neo")); assertTrue(handler.contains("Trinity")); assertEquals(2, handler.size()); handler = matcher.match("/").getValue(); assertNotNull(handler); assertEquals(1, handler.size()); } @Test public void testPrefixPathHandlerMerging() { List<String> handler1 = new ArrayList<>(); handler1.add("Neo"); List<String> handler2 = new ArrayList<>(); handler2.add("Trinity"); List<String> handler3 = new ArrayList<>(); handler3.add("Morpheus"); List<String> handler4 = new ArrayList<>(); handler4.add("AgentSmith"); List<String> handler5 = new ArrayList<>(); handler5.add("TheOracle"); List<String> handler6 = new ArrayList<>(); handler6.add("AgentBrown"); var matcher = ImmutablePathMatcher.<List<String>> builder().handlerAccumulator(List::addAll).addPath("/path*", handler1) .addPath("/path*", handler2).addPath("/path/*", handler3).addPath("/path/", handler4) .addPath("/path/*/", handler5).addPath("/*", handler6).addPath("/path", handler1).build(); var handler = matcher.match("/path").getValue(); assertNotNull(handler); assertTrue(handler.contains("Neo")); assertTrue(handler.contains("Trinity")); assertTrue(handler.contains("Morpheus")); assertEquals(3, handler.size()); handler = matcher.match("/path/").getValue(); assertNotNull(handler); assertEquals(1, handler.size()); assertTrue(handler.contains("AgentSmith")); handler = matcher.match("/stuart").getValue(); assertNotNull(handler); assertEquals(1, handler.size()); assertTrue(handler.contains("AgentBrown")); handler = matcher.match("/path/ozzy/").getValue(); assertNotNull(handler); assertEquals(1, handler.size()); assertTrue(handler.contains("TheOracle")); } @Test public void testInnerWildcardPathHandlerMerging() { List<String> handler1 = new ArrayList<>(); handler1.add("Neo"); List<String> handler2 = new ArrayList<>(); handler2.add("Trinity"); List<String> handler3 = new ArrayList<>(); handler3.add("Morpheus"); List<String> handler4 = new ArrayList<>(); handler4.add("AgentSmith"); List<String> handler5 = new ArrayList<>(); handler5.add("TheOracle"); List<String> handler6 = new ArrayList<>(); handler6.add("AgentBrown"); List<String> handler7 = new ArrayList<>(); handler7.add("TheOperator"); List<String> handler8 = new ArrayList<>(); handler8.add("TheSpoonBoy"); List<String> handler9 = new ArrayList<>(); handler9.add("TheArchitect"); List<String> handler10 = new ArrayList<>(); handler10.add("KeyMan"); List<String> handler11 = new ArrayList<>(); handler11.add("Revolutions"); List<String> handler12 = new ArrayList<>(); handler12.add("Reloaded-1"); List<String> handler13 = new ArrayList<>(); handler13.add("Reloaded-2"); List<String> handler14 = new ArrayList<>(); handler14.add("Reloaded-3"); var matcher = ImmutablePathMatcher.<List<String>> builder().handlerAccumulator(List::addAll) .addPath("/*/one", handler1).addPath("/*/*", handler2).addPath("/*/*", handler3) .addPath("/*/one", handler4).addPath("/*/two", handler5).addPath("/*", handler6) .addPath("/one/*/three", handler7).addPath("/one/*", handler8).addPath("/one/*/*", handler9) .addPath("/one/*/three", handler10).addPath("/one/*/*", handler11) .addPath("/one/*/*/*", handler12).addPath("/one/*/*/*", handler13) .addPath("/one/*/*/*", handler14).build(); var handler = matcher.match("/one/two/three").getValue(); assertNotNull(handler); assertEquals(2, handler.size()); assertTrue(handler.contains("TheOperator")); assertTrue(handler.contains("KeyMan")); handler = matcher.match("/one/two/three/four").getValue(); assertNotNull(handler); assertEquals(3, handler.size()); assertTrue(handler.contains("Reloaded-1")); assertTrue(handler.contains("Reloaded-2")); assertTrue(handler.contains("Reloaded-3")); handler = matcher.match("/one/2/3").getValue(); assertNotNull(handler); assertEquals(2, handler.size()); assertTrue(handler.contains("TheArchitect")); assertTrue(handler.contains("Revolutions")); handler = matcher.match("/one/two").getValue(); assertNotNull(handler); assertEquals(1, handler.size()); assertTrue(handler.contains("TheSpoonBoy")); handler = matcher.match("/1/one").getValue(); assertNotNull(handler); assertEquals(2, handler.size()); assertTrue(handler.contains("Neo")); assertTrue(handler.contains("AgentSmith")); handler = matcher.match("/1/two").getValue(); assertNotNull(handler); assertEquals(1, handler.size()); assertTrue(handler.contains("TheOracle")); handler = matcher.match("/father-brown").getValue(); assertNotNull(handler); assertEquals(1, handler.size()); assertTrue(handler.contains("AgentBrown")); handler = matcher.match("/welcome/to/the/jungle").getValue(); assertNotNull(handler); assertEquals(2, handler.size()); assertTrue(handler.contains("Trinity")); assertTrue(handler.contains("Morpheus")); } @Test public void testDefaultHandlerInnerWildcardAndEndingWildcard() { // calling it default handler inner wildcard because first '/' path is matched and then '/one*' // '/one*' is matched as prefix path final ImmutablePathMatcher<Object> matcher = ImmutablePathMatcher.builder().addPath("/*/one*", HANDLER).build(); assertMatched(matcher, "/1/one"); assertMatched(matcher, "/2/one"); assertMatched(matcher, "/3/one"); assertMatched(matcher, "/4/one"); assertMatched(matcher, "/4/one"); assertMatched(matcher, "/1/one/"); assertMatched(matcher, "/1/one/two"); assertNotMatched(matcher, "/"); assertNotMatched(matcher, "/1"); assertNotMatched(matcher, "/1/"); assertNotMatched(matcher, "/1/one1"); assertNotMatched(matcher, "/1/two"); assertNotMatched(matcher, "/1/on"); } @Test public void testDefaultHandlerOneInnerWildcard() { // calling it default handler inner wildcard because first '/' path is matched and then '/one' // '/one' is matched as exact path final ImmutablePathMatcher<Object> matcher = ImmutablePathMatcher.builder().addPath("/*/one", HANDLER).build(); assertMatched(matcher, "/1/one"); assertMatched(matcher, "/2/one"); assertMatched(matcher, "/3/one"); assertMatched(matcher, "/4/one"); assertMatched(matcher, "/4/one"); assertMatched(matcher, "/1/one/"); assertNotMatched(matcher, "/"); assertNotMatched(matcher, "/1"); assertNotMatched(matcher, "/1/"); assertNotMatched(matcher, "/1/two"); assertNotMatched(matcher, "/1/one1"); assertNotMatched(matcher, "/1/on"); assertNotMatched(matcher, "/1/one/two"); } private static void assertMatched(ImmutablePathMatcher<Object> matcher, String path, Object handler) { var match = matcher.match(path); assertEquals(handler, match.getValue()); } private static void assertMatched(ImmutablePathMatcher<Object> matcher, String path) { assertMatched(matcher, path, HANDLER); } private static <T> void assertNotMatched(ImmutablePathMatcher<T> matcher, String path) { var match = matcher.match(path); assertNull(match.getValue()); } }
PathMatcherTest
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherFactoryTests.java
{ "start": 10116, "end": 16538 }
class ____ created by TestLauncherInterceptor1").contains( InterceptedTestEngine.ID); })); } @Test void appliesLauncherInterceptorsToTestDiscovery() { InterceptorInjectedLauncherSessionListener.CALLS = 0; withTestServices(() -> withSystemProperty(ENABLE_LAUNCHER_INTERCEPTORS, "true", () -> { var engine = new TestEngineSpy() { @Override public TestDescriptor discover(EngineDiscoveryRequest discoveryRequest, UniqueId uniqueId) { throw new RuntimeException("from discovery"); } }; var config = LauncherConfig.builder() // .enableTestEngineAutoRegistration(false) // .addTestEngines(engine) // .build(); var launcher = LauncherFactory.create(config); var request = request().build(); var exception = assertThrows(RuntimeException.class, () -> launcher.discover(request)); assertThat(exception) // .hasRootCauseMessage("from discovery") // .hasStackTraceContaining(TestLauncherInterceptor1.class.getName() + ".intercept(") // .hasStackTraceContaining(TestLauncherInterceptor2.class.getName() + ".intercept("); assertThat(InterceptorInjectedLauncherSessionListener.CALLS).isEqualTo(1); })); } @Test void appliesLauncherInterceptorsToTestExecution() { InterceptorInjectedLauncherSessionListener.CALLS = 0; withTestServices(() -> withSystemProperty(ENABLE_LAUNCHER_INTERCEPTORS, "true", () -> { var engine = new TestEngineSpy() { @Override public void execute(ExecutionRequest request) { throw new RuntimeException("from execution"); } }; var config = LauncherConfig.builder() // .enableTestEngineAutoRegistration(false) // .addTestEngines(engine) // .build(); AtomicReference<TestExecutionResult> result = new AtomicReference<>(); var listener = new TestExecutionListener() { @Override public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) { if (testIdentifier.getParentId().isEmpty()) { result.set(testExecutionResult); } } }; var request = request() // .configurationParameter(LauncherConstants.STACKTRACE_PRUNING_ENABLED_PROPERTY_NAME, "false") // .forExecution() // .listeners(listener) // .build(); var launcher = LauncherFactory.create(config); launcher.execute(request); assertThat(requireNonNull(result.get()).getThrowable().orElseThrow()) // .hasRootCauseMessage("from execution") // .hasStackTraceContaining(TestLauncherInterceptor1.class.getName() + ".intercept(") // .hasStackTraceContaining(TestLauncherInterceptor2.class.getName() + ".intercept("); assertThat(InterceptorInjectedLauncherSessionListener.CALLS).isEqualTo(1); })); } @Test void extensionCanReadValueFromSessionStoreAndReadByLauncherSessionListenerOnOpened() { var config = LauncherConfig.builder() // .addLauncherSessionListeners(new LauncherSessionListenerOpenedExample()) // .build(); try (LauncherSession session = LauncherFactory.openSession(config)) { AtomicReference<Throwable> errorRef = new AtomicReference<>(); var listener = new TestExecutionListener() { @Override public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) { testExecutionResult.getThrowable().ifPresent(errorRef::set); } }; var request = request() // .selectors(selectClass(SessionTrackingTestCase.class)) // .forExecution() // .listeners(listener) // .build(); session.getLauncher().execute(request); assertThat(errorRef.get()).isNull(); } } @Test void extensionCanReadValueFromSessionStoreAndReadByLauncherSessionListenerOnClose() { var config = LauncherConfig.builder() // .addLauncherSessionListeners(new LauncherSessionListenerClosedExample()) // .build(); try (LauncherSession session = LauncherFactory.openSession(config)) { AtomicReference<Throwable> errorRef = new AtomicReference<>(); var listener = new TestExecutionListener() { @Override public void executionFinished(TestIdentifier testIdentifier, TestExecutionResult testExecutionResult) { testExecutionResult.getThrowable().ifPresent(errorRef::set); } }; var request = request() // .selectors(selectClass(SessionStoringTestCase.class)) // .forExecution() // .listeners(listener) // .build(); session.getLauncher().execute(request); assertThat(errorRef.get()).isNull(); } } @Test void sessionResourceClosedOnSessionClose() { CloseTrackingResource.closed = false; var config = LauncherConfig.builder() // .addLauncherSessionListeners(new AutoCloseCheckListener()) // .build(); try (LauncherSession session = LauncherFactory.openSession(config)) { var request = request() // .selectors(selectClass(SessionResourceAutoCloseTestCase.class)) // .forExecution() // .build(); session.getLauncher().execute(request); assertThat(CloseTrackingResource.closed).isFalse(); } assertThat(CloseTrackingResource.closed).isTrue(); } @Test void requestResourceClosedOnExecutionClose() { CloseTrackingResource.closed = false; var config = LauncherConfig.builder().build(); try (LauncherSession session = LauncherFactory.openSession(config)) { var request = request() // .selectors(selectClass(RequestResourceAutoCloseTestCase.class)) // .forExecution() // .build(); session.getLauncher().execute(request); assertThat(CloseTrackingResource.closed).isTrue(); } } @SuppressWarnings("SameParameterValue") private static void withSystemProperty(String key, String value, Runnable runnable) { var oldValue = System.getProperty(key); System.setProperty(key, value); try { runnable.run(); } finally { if (oldValue == null) { System.clearProperty(key); } else { System.setProperty(key, oldValue); } } } private static void withTestServices(Runnable runnable) { withAdditionalClasspathRoot("testservices/", runnable); } private LauncherDiscoveryRequest createLauncherDiscoveryRequestForBothStandardEngineExampleClasses() { // @formatter:off return request() .selectors(selectClasses(JUnit4Example.class, JUnit5Example.class)) .enableImplicitConfigurationParameters(false) .build(); // @formatter:on } @SuppressWarnings({ "NewClassNamingConvention", "JUnitMalformedDeclaration" }) public static
loader
java
google__error-prone
check_api/src/test/java/com/google/errorprone/util/CommentsTest.java
{ "start": 10374, "end": 11006 }
class ____ { abstract void target(Object param1, Object param2); private void test(Object param1, Object param2) { // BUG: Diagnostic contains: [[] param1 [1], [] param2 []] target(param1, /* 1 */ param2); } } """) .doTest(); } @Test public void findCommentsForArguments_assignToSecondParameter_withLineCommentAfterMethod() { CompilationTestHelper.newInstance(PrintCommentsForArguments.class, getClass()) .addSourceLines( "Test.java", """ abstract
Test
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/annotation/ConfigurationClassWithConditionTests.java
{ "start": 5821, "end": 5992 }
class ____ { @Bean public ExampleBean bean2() { return new ExampleBean(); } } @Configuration @Conditional(HasBeanOneCondition.class) static
BeanTwoConfiguration
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/metamodel/mapping/internal/AbstractEntityCollectionPart.java
{ "start": 2202, "end": 15446 }
class ____ implements EntityCollectionPart, FetchOptions, TableGroupProducer { private final NavigableRole navigableRole; private final Nature nature; private final CollectionPersister collectionDescriptor; private final EntityMappingType associatedEntityTypeDescriptor; private final NotFoundAction notFoundAction; protected final Set<String> targetKeyPropertyNames; public AbstractEntityCollectionPart( Nature nature, Collection collectionBootDescriptor, CollectionPersister collectionDescriptor, EntityMappingType associatedEntityTypeDescriptor, NotFoundAction notFoundAction, MappingModelCreationProcess creationProcess) { this.navigableRole = collectionDescriptor.getNavigableRole().appendContainer( nature.getName() ); this.nature = nature; this.collectionDescriptor = collectionDescriptor; this.associatedEntityTypeDescriptor = associatedEntityTypeDescriptor; this.notFoundAction = notFoundAction; this.targetKeyPropertyNames = resolveTargetKeyPropertyNames( nature, collectionDescriptor, collectionBootDescriptor, associatedEntityTypeDescriptor, creationProcess ); } /** * For Hibernate Reactive */ protected AbstractEntityCollectionPart(AbstractEntityCollectionPart original) { this.navigableRole = original.navigableRole; this.nature = original.nature; this.collectionDescriptor = original.collectionDescriptor; this.associatedEntityTypeDescriptor = original.associatedEntityTypeDescriptor; this.notFoundAction = original.notFoundAction; this.targetKeyPropertyNames = original.targetKeyPropertyNames; } @Override public String toString() { return "EntityCollectionPart(" + navigableRole.getFullPath() + ")@" + System.identityHashCode( this ); } public CollectionPersister getCollectionDescriptor() { return collectionDescriptor; } @Override public EntityMappingType getMappedType() { return getAssociatedEntityMappingType(); } @Override public NavigableRole getNavigableRole() { return navigableRole; } @Override public Nature getNature() { return nature; } @Override public PluralAttributeMapping getCollectionAttribute() { return collectionDescriptor.getAttributeMapping(); } @Override public String getFetchableName() { return nature.getName(); } @Override public int getFetchableKey() { return nature == Nature.INDEX || !collectionDescriptor.hasIndex() ? 0 : 1; } @Override public EntityMappingType getAssociatedEntityMappingType() { return associatedEntityTypeDescriptor; } @Override public NotFoundAction getNotFoundAction() { return notFoundAction; } @Override public FetchOptions getMappedFetchOptions() { return this; } @Override public FetchStyle getStyle() { return FetchStyle.JOIN; } @Override public FetchTiming getTiming() { return FetchTiming.IMMEDIATE; } @Override public boolean incrementFetchDepth() { // the collection itself already increments the depth return false; } @Override public boolean isOptional() { return false; } @Override public boolean isUnwrapProxy() { return false; } @Override public EntityMappingType findContainingEntityMapping() { return collectionDescriptor.getAttributeMapping().findContainingEntityMapping(); } @Override public int getNumberOfFetchables() { return getAssociatedEntityMappingType().getNumberOfFetchables(); } @Override public <T> DomainResult<T> createDomainResult( NavigablePath navigablePath, TableGroup tableGroup, String resultVariable, DomainResultCreationState creationState) { final TableGroup partTableGroup = resolveTableGroup( navigablePath, creationState ); return associatedEntityTypeDescriptor.createDomainResult( navigablePath, partTableGroup, resultVariable, creationState ); } @Override public Object disassemble(Object value, SharedSessionContractImplementor session) { if ( value == null ) { return null; } // should be an instance of the associated entity return getAssociatedEntityMappingType().getIdentifierMapping().getIdentifier( value ); } @Override public EntityFetch generateFetch( FetchParent fetchParent, NavigablePath fetchablePath, FetchTiming fetchTiming, boolean selected, String resultVariable, DomainResultCreationState creationState) { final var associationKey = resolveFetchAssociationKey(); final boolean added = creationState.registerVisitedAssociationKey( associationKey ); final var partTableGroup = resolveTableGroup( fetchablePath, creationState ); final var fetch = buildEntityFetchJoined( fetchParent, this, partTableGroup, fetchablePath, creationState ); if ( added ) { creationState.removeVisitedAssociationKey( associationKey ); } return fetch; } /** * For Hibernate Reactive */ protected EagerCollectionFetch buildEagerCollectionFetch( NavigablePath fetchedPath, PluralAttributeMapping fetchedAttribute, TableGroup collectionTableGroup, FetchParent fetchParent, DomainResultCreationState creationState) { return new EagerCollectionFetch( fetchedPath, fetchedAttribute, collectionTableGroup, true, fetchParent, creationState ); } /** * For Hibernate Reactive */ protected EntityFetch buildEntityFetchJoined( FetchParent fetchParent, AbstractEntityCollectionPart abstractEntityCollectionPart, TableGroup partTableGroup, NavigablePath fetchablePath, DomainResultCreationState creationState) { return new EntityFetchJoinedImpl( fetchParent, abstractEntityCollectionPart, partTableGroup, fetchablePath, creationState ); } protected abstract AssociationKey resolveFetchAssociationKey(); private TableGroup resolveTableGroup(NavigablePath fetchablePath, DomainResultCreationState creationState) { final var fromClauseAccess = creationState.getSqlAstCreationState().getFromClauseAccess(); return fromClauseAccess.resolveTableGroup( fetchablePath, (np) -> { final var parentTableGroup = (PluralTableGroup) fromClauseAccess.getTableGroup( np.getParent() ); return switch ( nature ) { case ELEMENT -> parentTableGroup.getElementTableGroup(); case INDEX -> resolveIndexTableGroup( parentTableGroup, fetchablePath, fromClauseAccess, creationState ); default -> throw new IllegalStateException( "Could not find table group for: " + np ); }; } ); } private TableGroup resolveIndexTableGroup( PluralTableGroup collectionTableGroup, NavigablePath fetchablePath, FromClauseAccess fromClauseAccess, DomainResultCreationState creationState) { return collectionTableGroup.getIndexTableGroup(); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // TableGroupProducer @Override public String getSqlAliasStem() { return getCollectionDescriptor().getAttributeMapping().getSqlAliasStem(); } @Override public boolean containsTableReference(String tableExpression) { return getAssociatedEntityMappingType().containsTableReference( tableExpression ); } public TableGroup createTableGroupInternal( boolean canUseInnerJoins, NavigablePath navigablePath, boolean fetched, String sourceAlias, final SqlAliasBase sqlAliasBase, SqlAstCreationState creationState) { final var creationContext = creationState.getCreationContext(); final var primaryTableReference = getEntityMappingType() .createPrimaryTableReference( sqlAliasBase, creationState ); final TableGroup tableGroup = new StandardTableGroup( canUseInnerJoins, navigablePath, this, fetched, sourceAlias, primaryTableReference, true, sqlAliasBase, getEntityMappingType().getRootEntityDescriptor()::containsTableReference, (tableExpression, group) -> getEntityMappingType().createTableReferenceJoin( tableExpression, sqlAliasBase, primaryTableReference, creationState ), creationContext.getSessionFactory() ); // Make sure the association key's table is resolved in the table group tableGroup.getTableReference( null, resolveFetchAssociationKey().table(), true ); return tableGroup; } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Initialization private static Set<String> resolveTargetKeyPropertyNames( Nature nature, CollectionPersister collectionDescriptor, Collection collectionBootDescriptor, EntityMappingType elementTypeDescriptor, MappingModelCreationProcess creationProcess) { final Value bootModelValue = nature == Nature.INDEX ? ( (IndexedCollection) collectionBootDescriptor ).getIndex() : collectionBootDescriptor.getElement(); final var entityBinding = creationProcess.getCreationContext().getMetadata() .getEntityBinding( elementTypeDescriptor.getEntityName() ); final String referencedPropertyName; if ( bootModelValue instanceof OneToMany ) { final String mappedByProperty = collectionDescriptor.getMappedByProperty(); referencedPropertyName = isEmpty( mappedByProperty ) ? null : mappedByProperty; } else if ( bootModelValue instanceof ToOne toOne ) { referencedPropertyName = toOne.getReferencedPropertyName(); } else { throw new AssertionFailure( "Expected a OneToMany or ToOne" ); } if ( referencedPropertyName == null ) { final Set<String> targetKeyPropertyNames = new HashSet<>( 2 ); targetKeyPropertyNames.add( EntityIdentifierMapping.ID_ROLE_NAME ); final Type propertyType = entityBinding.getIdentifierMapper() == null ? entityBinding.getIdentifier().getType() : entityBinding.getIdentifierMapper().getType(); if ( entityBinding.getIdentifierProperty() == null ) { if ( propertyType instanceof ComponentType compositeType && compositeType.isEmbedded() && compositeType.getPropertyNames().length == 1 ) { ToOneAttributeMapping.addPrefixedPropertyPaths( targetKeyPropertyNames, compositeType.getPropertyNames()[0], compositeType.getSubtypes()[0], creationProcess.getCreationContext().getSessionFactory() ); ToOneAttributeMapping.addPrefixedPropertyNames( targetKeyPropertyNames, EntityIdentifierMapping.ID_ROLE_NAME, propertyType, creationProcess.getCreationContext().getSessionFactory() ); } else { ToOneAttributeMapping.addPrefixedPropertyPaths( targetKeyPropertyNames, null, propertyType, creationProcess.getCreationContext().getSessionFactory() ); } } else { ToOneAttributeMapping.addPrefixedPropertyPaths( targetKeyPropertyNames, entityBinding.getIdentifierProperty().getName(), propertyType, creationProcess.getCreationContext().getSessionFactory() ); } return targetKeyPropertyNames; } else if ( bootModelValue instanceof OneToMany ) { final Set<String> targetKeyPropertyNames = new HashSet<>( 2 ); int dotIndex = -1; while ( ( dotIndex = referencedPropertyName.indexOf( '.', dotIndex + 1 ) ) != -1 ) { targetKeyPropertyNames.add( referencedPropertyName.substring( 0, dotIndex ) ); } // todo (PropertyMapping) : the problem here is timing. this needs to be delayed. ToOneAttributeMapping.addPrefixedPropertyPaths( targetKeyPropertyNames, referencedPropertyName, elementTypeDescriptor.getEntityPersister().getPropertyType( referencedPropertyName ), creationProcess.getCreationContext().getSessionFactory() ); return targetKeyPropertyNames; } else { final Type propertyType = entityBinding.getRecursiveProperty( referencedPropertyName ).getType(); if ( propertyType instanceof ComponentType compositeType && compositeType.isEmbedded() && compositeType.getPropertyNames().length == 1 ) { final Set<String> targetKeyPropertyNames = new HashSet<>( 2 ); ToOneAttributeMapping.addPrefixedPropertyPaths( targetKeyPropertyNames, compositeType.getPropertyNames()[0], compositeType.getSubtypes()[0], creationProcess.getCreationContext().getSessionFactory() ); ToOneAttributeMapping.addPrefixedPropertyNames( targetKeyPropertyNames, EntityIdentifierMapping.ID_ROLE_NAME, propertyType, creationProcess.getCreationContext().getSessionFactory() ); return targetKeyPropertyNames; } else { final Set<String> targetKeyPropertyNames = new HashSet<>( 2 ); targetKeyPropertyNames.add( EntityIdentifierMapping.ID_ROLE_NAME ); targetKeyPropertyNames.add( referencedPropertyName ); final String mapsIdAttributeName = findMapsIdPropertyName( elementTypeDescriptor, referencedPropertyName ); if ( mapsIdAttributeName != null ) { ToOneAttributeMapping.addPrefixedPropertyPaths( targetKeyPropertyNames, mapsIdAttributeName, elementTypeDescriptor.getEntityPersister().getIdentifierType(), creationProcess.getCreationContext().getSessionFactory() ); } else { ToOneAttributeMapping.addPrefixedPropertyPaths( targetKeyPropertyNames, null, propertyType, creationProcess.getCreationContext().getSessionFactory() ); } return targetKeyPropertyNames; } } } }
AbstractEntityCollectionPart
java
quarkusio__quarkus
extensions/vertx-http/runtime/src/main/java/io/quarkus/vertx/http/runtime/CurrentRequestProducer.java
{ "start": 448, "end": 646 }
class ____ { @Named("vertxRequest") @Produces @RequestScoped public HttpServerRequest getCurrentRequest(RoutingContext rc) { return rc.request(); } }
CurrentRequestProducer
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/io/checkpointing/BarrierAlignmentUtil.java
{ "start": 2550, "end": 3001 }
interface ____ { /** * Register a task to be executed some time later. * * @param callable the task to submit * @param delay how long after the delay to execute the task * @return the Cancellable, it can cancel the task. */ Cancellable registerTask(Callable<?> callable, Duration delay); } /** A handle to a delayed action which can be cancelled. */ public
DelayableTimer
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/cache/CacheRegionStatisticsTest.java
{ "start": 1570, "end": 2797 }
class ____ { @Test @JiraKey(value = "HHH-15105") public void testAccessDefaultQueryRegionStatistics(SessionFactoryScope scope) { final Statistics statistics = scope.getSessionFactory().getStatistics(); final CacheRegionStatistics queryRegionStatistics = statistics.getQueryRegionStatistics( "default-query-results-region" ); scope.inTransaction( session -> { List<Dog> resultList = session.createQuery( "from Dog", Dog.class ) .setCacheable( true ) .getResultList(); assertEquals( 1, queryRegionStatistics.getMissCount() ); } ); } @BeforeEach public void setupData(SessionFactoryScope scope) { scope.inTransaction( session -> { Dog yogi = new Dog( "Yogi" ); yogi.nickNames.add( "The Yog" ); yogi.nickNames.add( "Little Boy" ); yogi.nickNames.add( "Yogaroni Macaroni" ); Dog irma = new Dog( "Irma" ); irma.nickNames.add( "Squirmy" ); irma.nickNames.add( "Bird" ); session.persist( yogi ); session.persist( irma ); } ); } @AfterEach public void cleanupData(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncateMappedObjects(); } @Entity(name = "Dog") public static
CacheRegionStatisticsTest
java
alibaba__nacos
plugin/control/src/main/java/com/alibaba/nacos/plugin/control/connection/response/ConnectionCheckResponse.java
{ "start": 748, "end": 1545 }
class ____ { private boolean success; private String message; private int code; private String limitMessage; public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public int getCode() { return code; } public void setCode(int code) { this.code = code; } public String getLimitMessage() { return limitMessage; } public void setLimitMessage(String limitMessage) { this.limitMessage = limitMessage; } }
ConnectionCheckResponse
java
spring-projects__spring-framework
spring-expression/src/test/java/org/springframework/expression/spel/SpelCompilationCoverageTests.java
{ "start": 8148, "end": 27675 }
class ____ { @Test void indexIntoPrimitiveShortArray() { short[] shorts = { (short) 33, (short) 44, (short) 55 }; expression = parser.parseExpression("[2]"); assertThat(expression.getValue(shorts)).isEqualTo((short) 55); assertCanCompile(expression); assertThat(expression.getValue(shorts)).isEqualTo((short) 55); assertThat(getAst().getExitDescriptor()).isEqualTo("S"); } @Test void indexIntoPrimitiveByteArray() { byte[] bytes = { (byte) 2, (byte) 3, (byte) 4 }; expression = parser.parseExpression("[2]"); assertThat(expression.getValue(bytes)).isEqualTo((byte) 4); assertCanCompile(expression); assertThat(expression.getValue(bytes)).isEqualTo((byte) 4); assertThat(getAst().getExitDescriptor()).isEqualTo("B"); } @Test void indexIntoPrimitiveIntArray() { int[] ints = { 8, 9, 10 }; expression = parser.parseExpression("[2]"); assertThat(expression.getValue(ints)).isEqualTo(10); assertCanCompile(expression); assertThat(expression.getValue(ints)).isEqualTo(10); assertThat(getAst().getExitDescriptor()).isEqualTo("I"); } @Test void indexIntoPrimitiveLongArray() { long[] longs = { 2L, 3L, 4L }; expression = parser.parseExpression("[0]"); assertThat(expression.getValue(longs)).isEqualTo(2L); assertCanCompile(expression); assertThat(expression.getValue(longs)).isEqualTo(2L); assertThat(getAst().getExitDescriptor()).isEqualTo("J"); } @Test void indexIntoPrimitiveFloatArray() { float[] floats = { 6.0f, 7.0f, 8.0f }; expression = parser.parseExpression("[0]"); assertThat(expression.getValue(floats)).isEqualTo(6.0f); assertCanCompile(expression); assertThat(expression.getValue(floats)).isEqualTo(6.0f); assertThat(getAst().getExitDescriptor()).isEqualTo("F"); } @Test void indexIntoPrimitiveDoubleArray() { double[] doubles = { 3.0d, 4.0d, 5.0d }; expression = parser.parseExpression("[1]"); assertThat(expression.getValue(doubles)).isEqualTo(4.0d); assertCanCompile(expression); assertThat(expression.getValue(doubles)).isEqualTo(4.0d); assertThat(getAst().getExitDescriptor()).isEqualTo("D"); } @Test void indexIntoPrimitiveCharArray() { char[] chars = { 'a', 'b', 'c' }; expression = parser.parseExpression("[1]"); assertThat(expression.getValue(chars)).isEqualTo('b'); assertCanCompile(expression); assertThat(expression.getValue(chars)).isEqualTo('b'); assertThat(getAst().getExitDescriptor()).isEqualTo("C"); } @Test void indexIntoPrimitiveBooleanArray() { boolean[] booleans = { true, false }; expression = parser.parseExpression("[1]"); assertThat(expression.getValue(booleans)).isEqualTo(false); assertCanCompile(expression); assertThat(expression.getValue(booleans)).isEqualTo(false); assertThat(getAst().getExitDescriptor()).isEqualTo("Z"); } @Test void indexIntoStringArray() { String[] strings = { "a", "b", "c" }; expression = parser.parseExpression("[0]"); assertThat(expression.getValue(strings)).isEqualTo("a"); assertCanCompile(expression); assertThat(expression.getValue(strings)).isEqualTo("a"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/String"); } @Test void indexIntoNumberArray() { Number[] numbers = { 2, 8, 9 }; expression = parser.parseExpression("[1]"); assertThat(expression.getValue(numbers)).isEqualTo(8); assertCanCompile(expression); assertThat(expression.getValue(numbers)).isEqualTo(8); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Number"); } @Test void indexInto2DPrimitiveIntArray() { int[][] array = new int[][] { { 1, 2, 3 }, { 4, 5, 6 } }; expression = parser.parseExpression("[1]"); assertThat(stringify(expression.getValue(array))).isEqualTo("4 5 6"); assertCanCompile(expression); assertThat(stringify(expression.getValue(array))).isEqualTo("4 5 6"); assertThat(getAst().getExitDescriptor()).isEqualTo("[I"); expression = parser.parseExpression("[1][2]"); assertThat(stringify(expression.getValue(array))).isEqualTo("6"); assertCanCompile(expression); assertThat(stringify(expression.getValue(array))).isEqualTo("6"); assertThat(getAst().getExitDescriptor()).isEqualTo("I"); } @Test void indexInto2DStringArray() { String[][] array = new String[][] { { "a", "b", "c" }, { "d", "e", "f" } }; expression = parser.parseExpression("[1]"); assertThat(stringify(expression.getValue(array))).isEqualTo("d e f"); assertCanCompile(expression); assertThat(getAst().getExitDescriptor()).isEqualTo("[Ljava/lang/String"); assertThat(stringify(expression.getValue(array))).isEqualTo("d e f"); assertThat(getAst().getExitDescriptor()).isEqualTo("[Ljava/lang/String"); expression = parser.parseExpression("[1][2]"); assertThat(stringify(expression.getValue(array))).isEqualTo("f"); assertCanCompile(expression); assertThat(stringify(expression.getValue(array))).isEqualTo("f"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/String"); } @Test @SuppressWarnings("unchecked") void indexIntoArrayOfListOfString() { List<String>[] array = new List[] { List.of("a", "b", "c"), List.of("d", "e", "f") }; expression = parser.parseExpression("[1]"); assertThat(stringify(expression.getValue(array))).isEqualTo("d e f"); assertCanCompile(expression); assertThat(stringify(expression.getValue(array))).isEqualTo("d e f"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/util/List"); expression = parser.parseExpression("[1][2]"); assertThat(stringify(expression.getValue(array))).isEqualTo("f"); assertCanCompile(expression); assertThat(stringify(expression.getValue(array))).isEqualTo("f"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); } @Test @SuppressWarnings("unchecked") void indexIntoArrayOfMap() { Map<String, String>[] array = new Map[] { Map.of("key", "value1") }; expression = parser.parseExpression("[0]"); assertThat(stringify(expression.getValue(array))).isEqualTo("{key=value1}"); assertCanCompile(expression); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/util/Map"); assertThat(stringify(expression.getValue(array))).isEqualTo("{key=value1}"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/util/Map"); expression = parser.parseExpression("[0]['key']"); assertThat(stringify(expression.getValue(array))).isEqualTo("value1"); assertCanCompile(expression); assertThat(stringify(expression.getValue(array))).isEqualTo("value1"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); } @Test void indexIntoListOfString() { List<String> list = List.of("aaa", "bbb", "ccc"); expression = parser.parseExpression("[1]"); assertThat(expression.getValue(list)).isEqualTo("bbb"); assertCanCompile(expression); assertThat(expression.getValue(list)).isEqualTo("bbb"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); } @Test void indexIntoListOfInteger() { List<Integer> list = List.of(123, 456, 789); expression = parser.parseExpression("[2]"); assertThat(expression.getValue(list)).isEqualTo(789); assertCanCompile(expression); assertThat(expression.getValue(list)).isEqualTo(789); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); } @Test void indexIntoListOfStringArray() { List<String[]> list = List.of( new String[] { "a", "b", "c" }, new String[] { "d", "e", "f" } ); expression = parser.parseExpression("[1]"); assertThat(stringify(expression.getValue(list))).isEqualTo("d e f"); assertCanCompile(expression); assertThat(stringify(expression.getValue(list))).isEqualTo("d e f"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); expression = parser.parseExpression("[1][0]"); assertThat(stringify(expression.getValue(list))).isEqualTo("d"); assertCanCompile(expression); assertThat(stringify(expression.getValue(list))).isEqualTo("d"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/String"); } @Test void indexIntoListOfIntegerArray() { List<Integer[]> list = List.of( new Integer[] { 1, 2, 3 }, new Integer[] { 4, 5, 6 } ); expression = parser.parseExpression("[0]"); assertThat(stringify(expression.getValue(list))).isEqualTo("1 2 3"); assertCanCompile(expression); assertThat(stringify(expression.getValue(list))).isEqualTo("1 2 3"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); expression = parser.parseExpression("[0][1]"); assertThat(expression.getValue(list)).isEqualTo(2); assertCanCompile(expression); assertThat(expression.getValue(list)).isEqualTo(2); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Integer"); } @Test void indexIntoListOfListOfString() { List<List<String>> list = List.of( List.of("a", "b", "c"), List.of("d", "e", "f") ); expression = parser.parseExpression("[1]"); assertThat(stringify(expression.getValue(list))).isEqualTo("d e f"); assertCanCompile(expression); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); assertThat(stringify(expression.getValue(list))).isEqualTo("d e f"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); expression = parser.parseExpression("[1][2]"); assertThat(stringify(expression.getValue(list))).isEqualTo("f"); assertCanCompile(expression); assertThat(stringify(expression.getValue(list))).isEqualTo("f"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); } @Test void indexIntoMap() { Map<String, Integer> map = Map.of("aaa", 111); expression = parser.parseExpression("['aaa']"); assertThat(expression.getValue(map)).isEqualTo(111); assertCanCompile(expression); assertThat(expression.getValue(map)).isEqualTo(111); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // String key not enclosed in single quotes expression = parser.parseExpression("[aaa]"); assertThat(expression.getValue(map)).isEqualTo(111); assertCanCompile(expression); assertThat(expression.getValue(map)).isEqualTo(111); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); } @Test void indexIntoMapOfListOfString() { Map<String, List<String>> map = Map.of("foo", List.of("a", "b", "c")); expression = parser.parseExpression("['foo']"); assertThat(stringify(expression.getValue(map))).isEqualTo("a b c"); assertCanCompile(expression); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); assertThat(stringify(expression.getValue(map))).isEqualTo("a b c"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); expression = parser.parseExpression("['foo'][2]"); assertThat(stringify(expression.getValue(map))).isEqualTo("c"); assertCanCompile(expression); assertThat(stringify(expression.getValue(map))).isEqualTo("c"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); } @Test // gh-32356 void indexIntoMapOfPrimitiveIntArray() { Map<String, int[]> map = Map.of("foo", new int[] { 1, 2, 3 }); // Prerequisite: root type must not be public for this use case. assertNotPublic(map.getClass()); // map key access expression = parser.parseExpression("['foo']"); assertThat(stringify(expression.getValue(map))).isEqualTo("1 2 3"); assertCanCompile(expression); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); assertThat(stringify(expression.getValue(map))).isEqualTo("1 2 3"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // map key access via implicit #root & array index expression = parser.parseExpression("['foo'][1]"); assertThat(expression.getValue(map)).isEqualTo(2); assertCanCompile(expression); assertThat(expression.getValue(map)).isEqualTo(2); // map key access via explicit #root & array index expression = parser.parseExpression("#root['foo'][1]"); assertThat(expression.getValue(map)).isEqualTo(2); assertCanCompile(expression); assertThat(expression.getValue(map)).isEqualTo(2); // map key access via explicit #this & array index expression = parser.parseExpression("#this['foo'][1]"); assertThat(expression.getValue(map)).isEqualTo(2); assertCanCompile(expression); assertThat(expression.getValue(map)).isEqualTo(2); } @Test // gh-32356 void indexIntoMapOfPrimitiveIntArrayWithMapAccessor() { StandardEvaluationContext context = new StandardEvaluationContext(); context.addPropertyAccessor(new MapAccessor()); Map<String, int[]> map = Map.of("foo", new int[] { 1, 2, 3 }); // Prerequisite: root type must not be public for this use case. assertNotPublic(map.getClass()); // map key access expression = parser.parseExpression("['foo']"); assertThat(stringify(expression.getValue(context, map))).isEqualTo("1 2 3"); assertCanCompile(expression); assertThat(stringify(expression.getValue(context, map))).isEqualTo("1 2 3"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // custom MapAccessor via implicit #root & array index expression = parser.parseExpression("foo[1]"); assertThat(expression.getValue(context, map)).isEqualTo(2); assertCanCompile(expression); assertThat(expression.getValue(context, map)).isEqualTo(2); // custom MapAccessor via explicit #root & array index expression = parser.parseExpression("#root.foo[1]"); assertThat(expression.getValue(context, map)).isEqualTo(2); assertCanCompile(expression); assertThat(expression.getValue(context, map)).isEqualTo(2); // custom MapAccessor via explicit #this & array index expression = parser.parseExpression("#this.foo[1]"); assertThat(expression.getValue(context, map)).isEqualTo(2); assertCanCompile(expression); assertThat(expression.getValue(context, map)).isEqualTo(2); // map key access & array index expression = parser.parseExpression("['foo'][2]"); assertThat(stringify(expression.getValue(context, map))).isEqualTo("3"); assertCanCompile(expression); assertThat(stringify(expression.getValue(context, map))).isEqualTo("3"); assertThat(getAst().getExitDescriptor()).isEqualTo("I"); } @Test void indexIntoSetCannotBeCompiled() { Set<Integer> set = Set.of(42); expression = parser.parseExpression("[0]"); assertThat(expression.getValue(set)).isEqualTo(42); assertCannotCompile(expression); assertThat(expression.getValue(set)).isEqualTo(42); assertThat(getAst().getExitDescriptor()).isNull(); } @Test void indexIntoStringCannotBeCompiled() { String text = "enigma"; // "g" is the 4th letter in "enigma" (index 3) expression = parser.parseExpression("[3]"); assertThat(expression.getValue(text)).isEqualTo("g"); assertCannotCompile(expression); assertThat(expression.getValue(text)).isEqualTo("g"); assertThat(getAst().getExitDescriptor()).isNull(); } @Test void indexIntoObject() { TestClass6 tc = new TestClass6(); // field access expression = parser.parseExpression("['orange']"); assertThat(expression.getValue(tc)).isEqualTo("value1"); assertCanCompile(expression); assertThat(expression.getValue(tc)).isEqualTo("value1"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/String"); // field access expression = parser.parseExpression("['peach']"); assertThat(expression.getValue(tc)).isEqualTo(34L); assertCanCompile(expression); assertThat(expression.getValue(tc)).isEqualTo(34L); assertThat(getAst().getExitDescriptor()).isEqualTo("J"); // property access (getter) expression = parser.parseExpression("['banana']"); assertThat(expression.getValue(tc)).isEqualTo("value3"); assertCanCompile(expression); assertThat(expression.getValue(tc)).isEqualTo("value3"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/String"); } @Test // gh-32694, gh-32908 void indexIntoArrayUsingIntegerWrapper() { context.setVariable("array", new int[] {1, 2, 3, 4}); context.setVariable("index", 2); expression = parser.parseExpression("#array[#index]"); assertThat(expression.getValue(context)).isEqualTo(3); assertCanCompile(expression); assertThat(expression.getValue(context)).isEqualTo(3); assertThat(getAst().getExitDescriptor()).isEqualTo("I"); } @Test // gh-32694, gh-32908 void indexIntoListUsingIntegerWrapper() { context.setVariable("list", List.of(1, 2, 3, 4)); context.setVariable("index", 2); expression = parser.parseExpression("#list[#index]"); assertThat(expression.getValue(context)).isEqualTo(3); assertCanCompile(expression); assertThat(expression.getValue(context)).isEqualTo(3); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); } @Test // gh-32903 void indexIntoMapUsingPrimitiveLiteral() { Map<Object, String> map = Map.of( false, "0", // BooleanLiteral 1, "ABC", // IntLiteral 2L, "XYZ", // LongLiteral 9.99F, "~10", // FloatLiteral 3.14159, "PI" // RealLiteral ); context.setVariable("map", map); // BooleanLiteral expression = parser.parseExpression("#map[false]"); assertThat(expression.getValue(context)).isEqualTo("0"); assertCanCompile(expression); assertThat(expression.getValue(context)).isEqualTo("0"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // IntLiteral expression = parser.parseExpression("#map[1]"); assertThat(expression.getValue(context)).isEqualTo("ABC"); assertCanCompile(expression); assertThat(expression.getValue(context)).isEqualTo("ABC"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // LongLiteral expression = parser.parseExpression("#map[2L]"); assertThat(expression.getValue(context)).isEqualTo("XYZ"); assertCanCompile(expression); assertThat(expression.getValue(context)).isEqualTo("XYZ"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // FloatLiteral expression = parser.parseExpression("#map[9.99F]"); assertThat(expression.getValue(context)).isEqualTo("~10"); assertCanCompile(expression); assertThat(expression.getValue(context)).isEqualTo("~10"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); // RealLiteral expression = parser.parseExpression("#map[3.14159]"); assertThat(expression.getValue(context)).isEqualTo("PI"); assertCanCompile(expression); assertThat(expression.getValue(context)).isEqualTo("PI"); assertThat(getAst().getExitDescriptor()).isEqualTo("Ljava/lang/Object"); } private String stringify(Object object) { Stream<? extends Object> stream; if (object instanceof Collection<?> collection) { stream = collection.stream(); } else if (object instanceof Object[] objects) { stream = Arrays.stream(objects); } else if (object instanceof int[] ints) { stream = Arrays.stream(ints).mapToObj(Integer::valueOf); } else { return String.valueOf(object); } return stream.map(Object::toString).collect(joining(" ")); } @Nested
IndexingTests
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/AbstractAWSCredentialProvider.java
{ "start": 1033, "end": 1144 }
class ____ AWS credential providers which * take a URI and config in their constructor. * */ public abstract
for
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/bugs/_2663/Request.java
{ "start": 232, "end": 709 }
class ____ { private Nullable<String> name = Nullable.undefined(); private Nullable<ChildRequest> child = Nullable.undefined(); public Nullable<String> getName() { return name; } public void setName(Nullable<String> name) { this.name = name; } public Nullable<ChildRequest> getChild() { return child; } public void setChild(Nullable<ChildRequest> child) { this.child = child; } public static
Request
java
alibaba__druid
core/src/main/java/com/alibaba/druid/support/spring/stat/SpringStatManager.java
{ "start": 800, "end": 3322 }
class ____ { public static final String SYS_PROP_INSTANCES = "druid.spring.springStat"; private static final SpringStatManager instance = new SpringStatManager(); private Set<Object> springStatSet; public static SpringStatManager getInstance() { return instance; } public Set<Object> getSpringStatSet() { if (springStatSet == null) { if (DruidDataSourceStatManager.isRegisterToSystemProperty()) { springStatSet = getSpringStatSetFromSysProperty(); } else { springStatSet = new CopyOnWriteArraySet<Object>(); } } return springStatSet; } public void addSpringStat(Object springStat) { getSpringStatSet().add(springStat); } @SuppressWarnings("unchecked") static Set<Object> getSpringStatSetFromSysProperty() { Properties properties = System.getProperties(); Set<Object> webAppStats = (Set<Object>) properties.get(SYS_PROP_INSTANCES); if (webAppStats == null) { synchronized (properties) { webAppStats = (Set<Object>) properties.get(SYS_PROP_INSTANCES); if (webAppStats == null) { webAppStats = new CopyOnWriteArraySet<Object>(); properties.put(SYS_PROP_INSTANCES, webAppStats); } } } return webAppStats; } public List<Map<String, Object>> getMethodStatData() { Set<Object> stats = getSpringStatSet(); List<Map<String, Object>> allMethodStatDataList = new ArrayList<Map<String, Object>>(); for (Object stat : stats) { List<Map<String, Object>> methodStatDataList = SpringStatUtils.getMethodStatDataList(stat); if (methodStatDataList != null) { allMethodStatDataList.addAll(methodStatDataList); } } return allMethodStatDataList; } public Map<String, Object> getMethodStatData(String clazz, String method) { Set<Object> stats = getSpringStatSet(); for (Object stat : stats) { Map<String, Object> statData = SpringStatUtils.getMethodStatData(stat, clazz, method); if (statData != null) { return statData; } } return null; } public void resetStat() { Set<Object> stats = getSpringStatSet(); for (Object stat : stats) { SpringStatUtils.reset(stat); } } }
SpringStatManager
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-httpfs/src/main/java/org/apache/hadoop/lib/server/Server.java
{ "start": 3995, "end": 18369 }
enum ____ { UNDEF(false, false), BOOTING(false, true), HALTED(true, true), ADMIN(true, true), NORMAL(true, true), SHUTTING_DOWN(false, true), SHUTDOWN(false, false); private boolean settable; private boolean operational; /** * Status constructor. * * @param settable indicates if the status is settable. * @param operational indicates if the server is operational * when in this status. */ private Status(boolean settable, boolean operational) { this.settable = settable; this.operational = operational; } /** * Returns if this server status is operational. * * @return if this server status is operational. */ public boolean isOperational() { return operational; } } /** * Name of the log4j configuration file the Server will load from the * classpath if the <code>#SERVER#-log4j.properties</code> is not defined * in the server configuration directory. */ public static final String DEFAULT_LOG4J_PROPERTIES = "default-log4j.properties"; private Status status; private String name; private String homeDir; private String configDir; private String logDir; private String tempDir; private Configuration config; private Map<Class, Service> services = new LinkedHashMap<Class, Service>(); /** * Creates a server instance. * <p> * The config, log and temp directories are all under the specified home directory. * * @param name server name. * @param homeDir server home directory. */ public Server(String name, String homeDir) { this(name, homeDir, null); } /** * Creates a server instance. * * @param name server name. * @param homeDir server home directory. * @param configDir config directory. * @param logDir log directory. * @param tempDir temp directory. */ public Server(String name, String homeDir, String configDir, String logDir, String tempDir) { this(name, homeDir, configDir, logDir, tempDir, null); } /** * Creates a server instance. * <p> * The config, log and temp directories are all under the specified home directory. * <p> * It uses the provided configuration instead loading it from the config dir. * * @param name server name. * @param homeDir server home directory. * @param config server configuration. */ public Server(String name, String homeDir, Configuration config) { this(name, homeDir, homeDir + "/conf", homeDir + "/log", homeDir + "/temp", config); } /** * Creates a server instance. * <p> * It uses the provided configuration instead loading it from the config dir. * * @param name server name. * @param homeDir server home directory. * @param configDir config directory. * @param logDir log directory. * @param tempDir temp directory. * @param config server configuration. */ public Server(String name, String homeDir, String configDir, String logDir, String tempDir, Configuration config) { this.name = StringUtils.toLowerCase(Check.notEmpty(name, "name").trim()); this.homeDir = Check.notEmpty(homeDir, "homeDir"); this.configDir = Check.notEmpty(configDir, "configDir"); this.logDir = Check.notEmpty(logDir, "logDir"); this.tempDir = Check.notEmpty(tempDir, "tempDir"); checkAbsolutePath(homeDir, "homeDir"); checkAbsolutePath(configDir, "configDir"); checkAbsolutePath(logDir, "logDir"); checkAbsolutePath(tempDir, "tempDir"); if (config != null) { this.config = new Configuration(false); ConfigurationUtils.copy(config, this.config); } status = Status.UNDEF; } /** * Validates that the specified value is an absolute path (starts with '/'). * * @param value value to verify it is an absolute path. * @param name name to use in the exception if the value is not an absolute * path. * * @return the value. * * @throws IllegalArgumentException thrown if the value is not an absolute * path. */ private String checkAbsolutePath(String value, String name) { if (!new File(value).isAbsolute()) { throw new IllegalArgumentException( MessageFormat.format("[{0}] must be an absolute path [{1}]", name, value)); } return value; } /** * Returns the current server status. * * @return the current server status. */ public Status getStatus() { return status; } /** * Sets a new server status. * <p> * The status must be settable. * <p> * All services will be notified o the status change via the * {@link Service#serverStatusChange(Server.Status, Server.Status)} method. If a service * throws an exception during the notification, the server will be destroyed. * * @param status status to set. * * @throws ServerException thrown if the service has been destroy because of * a failed notification to a service. */ public void setStatus(Status status) throws ServerException { Check.notNull(status, "status"); if (status.settable) { if (status != this.status) { Status oldStatus = this.status; this.status = status; for (Service service : services.values()) { try { service.serverStatusChange(oldStatus, status); } catch (Exception ex) { log.error("Service [{}] exception during status change to [{}] -server shutting down-, {}", new Object[]{service.getInterface().getSimpleName(), status, ex.getMessage(), ex}); destroy(); throw new ServerException(ServerException.ERROR.S11, service.getInterface().getSimpleName(), status, ex.getMessage(), ex); } } } } else { throw new IllegalArgumentException("Status [" + status + " is not settable"); } } /** * Verifies the server is operational. * * @throws IllegalStateException thrown if the server is not operational. */ protected void ensureOperational() { if (!getStatus().isOperational()) { throw new IllegalStateException("Server is not running"); } } /** * Convenience method that returns a resource as inputstream from the * classpath. * <p> * It first attempts to use the Thread's context classloader and if not * set it uses the <code>ClassUtils</code> classloader. * * @param name resource to retrieve. * * @return inputstream with the resource, NULL if the resource does not * exist. */ static InputStream getResource(String name) { Check.notEmpty(name, "name"); ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = Server.class.getClassLoader(); } return cl.getResourceAsStream(name); } /** * Initializes the Server. * <p> * The initialization steps are: * <ul> * <li>It verifies the service home and temp directories exist</li> * <li>Loads the Server <code>#SERVER#-default.xml</code> * configuration file from the classpath</li> * <li>Initializes log4j logging. If the * <code>#SERVER#-log4j.properties</code> file does not exist in the config * directory it load <code>default-log4j.properties</code> from the classpath * </li> * <li>Loads the <code>#SERVER#-site.xml</code> file from the server config * directory and merges it with the default configuration.</li> * <li>Loads the services</li> * <li>Initializes the services</li> * <li>Post-initializes the services</li> * <li>Sets the server startup status</li> * </ul> * * @throws ServerException thrown if the server could not be initialized. */ public void init() throws ServerException { if (status != Status.UNDEF) { throw new IllegalStateException("Server already initialized"); } status = Status.BOOTING; verifyDir(homeDir); verifyDir(tempDir); Properties serverInfo = new Properties(); try { InputStream is = getResource(name + ".properties"); serverInfo.load(is); is.close(); } catch (IOException ex) { throw new RuntimeException("Could not load server information file: " + name + ".properties"); } initLog(); log.info("++++++++++++++++++++++++++++++++++++++++++++++++++++++"); log.info("Server [{}] starting", name); log.info(" Built information:"); log.info(" Version : {}", serverInfo.getProperty(name + ".version", "undef")); log.info(" Source Repository : {}", serverInfo.getProperty(name + ".source.repository", "undef")); log.info(" Source Revision : {}", serverInfo.getProperty(name + ".source.revision", "undef")); log.info(" Built by : {}", serverInfo.getProperty(name + ".build.username", "undef")); log.info(" Built timestamp : {}", serverInfo.getProperty(name + ".build.timestamp", "undef")); log.info(" Runtime information:"); log.info(" Home dir: {}", homeDir); log.info(" Config dir: {}", (config == null) ? configDir : "-"); log.info(" Log dir: {}", logDir); log.info(" Temp dir: {}", tempDir); initConfig(); log.debug("Loading services"); List<Service> list = loadServices(); try { log.debug("Initializing services"); initServices(list); log.info("Services initialized"); } catch (ServerException ex) { log.error("Services initialization failure, destroying initialized services"); destroyServices(); throw ex; } Status status = Status.valueOf(getConfig().get(getPrefixedName(CONF_STARTUP_STATUS), Status.NORMAL.toString())); setStatus(status); log.info("Server [{}] started!, status [{}]", name, status); } /** * Verifies the specified directory exists. * * @param dir directory to verify it exists. * * @throws ServerException thrown if the directory does not exist or it the * path it is not a directory. */ private void verifyDir(String dir) throws ServerException { File file = new File(dir); if (!file.exists()) { throw new ServerException(ServerException.ERROR.S01, dir); } if (!file.isDirectory()) { throw new ServerException(ServerException.ERROR.S02, dir); } } /** * Initializes Log4j logging. * * @throws ServerException thrown if Log4j could not be initialized. */ protected void initLog() throws ServerException { verifyDir(logDir); LogManager.resetConfiguration(); File log4jFile = new File(configDir, name + "-log4j.properties"); if (log4jFile.exists()) { PropertyConfigurator.configureAndWatch(log4jFile.toString(), 10 * 1000); //every 10 secs log = LoggerFactory.getLogger(Server.class); } else { Properties props = new Properties(); try { InputStream is = getResource(DEFAULT_LOG4J_PROPERTIES); try { props.load(is); } finally { is.close(); } } catch (IOException ex) { throw new ServerException(ServerException.ERROR.S03, DEFAULT_LOG4J_PROPERTIES, ex.getMessage(), ex); } PropertyConfigurator.configure(props); log = LoggerFactory.getLogger(Server.class); log.warn("Log4j [{}] configuration file not found, using default configuration from classpath", log4jFile); } } /** * Loads and inializes the server configuration. * * @throws ServerException thrown if the configuration could not be loaded/initialized. */ protected void initConfig() throws ServerException { verifyDir(configDir); File file = new File(configDir); Configuration defaultConf; String defaultConfig = name + "-default.xml"; ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = classLoader.getResourceAsStream(defaultConfig); if (inputStream == null) { log.warn("Default configuration file not available in classpath [{}]", defaultConfig); defaultConf = new Configuration(false); } else { try { defaultConf = new Configuration(false); ConfigurationUtils.load(defaultConf, inputStream); } catch (Exception ex) { throw new ServerException(ServerException.ERROR.S03, defaultConfig, ex.getMessage(), ex); } } if (config == null) { Configuration siteConf; File siteFile = new File(file, name + "-site.xml"); if (!siteFile.exists()) { log.warn("Site configuration file [{}] not found in config directory", siteFile); siteConf = new Configuration(false); } else { if (!siteFile.isFile()) { throw new ServerException(ServerException.ERROR.S05, siteFile.getAbsolutePath()); } try { log.debug("Loading site configuration from [{}]", siteFile); inputStream = Files.newInputStream(siteFile.toPath()); siteConf = new Configuration(false); ConfigurationUtils.load(siteConf, inputStream); } catch (IOException ex) { throw new ServerException(ServerException.ERROR.S06, siteFile, ex.getMessage(), ex); } } config = new Configuration(false); ConfigurationUtils.copy(siteConf, config); } ConfigurationUtils.injectDefaults(defaultConf, config); ConfigRedactor redactor = new ConfigRedactor(config); for (String name : System.getProperties().stringPropertyNames()) { String value = System.getProperty(name); if (name.startsWith(getPrefix() + ".")) { config.set(name, value); String redacted = redactor.redact(name, value); log.info("System property sets {}: {}", name, redacted); } } log.debug("Loaded Configuration:"); log.debug("------------------------------------------------------"); for (Map.Entry<String, String> entry : config) { String name = entry.getKey(); String value = config.get(entry.getKey()); String redacted = redactor.redact(name, value); log.debug(" {}: {}", entry.getKey(), redacted); } log.debug("------------------------------------------------------"); } /** * Loads the specified services. * * @param classes services classes to load. * @param list list of loaded service in order of appearance in the * configuration. * * @throws ServerException thrown if a service
Status
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/simplelistparameter/Car.java
{ "start": 739, "end": 1052 }
class ____ { private String name; private List<String> doors; public String getName() { return name; } public void setName(String name) { this.name = name; } public List<String> getDoors() { return doors; } public void setDoors(List<String> doors) { this.doors = doors; } }
Car
java
apache__hadoop
hadoop-common-project/hadoop-common/src/test/java/org/apache/hadoop/http/TestAuthenticationSessionCookie.java
{ "start": 2568, "end": 2857 }
class ____ extends FilterInitializer { @Override public void initFilter(FilterContainer container, Configuration conf) { container.addFilter("DummyAuth", DummyAuthenticationFilter.class .getName(), new HashMap<>()); } } public static
DummyFilterInitializer
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/analysis/PreBuiltCacheFactory.java
{ "start": 691, "end": 1227 }
class ____ { /** * The strategy of caching the analyzer * * ONE Exactly one version is stored. Useful for analyzers which do not store version information * LUCENE Exactly one version for each lucene version is stored. Useful to prevent different analyzers with the same version * INDEX Exactly one version for each index version is stored. Useful if you change an analyzer between index changes, * when the lucene version does not change */ public
PreBuiltCacheFactory
java
quarkusio__quarkus
independent-projects/tools/devtools-common/src/main/java/io/quarkus/devtools/codestarts/CodestartResourceLoader.java
{ "start": 250, "end": 1555 }
class ____ implements CodestartPathLoader { private ResourceLoader resourceLoader; private CodestartResourceLoader(ResourceLoader resourceLoader) { this.resourceLoader = resourceLoader; } public static Map<String, Codestart> loadCodestartsFromResources(List<ResourceLoader> codestartResourceLoaders, String relativePath) throws IOException { final Map<String, Codestart> codestarts = new HashMap<>(); for (ResourceLoader codestartResourceLoader : codestartResourceLoaders) { final CodestartPathLoader pathLoader = toCodestartPathLoader(codestartResourceLoader); final Collection<Codestart> loadedCodestarts = CodestartCatalogLoader.loadCodestarts(pathLoader, relativePath); for (Codestart codestart : loadedCodestarts) { codestarts.put(codestart.getName(), codestart); } } return codestarts; } public static CodestartPathLoader toCodestartPathLoader(ResourceLoader resourceLoader) { return new CodestartResourceLoader(resourceLoader); } @Override public <T> T loadResourceAsPath(String name, PathConsumer<T> consumer) throws IOException { return resourceLoader.loadResourceAsPath(name, consumer::consume); } }
CodestartResourceLoader
java
apache__flink
flink-rpc/flink-rpc-akka/src/main/java/org/apache/flink/runtime/rpc/pekko/PekkoRpcServiceUtils.java
{ "start": 15676, "end": 15758 }
class ____ not meant to be instantiated. */ private PekkoRpcServiceUtils() {} }
is
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/GeoArgs.java
{ "start": 568, "end": 888 }
class ____ implements CompositeArgument { private boolean withdistance; private boolean withcoordinates; private boolean withhash; private Long count; private boolean any; private Sort sort = Sort.none; /** * Builder entry points for {@link GeoArgs}. */ public static
GeoArgs
java
spring-projects__spring-security
config/src/test/java/org/springframework/security/config/annotation/web/configuration/OAuth2ClientConfigurationTests.java
{ "start": 13060, "end": 13381 }
class ____ { @GetMapping("/authorized-client") String authorizedClient( @RegisteredOAuth2AuthorizedClient("client1") OAuth2AuthorizedClient authorizedClient) { return (authorizedClient != null) ? "resolved" : "not-resolved"; } } } @Configuration @EnableWebMvc @EnableWebSecurity static
Controller
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/action/admin/indices/rollover/RolloverIT.java
{ "start": 3174, "end": 48924 }
class ____ extends ESIntegTestCase { @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singleton(InternalSettingsPlugin.class); } public void testRolloverOnEmptyIndex() throws Exception { Alias testAlias = new Alias("test_alias"); boolean explicitWriteIndex = randomBoolean(); if (explicitWriteIndex) { testAlias.writeIndex(true); } assertAcked(prepareCreate("test_index-1").addAlias(testAlias).get()); final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias").get(); assertThat(response.getOldIndex(), equalTo("test_index-1")); assertThat(response.getNewIndex(), equalTo("test_index-000002")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); final ClusterState state = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); final IndexMetadata oldIndex = state.metadata().getProject().index("test_index-1"); if (explicitWriteIndex) { assertTrue(oldIndex.getAliases().containsKey("test_alias")); assertFalse(oldIndex.getAliases().get("test_alias").writeIndex()); } else { assertFalse(oldIndex.getAliases().containsKey("test_alias")); } final IndexMetadata newIndex = state.metadata().getProject().index("test_index-000002"); assertTrue(newIndex.getAliases().containsKey("test_alias")); } public void testRollover() throws Exception { long beforeTime = client().threadPool().absoluteTimeInMillis() - 1000L; assertAcked(prepareCreate("test_index-2").addAlias(new Alias("test_alias")).get()); indexDoc("test_index-2", "1", "field", "value"); flush("test_index-2"); final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias").get(); assertThat(response.getOldIndex(), equalTo("test_index-2")); assertThat(response.getNewIndex(), equalTo("test_index-000003")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); final ClusterState state = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); final IndexMetadata oldIndex = state.metadata().getProject().index("test_index-2"); assertFalse(oldIndex.getAliases().containsKey("test_alias")); final IndexMetadata newIndex = state.metadata().getProject().index("test_index-000003"); assertTrue(newIndex.getAliases().containsKey("test_alias")); assertThat(oldIndex.getRolloverInfos().size(), equalTo(1)); assertThat(oldIndex.getRolloverInfos().get("test_alias").getAlias(), equalTo("test_alias")); assertThat(oldIndex.getRolloverInfos().get("test_alias").getMetConditions(), is(empty())); assertThat( oldIndex.getRolloverInfos().get("test_alias").getTime(), is(both(greaterThanOrEqualTo(beforeTime)).and(lessThanOrEqualTo(client().threadPool().absoluteTimeInMillis() + 1000L))) ); } public void testInfiniteMasterNodeTimeout() { assertAcked(prepareCreate("test_index-2").addAlias(new Alias("test_alias")).get()); indexDoc("test_index-2", "1", "field", "value"); flush("test_index-2"); final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias").setMasterNodeTimeout(TimeValue.MINUS_ONE).get(); assertTrue(response.isShardsAcknowledged()); } public void testRolloverWithExplicitWriteIndex() throws Exception { long beforeTime = client().threadPool().absoluteTimeInMillis() - 1000L; assertAcked(prepareCreate("test_index-2").addAlias(new Alias("test_alias").writeIndex(true)).get()); indexDoc("test_index-2", "1", "field", "value"); flush("test_index-2"); final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias").get(); assertThat(response.getOldIndex(), equalTo("test_index-2")); assertThat(response.getNewIndex(), equalTo("test_index-000003")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); final ClusterState state = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); final IndexMetadata oldIndex = state.metadata().getProject().index("test_index-2"); assertTrue(oldIndex.getAliases().containsKey("test_alias")); assertFalse(oldIndex.getAliases().get("test_alias").writeIndex()); final IndexMetadata newIndex = state.metadata().getProject().index("test_index-000003"); assertTrue(newIndex.getAliases().containsKey("test_alias")); assertTrue(newIndex.getAliases().get("test_alias").writeIndex()); assertThat(oldIndex.getRolloverInfos().size(), equalTo(1)); assertThat(oldIndex.getRolloverInfos().get("test_alias").getAlias(), equalTo("test_alias")); assertThat(oldIndex.getRolloverInfos().get("test_alias").getMetConditions(), is(empty())); assertThat( oldIndex.getRolloverInfos().get("test_alias").getTime(), is(both(greaterThanOrEqualTo(beforeTime)).and(lessThanOrEqualTo(client().threadPool().absoluteTimeInMillis() + 1000L))) ); } public void testRolloverWithNoWriteIndex() { Boolean firstIsWriteIndex = randomFrom(false, null); assertAcked(prepareCreate("index1").addAlias(new Alias("alias").writeIndex(firstIsWriteIndex)).get()); if (firstIsWriteIndex == null) { assertAcked(prepareCreate("index2").addAlias(new Alias("alias").writeIndex(randomFrom(false, null))).get()); } IllegalArgumentException exception = expectThrows( IllegalArgumentException.class, indicesAdmin().prepareRolloverIndex("alias").dryRun(randomBoolean()) ); assertThat(exception.getMessage(), equalTo("rollover target [alias] does not point to a write index")); } public void testRolloverWithIndexSettings() throws Exception { Alias testAlias = new Alias("test_alias"); boolean explicitWriteIndex = randomBoolean(); if (explicitWriteIndex) { testAlias.writeIndex(true); } assertAcked(prepareCreate("test_index-2").addAlias(testAlias).get()); indexDoc("test_index-2", "1", "field", "value"); flush("test_index-2"); final Settings settings = indexSettings(1, 0).build(); final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .settings(settings) .alias(new Alias("extra_alias")) .get(); assertThat(response.getOldIndex(), equalTo("test_index-2")); assertThat(response.getNewIndex(), equalTo("test_index-000003")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); final ClusterState state = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); final IndexMetadata oldIndex = state.metadata().getProject().index("test_index-2"); final IndexMetadata newIndex = state.metadata().getProject().index("test_index-000003"); assertThat(newIndex.getNumberOfShards(), equalTo(1)); assertThat(newIndex.getNumberOfReplicas(), equalTo(0)); assertTrue(newIndex.getAliases().containsKey("test_alias")); assertTrue(newIndex.getAliases().containsKey("extra_alias")); if (explicitWriteIndex) { assertFalse(oldIndex.getAliases().get("test_alias").writeIndex()); assertTrue(newIndex.getAliases().get("test_alias").writeIndex()); } else { assertFalse(oldIndex.getAliases().containsKey("test_alias")); } } public void testRolloverWithIndexSettingsWithoutPrefix() throws Exception { Alias testAlias = new Alias("test_alias"); boolean explicitWriteIndex = randomBoolean(); if (explicitWriteIndex) { testAlias.writeIndex(true); } assertAcked(prepareCreate("test_index-2").addAlias(testAlias).get()); indexDoc("test_index-2", "1", "field", "value"); flush("test_index-2"); final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .settings(indexSettings(1, 0).build()) .alias(new Alias("extra_alias")) .get(); assertThat(response.getOldIndex(), equalTo("test_index-2")); assertThat(response.getNewIndex(), equalTo("test_index-000003")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); final ClusterState state = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); final IndexMetadata oldIndex = state.metadata().getProject().index("test_index-2"); final IndexMetadata newIndex = state.metadata().getProject().index("test_index-000003"); assertThat(newIndex.getNumberOfShards(), equalTo(1)); assertThat(newIndex.getNumberOfReplicas(), equalTo(0)); assertTrue(newIndex.getAliases().containsKey("test_alias")); assertTrue(newIndex.getAliases().containsKey("extra_alias")); if (explicitWriteIndex) { assertFalse(oldIndex.getAliases().get("test_alias").writeIndex()); assertTrue(newIndex.getAliases().get("test_alias").writeIndex()); } else { assertFalse(oldIndex.getAliases().containsKey("test_alias")); } } public void testRolloverDryRun() throws Exception { if (randomBoolean()) { PutIndexTemplateRequestBuilder putTemplate = indicesAdmin().preparePutTemplate("test_index") .setPatterns(List.of("test_index-*")) .setOrder(-1) .setSettings(Settings.builder().put(AutoExpandReplicas.SETTING.getKey(), "0-all")); assertAcked(putTemplate.get()); } assertAcked(prepareCreate("test_index-1").addAlias(new Alias("test_alias")).get()); indexDoc("test_index-1", "1", "field", "value"); flush("test_index-1"); ensureGreen(); Logger allocationServiceLogger = LogManager.getLogger(AllocationService.class); final RolloverResponse response; try (var mockLog = MockLog.capture(AllocationService.class)) { mockLog.addExpectation( new MockLog.UnseenEventExpectation( "no related message logged on dry run", AllocationService.class.getName(), Level.INFO, "*test_index*" ) ); response = indicesAdmin().prepareRolloverIndex("test_alias").dryRun(true).get(); mockLog.assertAllExpectationsMatched(); } assertThat(response.getOldIndex(), equalTo("test_index-1")); assertThat(response.getNewIndex(), equalTo("test_index-000002")); assertThat(response.isDryRun(), equalTo(true)); assertThat(response.isRolledOver(), equalTo(false)); assertThat(response.getConditionStatus().size(), equalTo(0)); final ClusterState state = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); final IndexMetadata oldIndex = state.metadata().getProject().index("test_index-1"); assertTrue(oldIndex.getAliases().containsKey("test_alias")); final IndexMetadata newIndex = state.metadata().getProject().index("test_index-000002"); assertNull(newIndex); } public void testRolloverLazy() throws Exception { if (randomBoolean()) { PutIndexTemplateRequestBuilder putTemplate = indicesAdmin().preparePutTemplate("test_index") .setPatterns(List.of("test_index-*")) .setOrder(-1) .setSettings(Settings.builder().put(AutoExpandReplicas.SETTING.getKey(), "0-all")); assertAcked(putTemplate.get()); } assertAcked(prepareCreate("test_index-1").addAlias(new Alias("test_alias")).get()); indexDoc("test_index-1", "1", "field", "value"); flush("test_index-1"); ensureGreen(); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> { RolloverConditions.Builder rolloverConditionsBuilder = RolloverConditions.newBuilder(); if (randomBoolean()) { rolloverConditionsBuilder.addMaxIndexDocsCondition(1L); } indicesAdmin().prepareRolloverIndex("test_alias") .dryRun(randomBoolean()) .lazy(true) .setConditions(rolloverConditionsBuilder) .get(); }); assertThat(exception.getMessage(), containsString("can be applied only on a data stream")); } public void testRolloverConditionsNotMet() throws Exception { boolean explicitWriteIndex = randomBoolean(); Alias testAlias = new Alias("test_alias"); if (explicitWriteIndex) { testAlias.writeIndex(true); } assertAcked(prepareCreate("test_index-0").addAlias(testAlias).get()); indexDoc("test_index-0", "1", "field", "value"); flush("test_index-0"); final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .setConditions( RolloverConditions.newBuilder() .addMaxIndexSizeCondition(ByteSizeValue.of(10, ByteSizeUnit.MB)) .addMaxIndexAgeCondition(TimeValue.timeValueHours(4)) ) .get(); assertThat(response.getOldIndex(), equalTo("test_index-0")); assertThat(response.getNewIndex(), equalTo("test_index-000001")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(false)); assertThat(response.getConditionStatus().size(), equalTo(2)); assertThat(response.getConditionStatus().values(), everyItem(is(false))); Set<String> conditions = response.getConditionStatus().keySet(); assertThat( conditions, containsInAnyOrder( new MaxSizeCondition(ByteSizeValue.of(10, ByteSizeUnit.MB)).toString(), new MaxAgeCondition(TimeValue.timeValueHours(4)).toString() ) ); final ClusterState state = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); final IndexMetadata oldIndex = state.metadata().getProject().index("test_index-0"); assertTrue(oldIndex.getAliases().containsKey("test_alias")); if (explicitWriteIndex) { assertTrue(oldIndex.getAliases().get("test_alias").writeIndex()); } else { assertNull(oldIndex.getAliases().get("test_alias").writeIndex()); } final IndexMetadata newIndex = state.metadata().getProject().index("test_index-000001"); assertNull(newIndex); } public void testRolloverWithNewIndexName() throws Exception { Alias testAlias = new Alias("test_alias"); boolean explicitWriteIndex = randomBoolean(); if (explicitWriteIndex) { testAlias.writeIndex(true); } assertAcked(prepareCreate("test_index").addAlias(testAlias).get()); indexDoc("test_index", "1", "field", "value"); flush("test_index"); final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias").setNewIndexName("test_new_index").get(); assertThat(response.getOldIndex(), equalTo("test_index")); assertThat(response.getNewIndex(), equalTo("test_new_index")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); final ClusterState state = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); final IndexMetadata oldIndex = state.metadata().getProject().index("test_index"); final IndexMetadata newIndex = state.metadata().getProject().index("test_new_index"); assertTrue(newIndex.getAliases().containsKey("test_alias")); if (explicitWriteIndex) { assertFalse(oldIndex.getAliases().get("test_alias").writeIndex()); assertTrue(newIndex.getAliases().get("test_alias").writeIndex()); } else { assertFalse(oldIndex.getAliases().containsKey("test_alias")); } } public void testRolloverOnExistingIndex() throws Exception { assertAcked(prepareCreate("test_index-0").addAlias(new Alias("test_alias")).get()); indexDoc("test_index-0", "1", "field", "value"); assertAcked(prepareCreate("test_index-000001").get()); indexDoc("test_index-000001", "1", "field", "value"); flush("test_index-0", "test_index-000001"); try { indicesAdmin().prepareRolloverIndex("test_alias").get(); fail("expected failure due to existing rollover index"); } catch (ResourceAlreadyExistsException e) { assertThat(e.getIndex().getName(), equalTo("test_index-000001")); } } public void testRolloverWithDateMath() { ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC); assumeTrue("only works on the same day", now.plusMinutes(5).getDayOfYear() == now.getDayOfYear()); String index = "test-" + DateFormatter.forPattern("yyyy.MM.dd").format(now) + "-1"; String dateMathExp = "<test-{now/d}-1>"; assertAcked(prepareCreate(dateMathExp).addAlias(new Alias("test_alias")).get()); ensureGreen(index); // now we modify the provided name such that we can test that the pattern is carried on indicesAdmin().prepareClose(index).get(); updateIndexSettings(Settings.builder().put(IndexMetadata.SETTING_INDEX_PROVIDED_NAME, "<test-{now/M{yyyy.MM}}-1>"), index); indicesAdmin().prepareOpen(index).get(); ensureGreen(index); RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias").get(); assertThat(response.getOldIndex(), equalTo(index)); assertThat(response.getNewIndex(), equalTo("test-" + DateFormatter.forPattern("yyyy.MM").format(now) + "-000002")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); response = indicesAdmin().prepareRolloverIndex("test_alias").get(); assertThat(response.getOldIndex(), equalTo("test-" + DateFormatter.forPattern("yyyy.MM").format(now) + "-000002")); assertThat(response.getNewIndex(), equalTo("test-" + DateFormatter.forPattern("yyyy.MM").format(now) + "-000003")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); GetSettingsResponse getSettingsResponse = indicesAdmin().prepareGetSettings( TEST_REQUEST_TIMEOUT, response.getOldIndex(), response.getNewIndex() ).get(); assertEquals( "<test-{now/M{yyyy.MM}}-000002>", getSettingsResponse.getSetting(response.getOldIndex(), IndexMetadata.SETTING_INDEX_PROVIDED_NAME) ); assertEquals( "<test-{now/M{yyyy.MM}}-000003>", getSettingsResponse.getSetting(response.getNewIndex(), IndexMetadata.SETTING_INDEX_PROVIDED_NAME) ); response = indicesAdmin().prepareRolloverIndex("test_alias").setNewIndexName("<test-{now/d}-000004>").get(); assertThat(response.getOldIndex(), equalTo("test-" + DateFormatter.forPattern("yyyy.MM").format(now) + "-000003")); assertThat(response.getNewIndex(), equalTo("test-" + DateFormatter.forPattern("yyyy.MM.dd").format(now) + "-000004")); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); } public void testRolloverMaxSize() throws Exception { assertAcked(prepareCreate("test-1").addAlias(new Alias("test_alias")).get()); int numDocs = randomIntBetween(10, 20); for (int i = 0; i < numDocs; i++) { indexDoc("test-1", Integer.toString(i), "field", "foo-" + i); } flush("test-1"); refresh("test_alias"); // A large max_size { final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .setConditions( RolloverConditions.newBuilder() .addMaxIndexSizeCondition(ByteSizeValue.of(randomIntBetween(100, 50 * 1024), ByteSizeUnit.MB)) ) .get(); assertThat(response.getOldIndex(), equalTo("test-1")); assertThat(response.getNewIndex(), equalTo("test-000002")); assertThat("No rollover with a large max_size condition", response.isRolledOver(), equalTo(false)); final IndexMetadata oldIndex = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT) .get() .getState() .metadata() .getProject() .index("test-1"); assertThat(oldIndex.getRolloverInfos().size(), equalTo(0)); } // A small max_size { ByteSizeValue maxSizeValue = ByteSizeValue.of(randomIntBetween(1, 20), ByteSizeUnit.BYTES); long beforeTime = client().threadPool().absoluteTimeInMillis() - 1000L; final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .setConditions(RolloverConditions.newBuilder().addMaxIndexSizeCondition(maxSizeValue)) .get(); assertThat(response.getOldIndex(), equalTo("test-1")); assertThat(response.getNewIndex(), equalTo("test-000002")); assertThat("Should rollover with a small max_size condition", response.isRolledOver(), equalTo(true)); final IndexMetadata oldIndex = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT) .get() .getState() .metadata() .getProject() .index("test-1"); List<Condition<?>> metConditions = oldIndex.getRolloverInfos().get("test_alias").getMetConditions(); assertThat(metConditions.size(), equalTo(1)); assertThat(metConditions.get(0).toString(), equalTo(new MaxSizeCondition(maxSizeValue).toString())); assertThat( oldIndex.getRolloverInfos().get("test_alias").getTime(), is(both(greaterThanOrEqualTo(beforeTime)).and(lessThanOrEqualTo(client().threadPool().absoluteTimeInMillis() + 1000L))) ); } // An empty index { final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .setConditions( RolloverConditions.newBuilder() .addMaxIndexSizeCondition(ByteSizeValue.of(randomNonNegativeLong(), ByteSizeUnit.BYTES)) .addMinIndexDocsCondition(1L) ) .get(); assertThat(response.getOldIndex(), equalTo("test-000002")); assertThat(response.getNewIndex(), equalTo("test-000003")); assertThat("No rollover with an empty index", response.isRolledOver(), equalTo(false)); final IndexMetadata oldIndex = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT) .get() .getState() .metadata() .getProject() .index("test-000002"); assertThat(oldIndex.getRolloverInfos().size(), equalTo(0)); } } public void testRolloverMaxPrimaryShardSize() throws Exception { assertAcked(prepareCreate("test-1").addAlias(new Alias("test_alias")).get()); int numDocs = randomIntBetween(10, 20); for (int i = 0; i < numDocs; i++) { indexDoc("test-1", Integer.toString(i), "field", "foo-" + i); } flush("test-1"); refresh("test_alias"); // A large max_primary_shard_size { final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .setConditions( RolloverConditions.newBuilder() .addMaxPrimaryShardSizeCondition(ByteSizeValue.of(randomIntBetween(100, 50 * 1024), ByteSizeUnit.MB)) ) .get(); assertThat(response.getOldIndex(), equalTo("test-1")); assertThat(response.getNewIndex(), equalTo("test-000002")); assertThat("No rollover with a large max_primary_shard_size condition", response.isRolledOver(), equalTo(false)); final IndexMetadata oldIndex = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT) .get() .getState() .metadata() .getProject() .index("test-1"); assertThat(oldIndex.getRolloverInfos().size(), equalTo(0)); } // A small max_primary_shard_size { ByteSizeValue maxPrimaryShardSizeCondition = ByteSizeValue.of(randomIntBetween(1, 20), ByteSizeUnit.BYTES); long beforeTime = client().threadPool().absoluteTimeInMillis() - 1000L; final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .setConditions(RolloverConditions.newBuilder().addMaxPrimaryShardSizeCondition(maxPrimaryShardSizeCondition)) .get(); assertThat(response.getOldIndex(), equalTo("test-1")); assertThat(response.getNewIndex(), equalTo("test-000002")); assertThat("Should rollover with a small max_primary_shard_size condition", response.isRolledOver(), equalTo(true)); final IndexMetadata oldIndex = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT) .get() .getState() .metadata() .getProject() .index("test-1"); List<Condition<?>> metConditions = oldIndex.getRolloverInfos().get("test_alias").getMetConditions(); assertThat(metConditions.size(), equalTo(1)); assertThat(metConditions.get(0).toString(), equalTo(new MaxPrimaryShardSizeCondition(maxPrimaryShardSizeCondition).toString())); assertThat( oldIndex.getRolloverInfos().get("test_alias").getTime(), is(both(greaterThanOrEqualTo(beforeTime)).and(lessThanOrEqualTo(client().threadPool().absoluteTimeInMillis() + 1000L))) ); } // An empty index { final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .setConditions( RolloverConditions.newBuilder() .addMaxPrimaryShardSizeCondition(ByteSizeValue.of(randomNonNegativeLong(), ByteSizeUnit.BYTES)) .addMinIndexDocsCondition(1L) ) .get(); assertThat(response.getOldIndex(), equalTo("test-000002")); assertThat(response.getNewIndex(), equalTo("test-000003")); assertThat("No rollover with an empty index", response.isRolledOver(), equalTo(false)); final IndexMetadata oldIndex = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT) .get() .getState() .metadata() .getProject() .index("test-000002"); assertThat(oldIndex.getRolloverInfos().size(), equalTo(0)); } } public void testRolloverMaxPrimaryShardDocs() throws Exception { assertAcked( prepareCreate("test-1").setSettings(Settings.builder().put("index.number_of_shards", 1)).addAlias(new Alias("test_alias")) ); int numDocs = randomIntBetween(10, 20); for (int i = 0; i < numDocs; i++) { indexDoc("test-1", Integer.toString(i), "field", "foo-" + i); } flush("test-1"); refresh("test_alias"); // A large max_primary_shard_docs { final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .setConditions(RolloverConditions.newBuilder().addMaxPrimaryShardDocsCondition(randomLongBetween(21, 30))) .get(); assertThat(response.getOldIndex(), equalTo("test-1")); assertThat(response.getNewIndex(), equalTo("test-000002")); assertThat("No rollover with a large max_primary_shard_docs condition", response.isRolledOver(), equalTo(false)); final IndexMetadata oldIndex = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT) .get() .getState() .metadata() .getProject() .index("test-1"); assertThat(oldIndex.getRolloverInfos().size(), equalTo(0)); } // A small max_primary_shard_docs { MaxPrimaryShardDocsCondition maxPrimaryShardDocsCondition = new MaxPrimaryShardDocsCondition(randomLongBetween(1, 9)); long beforeTime = client().threadPool().absoluteTimeInMillis() - 1000L; final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .setConditions(RolloverConditions.newBuilder().addMaxPrimaryShardDocsCondition(maxPrimaryShardDocsCondition.value)) .get(); assertThat(response.getOldIndex(), equalTo("test-1")); assertThat(response.getNewIndex(), equalTo("test-000002")); assertThat("Should rollover with a small max_primary_shard_docs condition", response.isRolledOver(), equalTo(true)); final IndexMetadata oldIndex = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT) .get() .getState() .metadata() .getProject() .index("test-1"); List<Condition<?>> metConditions = oldIndex.getRolloverInfos().get("test_alias").getMetConditions(); assertThat(metConditions.size(), equalTo(1)); assertThat( metConditions.get(0).toString(), equalTo(new MaxPrimaryShardDocsCondition(maxPrimaryShardDocsCondition.value).toString()) ); assertThat( oldIndex.getRolloverInfos().get("test_alias").getTime(), is(both(greaterThanOrEqualTo(beforeTime)).and(lessThanOrEqualTo(client().threadPool().absoluteTimeInMillis() + 1000L))) ); } // An empty index { final RolloverResponse response = indicesAdmin().prepareRolloverIndex("test_alias") .setConditions( RolloverConditions.newBuilder().addMaxPrimaryShardDocsCondition(randomNonNegativeLong()).addMinIndexDocsCondition(1L) ) .get(); assertThat(response.getOldIndex(), equalTo("test-000002")); assertThat(response.getNewIndex(), equalTo("test-000003")); assertThat("No rollover with an empty index", response.isRolledOver(), equalTo(false)); final IndexMetadata oldIndex = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT) .get() .getState() .metadata() .getProject() .index("test-000002"); assertThat(oldIndex.getRolloverInfos().size(), equalTo(0)); } } public void testRejectIfAliasFoundInTemplate() throws Exception { indicesAdmin().preparePutTemplate("logs").setPatterns(Collections.singletonList("logs-*")).addAlias(new Alias("logs-write")).get(); assertAcked(indicesAdmin().prepareCreate("logs-000001").get()); ensureYellow("logs-write"); final IllegalArgumentException error = expectThrows( IllegalArgumentException.class, indicesAdmin().prepareRolloverIndex("logs-write") ); assertThat( error.getMessage(), equalTo( "Rollover alias [logs-write] can point to multiple indices, found duplicated alias [[logs-write]] in index template [logs]" ) ); } public void testRolloverWithClosedIndexInAlias() { final String aliasName = "alias"; final String openNonwriteIndex = "open-index-nonwrite"; final String closedIndex = "closed-index-nonwrite"; final String writeIndexPrefix = "write-index-"; assertAcked( prepareCreate(openNonwriteIndex).addAlias(new Alias(aliasName)), prepareCreate(closedIndex).addAlias(new Alias(aliasName)), prepareCreate(writeIndexPrefix + "000001").addAlias(new Alias(aliasName).writeIndex(true)) ); ensureGreen(); index(closedIndex, null, "{\"foo\": \"bar\"}"); index(aliasName, null, "{\"foo\": \"bar\"}"); index(aliasName, null, "{\"foo\": \"bar\"}"); refresh(aliasName); assertAcked(indicesAdmin().prepareClose(closedIndex).setTimeout(TimeValue.timeValueSeconds(60)).get()); RolloverResponse rolloverResponse = indicesAdmin().prepareRolloverIndex(aliasName) .setConditions(RolloverConditions.newBuilder().addMaxIndexDocsCondition(1L)) .get(); assertTrue(rolloverResponse.isRolledOver()); assertEquals(writeIndexPrefix + "000001", rolloverResponse.getOldIndex()); assertEquals(writeIndexPrefix + "000002", rolloverResponse.getNewIndex()); } public void testRolloverWithClosedWriteIndex() throws Exception { final String aliasName = "alias"; final String openNonwriteIndex = "open-index-nonwrite"; final String closedIndex = "closed-index-nonwrite"; final String writeIndexPrefix = "write-index-"; assertAcked( prepareCreate(openNonwriteIndex).addAlias(new Alias(aliasName)), prepareCreate(closedIndex).addAlias(new Alias(aliasName)), prepareCreate(writeIndexPrefix + "000001").addAlias(new Alias(aliasName).writeIndex(true)) ); ensureGreen(openNonwriteIndex, closedIndex, writeIndexPrefix + "000001"); index(closedIndex, null, "{\"foo\": \"bar\"}"); index(aliasName, null, "{\"foo\": \"bar\"}"); index(aliasName, null, "{\"foo\": \"bar\"}"); refresh(aliasName); assertAcked(indicesAdmin().prepareClose(closedIndex, writeIndexPrefix + "000001").get()); ensureGreen(aliasName); RolloverResponse rolloverResponse = indicesAdmin().prepareRolloverIndex(aliasName) .setConditions(RolloverConditions.newBuilder().addMaxIndexDocsCondition(1L)) .get(); assertTrue(rolloverResponse.isRolledOver()); assertEquals(writeIndexPrefix + "000001", rolloverResponse.getOldIndex()); assertEquals(writeIndexPrefix + "000002", rolloverResponse.getNewIndex()); } public void testRolloverWithHiddenAliasesAndExplicitWriteIndex() { long beforeTime = client().threadPool().absoluteTimeInMillis() - 1000L; final String indexNamePrefix = "test_index_hidden-"; final String firstIndexName = indexNamePrefix + "000001"; final String secondIndexName = indexNamePrefix + "000002"; final String aliasName = "test_alias"; assertAcked(prepareCreate(firstIndexName).addAlias(new Alias(aliasName).writeIndex(true).isHidden(true)).get()); indexDoc(aliasName, "1", "field", "value"); refresh(); final RolloverResponse response = indicesAdmin().prepareRolloverIndex(aliasName).get(); assertThat(response.getOldIndex(), equalTo(firstIndexName)); assertThat(response.getNewIndex(), equalTo(secondIndexName)); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); final ClusterState state = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); final IndexMetadata oldIndex = state.metadata().getProject().index(firstIndexName); assertTrue(oldIndex.getAliases().containsKey(aliasName)); assertTrue(oldIndex.getAliases().get(aliasName).isHidden()); assertFalse(oldIndex.getAliases().get(aliasName).writeIndex()); final IndexMetadata newIndex = state.metadata().getProject().index(secondIndexName); assertTrue(newIndex.getAliases().containsKey(aliasName)); assertTrue(newIndex.getAliases().get(aliasName).isHidden()); assertTrue(newIndex.getAliases().get(aliasName).writeIndex()); assertThat(oldIndex.getRolloverInfos().size(), equalTo(1)); assertThat(oldIndex.getRolloverInfos().get(aliasName).getAlias(), equalTo(aliasName)); assertThat(oldIndex.getRolloverInfos().get(aliasName).getMetConditions(), is(empty())); assertThat( oldIndex.getRolloverInfos().get(aliasName).getTime(), is(both(greaterThanOrEqualTo(beforeTime)).and(lessThanOrEqualTo(client().threadPool().absoluteTimeInMillis() + 1000L))) ); } public void testRolloverWithHiddenAliasesAndImplicitWriteIndex() { long beforeTime = client().threadPool().absoluteTimeInMillis() - 1000L; final String indexNamePrefix = "test_index_hidden-"; final String firstIndexName = indexNamePrefix + "000001"; final String secondIndexName = indexNamePrefix + "000002"; final String aliasName = "test_alias"; assertAcked(prepareCreate(firstIndexName).addAlias(new Alias(aliasName).isHidden(true)).get()); indexDoc(aliasName, "1", "field", "value"); refresh(); final RolloverResponse response = indicesAdmin().prepareRolloverIndex(aliasName).get(); assertThat(response.getOldIndex(), equalTo(firstIndexName)); assertThat(response.getNewIndex(), equalTo(secondIndexName)); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); assertThat(response.getConditionStatus().size(), equalTo(0)); final ClusterState state = clusterAdmin().prepareState(TEST_REQUEST_TIMEOUT).get().getState(); final IndexMetadata oldIndex = state.metadata().getProject().index(firstIndexName); assertFalse(oldIndex.getAliases().containsKey(aliasName)); final IndexMetadata newIndex = state.metadata().getProject().index(secondIndexName); assertTrue(newIndex.getAliases().containsKey(aliasName)); assertTrue(newIndex.getAliases().get(aliasName).isHidden()); assertThat(newIndex.getAliases().get(aliasName).writeIndex(), nullValue()); assertThat(oldIndex.getRolloverInfos().size(), equalTo(1)); assertThat(oldIndex.getRolloverInfos().get(aliasName).getAlias(), equalTo(aliasName)); assertThat(oldIndex.getRolloverInfos().get(aliasName).getMetConditions(), is(empty())); assertThat( oldIndex.getRolloverInfos().get(aliasName).getTime(), is(both(greaterThanOrEqualTo(beforeTime)).and(lessThanOrEqualTo(client().threadPool().absoluteTimeInMillis() + 1000L))) ); } /** * Tests that multiple threads all racing to rollover based on a condition trigger one and only one rollover */ public void testMultiThreadedRollover() throws Exception { final String aliasName = "alias"; final String writeIndexPrefix = "tt-"; assertAcked(prepareCreate(writeIndexPrefix + "000001").addAlias(new Alias(aliasName).writeIndex(true)).get()); ensureGreen(); final int threadCount = randomIntBetween(5, 10); final CyclicBarrier barrier = new CyclicBarrier(threadCount + 1); final AtomicBoolean running = new AtomicBoolean(true); Set<Thread> threads = IntStream.range(0, threadCount).mapToObj(i -> new Thread(() -> { try { logger.info("--> [{}] waiting for all the other threads before starting", i); barrier.await(); while (running.get()) { RolloverResponse resp = indicesAdmin().prepareRolloverIndex(aliasName) .setConditions(RolloverConditions.newBuilder().addMaxIndexDocsCondition(1L)) .get(); if (resp.isRolledOver()) { logger.info("--> thread [{}] successfully rolled over: {}", i, Strings.toString(resp)); assertThat(resp.getOldIndex(), equalTo(writeIndexPrefix + "000001")); assertThat(resp.getNewIndex(), equalTo(writeIndexPrefix + "000002")); } } } catch (Exception e) { logger.error(() -> "thread [" + i + "] encountered unexpected exception", e); fail("we should not encounter unexpected exceptions"); } }, "rollover-thread-" + i)).collect(Collectors.toSet()); threads.forEach(Thread::start); // Okay, signal the floodgates to open barrier.await(); index(aliasName, null, "{\"foo\": \"bar\"}"); assertBusy(() -> { try { indicesAdmin().prepareGetIndex(TEST_REQUEST_TIMEOUT).addIndices(writeIndexPrefix + "000002").get(); } catch (Exception e) { logger.info("--> expecting second index to be created but it has not yet been created"); fail("expecting second index to exist"); } }); // Tell everyone to stop trying to roll over running.set(false); threads.forEach(thread -> { try { thread.join(1000); } catch (Exception e) { logger.warn("expected thread to be stopped, but got", e); } }); // We should *NOT* have a third index, it should have rolled over *exactly* once expectThrows(Exception.class, indicesAdmin().prepareGetIndex(TEST_REQUEST_TIMEOUT).addIndices(writeIndexPrefix + "000003")); } public void testRolloverConcurrently() throws Exception { int numOfThreads = 5; int numberOfRolloversPerThread = 20; var putTemplateRequest = new TransportPutComposableIndexTemplateAction.Request("my-template"); var template = new Template( Settings.builder() // Avoid index check, which gets randomly inserted by test framework. This slows down the test a bit. .put(IndexSettings.INDEX_CHECK_ON_STARTUP.getKey(), false) .put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 0) .build(), null, null ); putTemplateRequest.indexTemplate( ComposableIndexTemplate.builder().indexPatterns(List.of("test-*")).template(template).priority(100L).build() ); assertAcked(client().execute(TransportPutComposableIndexTemplateAction.TYPE, putTemplateRequest).actionGet()); final CyclicBarrier barrier = new CyclicBarrier(numOfThreads); runInParallel(numOfThreads, i -> { var aliasName = "test-" + i; assertAcked(prepareCreate(aliasName + "-000001").addAlias(new Alias(aliasName).writeIndex(true)).get()); for (int j = 1; j <= numberOfRolloversPerThread; j++) { try { barrier.await(); } catch (Exception e) { throw new RuntimeException(e); } var response = indicesAdmin().prepareRolloverIndex(aliasName).waitForActiveShards(ActiveShardCount.NONE).get(); assertThat(response.getOldIndex(), equalTo(aliasName + Strings.format("-%06d", j))); assertThat(response.getNewIndex(), equalTo(aliasName + Strings.format("-%06d", j + 1))); assertThat(response.isDryRun(), equalTo(false)); assertThat(response.isRolledOver(), equalTo(true)); } }); for (int i = 0; i < numOfThreads; i++) { var aliasName = "test-" + i; var response = indicesAdmin().getAliases(new GetAliasesRequest(TEST_REQUEST_TIMEOUT, aliasName)).get(); List<Map.Entry<String, List<AliasMetadata>>> actual = response.getAliases().entrySet().stream().toList(); List<Map.Entry<String, List<AliasMetadata>>> expected = new ArrayList<>(numberOfRolloversPerThread); int numOfIndices = numberOfRolloversPerThread + 1; for (int j = 1; j <= numOfIndices; j++) { AliasMetadata.Builder amBuilder = new AliasMetadata.Builder(aliasName); amBuilder.writeIndex(j == numOfIndices); expected.add(Map.entry(aliasName + Strings.format("-%06d", j), List.of(amBuilder.build()))); } assertThat(actual, containsInAnyOrder(expected.toArray(Object[]::new))); } } }
RolloverIT
java
apache__hadoop
hadoop-common-project/hadoop-registry/src/main/java/org/apache/hadoop/registry/server/dns/ContainerServiceRecordProcessor.java
{ "start": 5772, "end": 6991 }
class ____ extends ContainerRecordDescriptor<Name> { /** * Creates a container PTR record descriptor. * @param path registry path for service record * @param record service record * @throws Exception */ public PTRContainerRecordDescriptor(String path, ServiceRecord record) throws Exception { super(path, record); } /** * Initializes the descriptor parameters. * @param serviceRecord the service record. */ @Override protected void init(ServiceRecord serviceRecord) { String host = serviceRecord.get(YarnRegistryAttributes.YARN_HOSTNAME); String ip = serviceRecord.get(YarnRegistryAttributes.YARN_IP); Name reverseLookupName = null; if (host != null && ip != null) { try { reverseLookupName = reverseIP(ip); } catch (UnknownHostException e) { //LOG } } this.setNames(new Name[] {reverseLookupName}); try { this.setTarget(getContainerName()); } catch (TextParseException e) { //LOG } catch (PathNotFoundException e) { //LOG } } } /** * A container A record descriptor. */
PTRContainerRecordDescriptor
java
spring-projects__spring-security
oauth2/oauth2-authorization-server/src/main/java/org/springframework/security/oauth2/server/authorization/authentication/X509ClientCertificateAuthenticationProvider.java
{ "start": 2360, "end": 8477 }
class ____ implements AuthenticationProvider { private static final String ERROR_URI = "https://datatracker.ietf.org/doc/html/rfc6749#section-3.2.1"; private final Log logger = LogFactory.getLog(getClass()); private final RegisteredClientRepository registeredClientRepository; private final CodeVerifierAuthenticator codeVerifierAuthenticator; private final Consumer<OAuth2ClientAuthenticationContext> selfSignedCertificateVerifier = new X509SelfSignedCertificateVerifier(); private Consumer<OAuth2ClientAuthenticationContext> certificateVerifier = this::verifyX509Certificate; /** * Constructs a {@code X509ClientCertificateAuthenticationProvider} using the provided * parameters. * @param registeredClientRepository the repository of registered clients * @param authorizationService the authorization service */ public X509ClientCertificateAuthenticationProvider(RegisteredClientRepository registeredClientRepository, OAuth2AuthorizationService authorizationService) { Assert.notNull(registeredClientRepository, "registeredClientRepository cannot be null"); Assert.notNull(authorizationService, "authorizationService cannot be null"); this.registeredClientRepository = registeredClientRepository; this.codeVerifierAuthenticator = new CodeVerifierAuthenticator(authorizationService); } @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { OAuth2ClientAuthenticationToken clientAuthentication = (OAuth2ClientAuthenticationToken) authentication; if (!ClientAuthenticationMethod.TLS_CLIENT_AUTH.equals(clientAuthentication.getClientAuthenticationMethod()) && !ClientAuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH .equals(clientAuthentication.getClientAuthenticationMethod())) { return null; } String clientId = clientAuthentication.getPrincipal().toString(); RegisteredClient registeredClient = this.registeredClientRepository.findByClientId(clientId); if (registeredClient == null) { throwInvalidClient(OAuth2ParameterNames.CLIENT_ID); } if (this.logger.isTraceEnabled()) { this.logger.trace("Retrieved registered client"); } if (!registeredClient.getClientAuthenticationMethods() .contains(clientAuthentication.getClientAuthenticationMethod())) { throwInvalidClient("authentication_method"); } if (!(clientAuthentication.getCredentials() instanceof X509Certificate[])) { throwInvalidClient("credentials"); } OAuth2ClientAuthenticationContext authenticationContext = OAuth2ClientAuthenticationContext .with(clientAuthentication) .registeredClient(registeredClient) .build(); this.certificateVerifier.accept(authenticationContext); if (this.logger.isTraceEnabled()) { this.logger.trace("Validated client authentication parameters"); } // Validate the "code_verifier" parameter for the confidential client, if // available this.codeVerifierAuthenticator.authenticateIfAvailable(clientAuthentication, registeredClient); if (this.logger.isTraceEnabled()) { this.logger.trace("Authenticated client X509Certificate"); } return new OAuth2ClientAuthenticationToken(registeredClient, clientAuthentication.getClientAuthenticationMethod(), clientAuthentication.getCredentials()); } @Override public boolean supports(Class<?> authentication) { return OAuth2ClientAuthenticationToken.class.isAssignableFrom(authentication); } /** * Sets the {@code Consumer} providing access to the * {@link OAuth2ClientAuthenticationContext} and is responsible for verifying the * client {@code X509Certificate} associated in the * {@link OAuth2ClientAuthenticationToken}. The default implementation for the * {@code tls_client_auth} authentication method verifies the * {@link ClientSettings#getX509CertificateSubjectDN() expected subject distinguished * name}. * * <p> * <b>NOTE:</b> If verification fails, an {@link OAuth2AuthenticationException} MUST * be thrown. * @param certificateVerifier the {@code Consumer} providing access to the * {@link OAuth2ClientAuthenticationContext} and is responsible for verifying the * client {@code X509Certificate} */ public void setCertificateVerifier(Consumer<OAuth2ClientAuthenticationContext> certificateVerifier) { Assert.notNull(certificateVerifier, "certificateVerifier cannot be null"); this.certificateVerifier = certificateVerifier; } private void verifyX509Certificate(OAuth2ClientAuthenticationContext clientAuthenticationContext) { OAuth2ClientAuthenticationToken clientAuthentication = clientAuthenticationContext.getAuthentication(); if (ClientAuthenticationMethod.SELF_SIGNED_TLS_CLIENT_AUTH .equals(clientAuthentication.getClientAuthenticationMethod())) { this.selfSignedCertificateVerifier.accept(clientAuthenticationContext); } else { verifyX509CertificateSubjectDN(clientAuthenticationContext); } } private void verifyX509CertificateSubjectDN(OAuth2ClientAuthenticationContext clientAuthenticationContext) { OAuth2ClientAuthenticationToken clientAuthentication = clientAuthenticationContext.getAuthentication(); RegisteredClient registeredClient = clientAuthenticationContext.getRegisteredClient(); X509Certificate[] clientCertificateChain = (X509Certificate[]) clientAuthentication.getCredentials(); X509Certificate clientCertificate = clientCertificateChain[0]; String expectedSubjectDN = registeredClient.getClientSettings().getX509CertificateSubjectDN(); if (!StringUtils.hasText(expectedSubjectDN) || !clientCertificate.getSubjectX500Principal().getName().equals(expectedSubjectDN)) { throwInvalidClient("x509_certificate_subject_dn"); } } private static void throwInvalidClient(String parameterName) { throwInvalidClient(parameterName, null); } private static void throwInvalidClient(String parameterName, Throwable cause) { OAuth2Error error = new OAuth2Error(OAuth2ErrorCodes.INVALID_CLIENT, "Client authentication failed: " + parameterName, ERROR_URI); throw new OAuth2AuthenticationException(error, error.toString(), cause); } }
X509ClientCertificateAuthenticationProvider
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/blob/BlobUtils.java
{ "start": 24231, "end": 24837 }
class ____<T extends BlobKey> { private final T blobKey; private final java.nio.file.Path path; @Nullable private final JobID jobId; Blob(T blobKey, java.nio.file.Path path, @Nullable JobID jobId) { this.blobKey = blobKey; this.path = path; this.jobId = jobId; } public T getBlobKey() { return blobKey; } public java.nio.file.Path getPath() { return path; } @Nullable public JobID getJobId() { return jobId; } } static final
Blob
java
elastic__elasticsearch
x-pack/plugin/spatial/src/test/java/org/elasticsearch/xpack/spatial/search/aggregations/GeoLineAggregatorTests.java
{ "start": 27787, "end": 29130 }
class ____ extends StreamingGeometrySimplifier.PointError { private final double sortField; private final long encoded; TestSimplifiablePoint(int index, double x, double y, double sortField) { super(index, quantizeX(x), quantizeY(y)); this.sortField = sortField; this.encoded = encode(x(), y()); } private static double quantizeX(double x) { return GeoEncodingUtils.decodeLongitude(GeoEncodingUtils.encodeLongitude(x)); } private static double quantizeY(double y) { return GeoEncodingUtils.decodeLatitude(GeoEncodingUtils.encodeLatitude(y)); } private static long encode(double x, double y) { return (((long) GeoEncodingUtils.encodeLongitude(x)) << 32) | GeoEncodingUtils.encodeLatitude(y) & 0xffffffffL; } private static double decodeLongitude(long encoded) { return GeoEncodingUtils.decodeLongitude((int) (encoded >>> 32)); } private static double decodeLatitude(long encoded) { return GeoEncodingUtils.decodeLatitude((int) (encoded & 0xffffffffL)); } } /** Allow test to use own objects for internal use in geometry simplifier, so we can track the sort-fields together with the points */ static
TestSimplifiablePoint
java
spring-projects__spring-framework
spring-context/src/test/java/org/springframework/context/event/EventPublicationInterceptorTests.java
{ "start": 1671, "end": 2951 }
class ____ { private final EventPublicationInterceptor interceptor = new EventPublicationInterceptor(); @BeforeEach void setup() { ApplicationEventPublisher publisher = mock(); this.interceptor.setApplicationEventPublisher(publisher); } @Test void withNoApplicationEventClassSupplied() { assertThatIllegalArgumentException().isThrownBy(interceptor::afterPropertiesSet); } @Test void withNonApplicationEventClassSupplied() { assertThatIllegalArgumentException().isThrownBy(() -> { interceptor.setApplicationEventClass(getClass()); interceptor.afterPropertiesSet(); }); } @Test void withAbstractStraightApplicationEventClassSupplied() { assertThatIllegalArgumentException().isThrownBy(() -> { interceptor.setApplicationEventClass(ApplicationEvent.class); interceptor.afterPropertiesSet(); }); } @Test void withApplicationEventClassThatDoesntExposeAValidCtor() { assertThatIllegalArgumentException().isThrownBy(() -> { interceptor.setApplicationEventClass(TestEventWithNoValidOneArgObjectCtor.class); interceptor.afterPropertiesSet(); }); } @Test void expectedBehavior() { TestBean target = new TestBean(); final TestApplicationListener listener = new TestApplicationListener();
EventPublicationInterceptorTests
java
netty__netty
transport/src/test/java/io/netty/nativeimage/ChannelHandlerMetadataUtil.java
{ "start": 7445, "end": 8125 }
class ____ { Condition(String typeReachable) { this.typeReachable = typeReachable; } final String typeReachable; @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Condition condition = (Condition) o; return typeReachable != null && typeReachable.equals(condition.typeReachable); } @Override public int hashCode() { return typeReachable.hashCode(); } } private static final
Condition
java
elastic__elasticsearch
x-pack/plugin/sql/src/main/java/org/elasticsearch/xpack/sql/expression/predicate/operator/arithmetic/Mul.java
{ "start": 877, "end": 2778 }
class ____ extends SqlArithmeticOperation implements BinaryComparisonInversible { private DataType dataType; public Mul(Source source, Expression left, Expression right) { super(source, left, right, SqlBinaryArithmeticOperation.MUL); } @Override protected TypeResolution resolveType() { if (childrenResolved() == false) { return new TypeResolution("Unresolved children"); } DataType l = left().dataType(); DataType r = right().dataType(); // 1. both are numbers if (DataTypes.isNullOrNumeric(l) && DataTypes.isNullOrNumeric(r)) { return TypeResolution.TYPE_RESOLVED; } if (SqlDataTypes.isNullOrInterval(l) && (r.isInteger() || DataTypes.isNull(r))) { dataType = l; return TypeResolution.TYPE_RESOLVED; } else if (SqlDataTypes.isNullOrInterval(r) && (l.isInteger() || DataTypes.isNull(l))) { dataType = r; return TypeResolution.TYPE_RESOLVED; } return new TypeResolution(format(null, "[{}] has arguments with incompatible types [{}] and [{}]", symbol(), l, r)); } @Override public DataType dataType() { if (dataType == null) { dataType = super.dataType(); } return dataType; } @Override protected NodeInfo<Mul> info() { return NodeInfo.create(this, Mul::new, left(), right()); } @Override protected Mul replaceChildren(Expression newLeft, Expression newRight) { return new Mul(source(), newLeft, newRight); } @Override public Mul swapLeftAndRight() { return new Mul(source(), right(), left()); } @Override public ArithmeticOperationFactory binaryComparisonInverse() { return Div::new; } @Override protected boolean isCommutative() { return true; } }
Mul
java
apache__rocketmq
filter/src/test/java/org/apache/rocketmq/filter/ParserTest.java
{ "start": 1134, "end": 4528 }
class ____ { private static String andExpression = "a=3 and b<>4 And c>5 AND d<=4"; private static String andExpressionHasBlank = "a=3 and b<>4 And c>5 AND d<=4"; private static String orExpression = "a=3 or b<>4 Or c>5 OR d<=4"; private static String inExpression = "a in ('3', '4', '5')"; private static String notInExpression = "(a not in ('6', '4', '5')) or (b in ('3', '4', '5'))"; private static String betweenExpression = "(a between 2 and 10) AND (b not between 6 and 9)"; private static String equalNullExpression = "a is null"; private static String notEqualNullExpression = "a is not null"; private static String nowExpression = "a <= now"; private static String containsExpression = "a=3 and b contains 'xxx' and c not contains 'xxx'"; private static String invalidExpression = "a and between 2 and 10"; private static String illegalBetween = " a between 10 and 0"; @Test public void testParse_valid() { for (String expr : Arrays.asList( andExpression, orExpression, inExpression, notInExpression, betweenExpression, equalNullExpression, notEqualNullExpression, nowExpression, containsExpression )) { try { Expression expression = SelectorParser.parse(expr); assertThat(expression).isNotNull(); } catch (MQFilterException e) { e.printStackTrace(); assertThat(Boolean.FALSE).isTrue(); } } } @Test public void testParse_invalid() { try { SelectorParser.parse(invalidExpression); assertThat(Boolean.TRUE).isFalse(); } catch (MQFilterException e) { } } @Test public void testParse_decimalOverFlow() { try { String str = "100000000000000000000000"; SelectorParser.parse("a > " + str); assertThat(Boolean.TRUE).isFalse(); } catch (Exception e) { } } @Test public void testParse_floatOverFlow() { try { StringBuilder sb = new StringBuilder(210000); sb.append("1"); for (int i = 0; i < 2048; i ++) { sb.append("111111111111111111111111111111111111111111111111111"); } sb.append("."); for (int i = 0; i < 2048; i ++) { sb.append("111111111111111111111111111111111111111111111111111"); } String str = sb.toString(); SelectorParser.parse("a > " + str); assertThat(Boolean.TRUE).isFalse(); } catch (Exception e) { } } @Test public void testParse_illegalBetween() { try { SelectorParser.parse(illegalBetween); assertThat(Boolean.TRUE).isFalse(); } catch (Exception e) { } } @Test public void testEquals() { try { Expression expr1 = SelectorParser.parse(andExpression); Expression expr2 = SelectorParser.parse(andExpressionHasBlank); Expression expr3 = SelectorParser.parse(orExpression); assertThat(expr1).isEqualTo(expr2); assertThat(expr1).isNotEqualTo(expr3); } catch (MQFilterException e) { e.printStackTrace(); assertThat(Boolean.TRUE).isFalse(); } } }
ParserTest
java
apache__dubbo
dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/integration/multiple/servicediscoveryregistry/MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.java
{ "start": 2226, "end": 9675 }
class ____ implements IntegrationTest { private static final Logger logger = LoggerFactory.getLogger(MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest.class); /** * Define the provider application name. */ public static String PROVIDER_APPLICATION_NAME = "multiple-registry-center-provider-for-service-discovery-registry-protocol"; /** * Define the protocol's name. */ private static String PROTOCOL_NAME = CommonConstants.DUBBO; /** * Define the protocol's port. */ private static int PROTOCOL_PORT = 20880; /** * Define the {@link ServiceConfig} instance. */ private ServiceConfig<MultipleRegistryCenterServiceDiscoveryRegistryService> serviceConfig; /** * Define a {@link RegistryServiceListener} instance. */ private MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener registryServiceListener; /** * The localhost. */ private static String HOST = "127.0.0.1"; /** * The port of register center. */ private Set<Integer> ports = new HashSet<>(2); @BeforeEach public void setUp() throws Exception { logger.info(getClass().getSimpleName() + " testcase is beginning..."); DubboBootstrap.reset(); // initialize service config serviceConfig = new ServiceConfig<>(); serviceConfig.setInterface(MultipleRegistryCenterServiceDiscoveryRegistryService.class); serviceConfig.setRef(new MultipleRegistryCenterServiceDiscoveryRegistryServiceImpl()); serviceConfig.setAsync(false); RegistryConfig registryConfig1 = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress1()); Map<String, String> parameters1 = new HashMap<>(); parameters1.put("registry.listeners", MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY); registryConfig1.updateParameters(parameters1); DubboBootstrap.getInstance().registry(registryConfig1); ports.add(ZookeeperConfig.DEFAULT_CLIENT_PORT_1); RegistryConfig registryConfig2 = new RegistryConfig(ZookeeperRegistryCenterConfig.getConnectionAddress2()); Map<String, String> parameters2 = new HashMap<>(); parameters2.put("registry.listeners", MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY); registryConfig2.updateParameters(parameters2); DubboBootstrap.getInstance().registry(registryConfig2); ports.add(ZookeeperConfig.DEFAULT_CLIENT_PORT_2); DubboBootstrap.getInstance() .application(new ApplicationConfig(PROVIDER_APPLICATION_NAME)) .protocol(new ProtocolConfig(PROTOCOL_NAME, PROTOCOL_PORT)) .service(serviceConfig); // ---------------initialize--------------- // registryServiceListener = (MultipleRegistryCenterServiceDiscoveryRegistryRegistryServiceListener) ExtensionLoader.getExtensionLoader(RegistryServiceListener.class) .getExtension(MULTIPLE_CONFIG_CENTER_SERVICE_DISCOVERY_REGISTRY); // RegistryServiceListener is not null Assertions.assertNotNull(registryServiceListener); registryServiceListener.getStorage().clear(); } /** * Define a {@link RegistryServiceListener} for helping check.<p> * There are some checkpoints need to verify as follow: * <ul> * <li>ServiceConfig is exported or not</li> * <li>ServiceDiscoveryRegistryStorage is empty or not</li> * </ul> */ private void beforeExport() { // ---------------checkpoints--------------- // // ServiceConfig isn't exported Assertions.assertFalse(serviceConfig.isExported()); // ServiceDiscoveryRegistryStorage is empty Assertions.assertEquals(registryServiceListener.getStorage().size(), 0); } /** * {@inheritDoc} */ @Test @Override public void integrate() { beforeExport(); DubboBootstrap.getInstance().start(); afterExport(); ReferenceConfig<MultipleRegistryCenterServiceDiscoveryRegistryService> referenceConfig = new ReferenceConfig<>(); referenceConfig.setInterface(MultipleRegistryCenterServiceDiscoveryRegistryService.class); referenceConfig.get().hello("Dubbo in multiple registry center"); afterInvoke(); } /** * There are some checkpoints need to check after exported as follow: * <ul> * <li>ServiceDiscoveryRegistry is right or not</li> * <li>All register center has been registered and subscribed</li> * </ul> */ private void afterExport() { // ServiceDiscoveryRegistry is not null Assertions.assertEquals(registryServiceListener.getStorage().size(), 2); // All register center has been registered and subscribed for (int port : ports) { Assertions.assertTrue(registryServiceListener.getStorage().contains(HOST, port)); ServiceDiscoveryRegistryInfoWrapper serviceDiscoveryRegistryInfoWrapper = registryServiceListener.getStorage().get(HOST, port); // check if it's registered Assertions.assertTrue(serviceDiscoveryRegistryInfoWrapper.isRegistered()); // check if it's subscribed Assertions.assertFalse(serviceDiscoveryRegistryInfoWrapper.isSubscribed()); MetadataServiceDelegation metadataService = DubboBootstrap.getInstance() .getApplicationModel() .getBeanFactory() .getBean(MetadataServiceDelegation.class); // check if the count of exported urls is right or not Assertions.assertEquals(metadataService.getExportedURLs().size(), 1); // check the exported url is right or not. Assertions.assertTrue(metadataService .getExportedURLs() .first() .contains(MultipleRegistryCenterServiceDiscoveryRegistryService.class.getName())); // check the count of metadatainfo is right or not. Assertions.assertEquals(2, metadataService.getMetadataInfos().size()); } } /** * There are some checkpoints need to check after invoked as follow: */ private void afterInvoke() {} @AfterEach public void tearDown() throws IOException { DubboBootstrap.reset(); serviceConfig = null; // TODO: we need to check whether this scenario is normal // TODO: the Exporter and ServiceDiscoveryRegistry are same in multiple registry center /* for (int port: ports) { Assertions.assertTrue(registryServiceListener.getStorage().contains(HOST, port)); ServiceDiscoveryRegistryInfoWrapper serviceDiscoveryRegistryInfoWrapper = registryServiceListener.getStorage().get(HOST, port); // check if it's registered Assertions.assertFalse(serviceDiscoveryRegistryInfoWrapper.isRegistered()); // check if it's subscribed Assertions.assertFalse(serviceDiscoveryRegistryInfoWrapper.isSubscribed()); } */ registryServiceListener.getStorage().clear(); registryServiceListener = null; logger.info(getClass().getSimpleName() + " testcase is ending..."); } }
MultipleRegistryCenterServiceDiscoveryRegistryIntegrationTest
java
apache__flink
flink-tests/src/test/java/org/apache/flink/test/classloading/jar/CustomKvStateProgram.java
{ "start": 4367, "end": 5158 }
class ____ extends RichFlatMapFunction<Tuple2<Integer, Integer>, Integer> { private static final long serialVersionUID = -5939722892793950253L; private transient ReducingState<Integer> kvState; @Override public void open(OpenContext openContext) throws Exception { ReducingStateDescriptor<Integer> stateDescriptor = new ReducingStateDescriptor<>("reducing-state", new ReduceSum(), Integer.class); this.kvState = getRuntimeContext().getReducingState(stateDescriptor); } @Override public void flatMap(Tuple2<Integer, Integer> value, Collector<Integer> out) throws Exception { kvState.add(value.f1); } private static
ReducingStateFlatMap
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/context/support/ContextLoaderUtils.java
{ "start": 3042, "end": 3252 }
class ____ or enclosing class * hierarchy. Each nested list contains the context configuration attributes * declared either via a single instance of {@code @ContextConfiguration} on * the particular
hierarchy
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azurebfs/utils/ListUtils.java
{ "start": 988, "end": 1032 }
class ____ List operations. */ public final
for
java
elastic__elasticsearch
x-pack/plugin/ent-search/src/main/java/org/elasticsearch/xpack/application/connector/action/UpdateConnectorFilteringAction.java
{ "start": 1467, "end": 1782 }
class ____ { public static final String NAME = "cluster:admin/xpack/connector/update_filtering"; public static final ActionType<ConnectorUpdateActionResponse> INSTANCE = new ActionType<>(NAME); private UpdateConnectorFilteringAction() {/* no instances */} public static
UpdateConnectorFilteringAction
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/io/network/netty/ClientOutboundMessage.java
{ "start": 1045, "end": 1291 }
class ____ { protected final RemoteInputChannel inputChannel; ClientOutboundMessage(RemoteInputChannel inputChannel) { this.inputChannel = inputChannel; } @Nullable abstract Object buildMessage(); }
ClientOutboundMessage
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/odps/issues/Issue4992.java
{ "start": 373, "end": 992 }
class ____ { @Test public void testInsert() { String sql = "CREATE TABLE IF NOT EXISTS test_table \n" + "(\n" + " user_id STRING COMMENT\"userid\"\n" + " ,user_features STRING COMMENT\"用户特征\"\n" + ")\n" + ";"; SQLCreateTableStatement stmt = (SQLCreateTableStatement) SQLUtils.parseSingleStatement(sql, DbType.odps); SQLColumnDefinition column = stmt.getColumn("user_id"); assertNotNull(column); assertNotNull(column.getParent()); assertSame(stmt, column.getParent()); } }
Issue4992
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/beanmanager/BeanManagerTest.java
{ "start": 15976, "end": 16236 }
class ____ implements Converter<String> { @Inject @Delegate Converter<String> delegate; @Override public String convert(String value) { return delegate.convert(value).repeat(2); } } }
RepeatDecorator
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/GenericFileMessageTest.java
{ "start": 1177, "end": 2450 }
class ____ extends ContextTestSupport { private final CamelContext camelContext = new DefaultCamelContext(); @Test public void testGenericMessageToStringConversion() { GenericFileMessage<File> message = new GenericFileMessage<>(camelContext); assertStringContains(message.toString(), "org.apache.camel.component.file.GenericFileMessage@"); GenericFile<File> file = new GenericFile<>(true); file.setFileName("target/dummy/test.txt"); file.setFile(new File("target/dummy/test.txt")); message = new GenericFileMessage<>(camelContext, file); Object o1 = FileUtil.isWindows() ? "target\\dummy\\test.txt" : "target/dummy/test.txt"; assertEquals(o1, message.toString()); } @Test public void testGenericFileContentType() { GenericFile<File> file = new GenericFile<>(true); file.setEndpointPath("target"); file.setFileName("target"); file.setFile(new File("target/camel-core-test.log")); GenericFileMessage<File> message = new GenericFileMessage<>(camelContext, file); file.populateHeaders(message, false); assertEquals("txt", message.getHeader(Exchange.FILE_CONTENT_TYPE), "Get a wrong file content type"); } }
GenericFileMessageTest
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/services/ChecksumAlgorithmServiceException.java
{ "start": 924, "end": 1109 }
class ____ extends MavenException { public ChecksumAlgorithmServiceException(String message, Throwable cause) { super(message, cause); } }
ChecksumAlgorithmServiceException
java
quarkusio__quarkus
extensions/resteasy-reactive/rest/deployment/src/test/java/io/quarkus/resteasy/reactive/server/test/security/inheritance/noclassannotation/NoAnnotationBaseResourceWithoutPathImplInterface.java
{ "start": 1418, "end": 5519 }
class ____ extends NoAnnotationParentResourceWithoutPathImplInterface { @Override @POST @Path(CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + NO_SECURITY_ANNOTATION_PATH) public String classPathOnInterface_ImplOnBase_ImplMethodWithPath_NoAnnotation(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + NO_SECURITY_ANNOTATION_PATH; } @RolesAllowed("admin") @Override @POST @Path(CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + METHOD_ROLES_ALLOWED_PATH) public String classPathOnInterface_ImplOnBase_ImplMethodWithPath_MethodRolesAllowed(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + METHOD_ROLES_ALLOWED_PATH; } @DenyAll @Override @POST @Path(CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + METHOD_DENY_ALL_PATH) public String classPathOnInterface_ImplOnBase_ImplMethodWithPath_MethodDenyAll(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + METHOD_DENY_ALL_PATH; } @PermitAll @Override @POST @Path(CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + METHOD_PERMIT_ALL_PATH) public String classPathOnInterface_ImplOnBase_ImplMethodWithPath_MethodPermitAll(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + IMPL_METHOD_WITH_PATH + METHOD_PERMIT_ALL_PATH; } @Override public String classPathOnInterface_ImplOnBase_InterfaceMethodWithPath_NoAnnotation(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + INTERFACE_METHOD_WITH_PATH + NO_SECURITY_ANNOTATION_PATH; } @RolesAllowed("admin") @Override public String classPathOnInterface_ImplOnBase_InterfaceMethodWithPath_MethodRolesAllowed(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + INTERFACE_METHOD_WITH_PATH + METHOD_ROLES_ALLOWED_PATH; } @DenyAll @Override public String classPathOnInterface_ImplOnBase_InterfaceMethodWithPath_MethodDenyAll(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + INTERFACE_METHOD_WITH_PATH + METHOD_DENY_ALL_PATH; } @PermitAll @Override public String classPathOnInterface_ImplOnBase_InterfaceMethodWithPath_MethodPermitAll(JsonObject array) { return CLASS_PATH_ON_INTERFACE + IMPL_ON_BASE + INTERFACE_METHOD_WITH_PATH + METHOD_PERMIT_ALL_PATH; } @Override public NoAnnotationSubResourceWithoutPath classPathOnInterface_SubDeclaredOnInterface_SubImplOnBase_NoSecurityAnnotation() { return new NoAnnotationSubResourceWithoutPath(CLASS_PATH_ON_INTERFACE + SUB_DECLARED_ON_INTERFACE + SUB_IMPL_ON_BASE + NO_SECURITY_ANNOTATION_PATH); } @PermitAll @Override public NoAnnotationSubResourceWithoutPath classPathOnInterface_SubDeclaredOnInterface_SubImplOnBase_MethodPermitAll() { return new NoAnnotationSubResourceWithoutPath(CLASS_PATH_ON_INTERFACE + SUB_DECLARED_ON_INTERFACE + SUB_IMPL_ON_BASE + METHOD_PERMIT_ALL_PATH); } @DenyAll @Override public NoAnnotationSubResourceWithoutPath classPathOnInterface_SubDeclaredOnInterface_SubImplOnBase_MethodDenyAll() { return new NoAnnotationSubResourceWithoutPath(CLASS_PATH_ON_INTERFACE + SUB_DECLARED_ON_INTERFACE + SUB_IMPL_ON_BASE + METHOD_DENY_ALL_PATH); } @RolesAllowed("admin") @Override public NoAnnotationSubResourceWithoutPath classPathOnInterface_SubDeclaredOnInterface_SubImplOnBase_MethodRolesAllowed() { return new NoAnnotationSubResourceWithoutPath(CLASS_PATH_ON_INTERFACE + SUB_DECLARED_ON_INTERFACE + SUB_IMPL_ON_BASE + METHOD_ROLES_ALLOWED_PATH); } @Override public String classPathOnInterface_ImplOnBase_ParentMethodWithPath_NoSecurityAnnotation(JsonObject array) { throw new IllegalStateException("RESTEasy didn't support this endpoint in past"); } }
NoAnnotationBaseResourceWithoutPathImplInterface
java
apache__commons-lang
src/test/java/org/apache/commons/lang3/builder/EqualsBuilderTest.java
{ "start": 8364, "end": 8679 }
class ____ extends TestObject { private transient int t; TestTSubObject2(final int a, final int t) { super(a); } public int getT() { return t; } public void setT(final int t) { this.t = t; } } static
TestTSubObject2
java
netty__netty
codec-http/src/main/java/io/netty/handler/codec/spdy/DefaultSpdyHeaders.java
{ "start": 1038, "end": 2560 }
class ____ extends DefaultHeaders<CharSequence, CharSequence, SpdyHeaders> implements SpdyHeaders { private static final NameValidator<CharSequence> SpdyNameValidator = new NameValidator<CharSequence>() { @Override public void validateName(CharSequence name) { SpdyCodecUtil.validateHeaderName(name); } }; public DefaultSpdyHeaders() { this(true); } @SuppressWarnings("unchecked") public DefaultSpdyHeaders(boolean validate) { super(CASE_INSENSITIVE_HASHER, validate ? HeaderValueConverterAndValidator.INSTANCE : CharSequenceValueConverter.INSTANCE, validate ? SpdyNameValidator : NameValidator.NOT_NULL); } @Override public String getAsString(CharSequence name) { return HeadersUtils.getAsString(this, name); } @Override public List<String> getAllAsString(CharSequence name) { return HeadersUtils.getAllAsString(this, name); } @Override public Iterator<Entry<String, String>> iteratorAsString() { return HeadersUtils.iteratorAsString(this); } @Override public boolean contains(CharSequence name, CharSequence value) { return contains(name, value, false); } @Override public boolean contains(CharSequence name, CharSequence value, boolean ignoreCase) { return contains(name, value, ignoreCase ? CASE_INSENSITIVE_HASHER : CASE_SENSITIVE_HASHER); } private static final
DefaultSpdyHeaders
java
spring-projects__spring-boot
module/spring-boot-devtools/src/main/java/org/springframework/boot/devtools/restart/RestartScopeInitializer.java
{ "start": 1494, "end": 2080 }
class ____ implements Scope { @Override public Object get(String name, ObjectFactory<?> objectFactory) { return Restarter.getInstance().getOrAddAttribute(name, objectFactory); } @Override public Object remove(String name) { return Restarter.getInstance().removeAttribute(name); } @Override public void registerDestructionCallback(String name, Runnable callback) { } @Override public @Nullable Object resolveContextualObject(String key) { return null; } @Override public @Nullable String getConversationId() { return null; } } }
RestartScope
java
elastic__elasticsearch
server/src/internalClusterTest/java/org/elasticsearch/action/bulk/BulkWithUpdatesIT.java
{ "start": 2797, "end": 36554 }
class ____ extends MockScriptPlugin { @Override @SuppressWarnings("unchecked") protected Map<String, Function<Map<String, Object>, Object>> pluginScripts() { Map<String, Function<Map<String, Object>, Object>> scripts = new HashMap<>(); scripts.put("ctx._source.field += 1", vars -> srcScript(vars, source -> { Integer field = (Integer) source.get("field"); return source.replace("field", field + 1); })); scripts.put("ctx._source.counter += 1", vars -> srcScript(vars, source -> { Integer counter = (Integer) source.get("counter"); return source.replace("counter", counter + 1); })); scripts.put("ctx._source.field2 = 'value2'", vars -> srcScript(vars, source -> source.replace("field2", "value2"))); scripts.put("throw script exception on unknown var", vars -> { throw new ScriptException("message", null, Collections.emptyList(), "exception on unknown var", CustomScriptPlugin.NAME); }); scripts.put("ctx.op = \"none\"", vars -> ((Map<String, Object>) vars.get("ctx")).put("op", "none")); scripts.put("ctx.op = \"delete\"", vars -> ((Map<String, Object>) vars.get("ctx")).put("op", "delete")); return scripts; } @SuppressWarnings("unchecked") static Object srcScript(Map<String, Object> vars, Function<Map<String, Object>, Object> f) { Map<?, ?> ctx = (Map<?, ?>) vars.get("ctx"); Map<String, Object> source = (Map<String, Object>) ctx.get("_source"); return f.apply(source); } } public void testBulkUpdateSimple() throws Exception { assertAcked(prepareCreate("test").addAlias(new Alias("alias"))); ensureGreen(); BulkResponse bulkResponse = client().prepareBulk() .add(prepareIndex(indexOrAlias()).setId("1").setSource("field", 1)) .add(prepareIndex(indexOrAlias()).setId("2").setSource("field", 2).setCreate(true)) .add(prepareIndex(indexOrAlias()).setId("3").setSource("field", 3)) .add(prepareIndex(indexOrAlias()).setId("4").setSource("field", 4)) .add(prepareIndex(indexOrAlias()).setId("5").setSource("field", 5)) .get(); assertThat(bulkResponse.hasFailures(), equalTo(false)); assertThat(bulkResponse.getItems().length, equalTo(5)); for (BulkItemResponse bulkItemResponse : bulkResponse) { assertThat(bulkItemResponse.getIndex(), equalTo("test")); } final Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "ctx._source.field += 1", Collections.emptyMap()); bulkResponse = client().prepareBulk() .add(client().prepareUpdate().setIndex(indexOrAlias()).setId("1").setScript(script)) .add(client().prepareUpdate().setIndex(indexOrAlias()).setId("2").setScript(script).setRetryOnConflict(3)) .add( client().prepareUpdate() .setIndex(indexOrAlias()) .setId("3") .setDoc(jsonBuilder().startObject().field("field1", "test").endObject()) ) .get(); assertThat(bulkResponse.hasFailures(), equalTo(false)); assertThat(bulkResponse.getItems().length, equalTo(3)); for (BulkItemResponse bulkItemResponse : bulkResponse) { assertThat(bulkItemResponse.getIndex(), equalTo("test")); } assertThat(bulkResponse.getItems()[0].getResponse().getId(), equalTo("1")); assertThat(bulkResponse.getItems()[0].getResponse().getVersion(), equalTo(2L)); assertThat(bulkResponse.getItems()[1].getResponse().getId(), equalTo("2")); assertThat(bulkResponse.getItems()[1].getResponse().getVersion(), equalTo(2L)); assertThat(bulkResponse.getItems()[2].getResponse().getId(), equalTo("3")); assertThat(bulkResponse.getItems()[2].getResponse().getVersion(), equalTo(2L)); GetResponse getResponse = client().prepareGet().setIndex("test").setId("1").get(); assertThat(getResponse.isExists(), equalTo(true)); assertThat(getResponse.getVersion(), equalTo(2L)); assertThat(((Number) getResponse.getSource().get("field")).longValue(), equalTo(2L)); getResponse = client().prepareGet().setIndex("test").setId("2").get(); assertThat(getResponse.isExists(), equalTo(true)); assertThat(getResponse.getVersion(), equalTo(2L)); assertThat(((Number) getResponse.getSource().get("field")).longValue(), equalTo(3L)); getResponse = client().prepareGet().setIndex("test").setId("3").get(); assertThat(getResponse.isExists(), equalTo(true)); assertThat(getResponse.getVersion(), equalTo(2L)); assertThat(getResponse.getSource().get("field1").toString(), equalTo("test")); bulkResponse = client().prepareBulk() .add( client().prepareUpdate() .setIndex(indexOrAlias()) .setId("6") .setScript(script) .setUpsert(jsonBuilder().startObject().field("field", 0).endObject()) ) .add(client().prepareUpdate().setIndex(indexOrAlias()).setId("7").setScript(script)) .add(client().prepareUpdate().setIndex(indexOrAlias()).setId("2").setScript(script)) .get(); assertThat(bulkResponse.hasFailures(), equalTo(true)); assertThat(bulkResponse.getItems().length, equalTo(3)); assertThat(bulkResponse.getItems()[0].getResponse().getId(), equalTo("6")); assertThat(bulkResponse.getItems()[0].getResponse().getVersion(), equalTo(1L)); assertThat(bulkResponse.getItems()[1].getResponse(), nullValue()); assertThat(bulkResponse.getItems()[1].getFailure().getIndex(), equalTo("test")); assertThat(bulkResponse.getItems()[1].getFailure().getId(), equalTo("7")); assertThat(bulkResponse.getItems()[1].getFailure().getMessage(), containsString("document missing")); assertThat(bulkResponse.getItems()[2].getResponse().getId(), equalTo("2")); assertThat(bulkResponse.getItems()[2].getResponse().getIndex(), equalTo("test")); assertThat(bulkResponse.getItems()[2].getResponse().getVersion(), equalTo(3L)); getResponse = client().prepareGet().setIndex("test").setId("6").get(); assertThat(getResponse.isExists(), equalTo(true)); assertThat(getResponse.getVersion(), equalTo(1L)); assertThat(((Number) getResponse.getSource().get("field")).longValue(), equalTo(0L)); getResponse = client().prepareGet().setIndex("test").setId("7").get(); assertThat(getResponse.isExists(), equalTo(false)); getResponse = client().prepareGet().setIndex("test").setId("2").get(); assertThat(getResponse.isExists(), equalTo(true)); assertThat(getResponse.getVersion(), equalTo(3L)); assertThat(((Number) getResponse.getSource().get("field")).longValue(), equalTo(4L)); } public void testBulkUpdateWithScriptedUpsertAndDynamicMappingUpdate() throws Exception { assertAcked(prepareCreate("test").addAlias(new Alias("alias"))); ensureGreen(); final Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "ctx._source.field += 1", Collections.emptyMap()); BulkResponse bulkResponse = client().prepareBulk() .add( client().prepareUpdate().setIndex(indexOrAlias()).setId("1").setScript(script).setScriptedUpsert(true).setUpsert("field", 1) ) .add( client().prepareUpdate().setIndex(indexOrAlias()).setId("2").setScript(script).setScriptedUpsert(true).setUpsert("field", 1) ) .get(); logger.info(bulkResponse.buildFailureMessage()); assertThat(bulkResponse.hasFailures(), equalTo(false)); assertThat(bulkResponse.getItems().length, equalTo(2)); for (BulkItemResponse bulkItemResponse : bulkResponse) { assertThat(bulkItemResponse.getIndex(), equalTo("test")); } assertThat(bulkResponse.getItems()[0].getResponse().getId(), equalTo("1")); assertThat(bulkResponse.getItems()[0].getResponse().getVersion(), equalTo(1L)); assertThat(bulkResponse.getItems()[1].getResponse().getId(), equalTo("2")); assertThat(bulkResponse.getItems()[1].getResponse().getVersion(), equalTo(1L)); GetResponse getResponse = client().prepareGet().setIndex("test").setId("1").get(); assertThat(getResponse.isExists(), equalTo(true)); assertThat(getResponse.getVersion(), equalTo(1L)); assertThat(((Number) getResponse.getSource().get("field")).longValue(), equalTo(2L)); getResponse = client().prepareGet().setIndex("test").setId("2").get(); assertThat(getResponse.isExists(), equalTo(true)); assertThat(getResponse.getVersion(), equalTo(1L)); assertThat(((Number) getResponse.getSource().get("field")).longValue(), equalTo(2L)); } public void testBulkWithCAS() throws Exception { createIndex("test", Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_SHARDS, 1).build()); ensureGreen(); BulkResponse bulkResponse = client().prepareBulk() .add(prepareIndex("test").setId("1").setCreate(true).setSource("field", "1")) .add(prepareIndex("test").setId("2").setCreate(true).setSource("field", "1")) .add(prepareIndex("test").setId("1").setSource("field", "2")) .get(); assertEquals(DocWriteResponse.Result.CREATED, bulkResponse.getItems()[0].getResponse().getResult()); assertThat(bulkResponse.getItems()[0].getResponse().getSeqNo(), equalTo(0L)); assertEquals(DocWriteResponse.Result.CREATED, bulkResponse.getItems()[1].getResponse().getResult()); assertThat(bulkResponse.getItems()[1].getResponse().getSeqNo(), equalTo(1L)); assertEquals(DocWriteResponse.Result.UPDATED, bulkResponse.getItems()[2].getResponse().getResult()); assertThat(bulkResponse.getItems()[2].getResponse().getSeqNo(), equalTo(2L)); bulkResponse = client().prepareBulk() .add(client().prepareUpdate("test", "1").setIfSeqNo(40L).setIfPrimaryTerm(20).setDoc(Requests.INDEX_CONTENT_TYPE, "field", "2")) .add(client().prepareUpdate("test", "2").setDoc(Requests.INDEX_CONTENT_TYPE, "field", "2")) .add(client().prepareUpdate("test", "1").setIfSeqNo(2L).setIfPrimaryTerm(1).setDoc(Requests.INDEX_CONTENT_TYPE, "field", "3")) .get(); assertThat(bulkResponse.getItems()[0].getFailureMessage(), containsString("version conflict")); assertThat(bulkResponse.getItems()[1].getResponse().getSeqNo(), equalTo(3L)); assertThat(bulkResponse.getItems()[2].getResponse().getSeqNo(), equalTo(4L)); bulkResponse = client().prepareBulk() .add(prepareIndex("test").setId("e1").setSource("field", "1").setVersion(10).setVersionType(VersionType.EXTERNAL)) .add(prepareIndex("test").setId("e2").setSource("field", "1").setVersion(10).setVersionType(VersionType.EXTERNAL)) .add(prepareIndex("test").setId("e1").setSource("field", "2").setVersion(12).setVersionType(VersionType.EXTERNAL)) .get(); assertEquals(DocWriteResponse.Result.CREATED, bulkResponse.getItems()[0].getResponse().getResult()); assertThat(bulkResponse.getItems()[0].getResponse().getVersion(), equalTo(10L)); assertEquals(DocWriteResponse.Result.CREATED, bulkResponse.getItems()[1].getResponse().getResult()); assertThat(bulkResponse.getItems()[1].getResponse().getVersion(), equalTo(10L)); assertEquals(DocWriteResponse.Result.UPDATED, bulkResponse.getItems()[2].getResponse().getResult()); assertThat(bulkResponse.getItems()[2].getResponse().getVersion(), equalTo(12L)); bulkResponse = client().prepareBulk() .add(client().prepareUpdate("test", "e1").setDoc(Requests.INDEX_CONTENT_TYPE, "field", "2").setIfSeqNo(10L).setIfPrimaryTerm(1)) .add(client().prepareUpdate("test", "e1").setDoc(Requests.INDEX_CONTENT_TYPE, "field", "3").setIfSeqNo(20L).setIfPrimaryTerm(1)) .get(); assertThat(bulkResponse.getItems()[0].getFailureMessage(), containsString("version conflict")); assertThat(bulkResponse.getItems()[1].getFailureMessage(), containsString("version conflict")); } public void testBulkUpdateMalformedScripts() throws Exception { createIndex("test"); ensureGreen(); BulkResponse bulkResponse = client().prepareBulk() .add(prepareIndex("test").setId("1").setSource("field", 1)) .add(prepareIndex("test").setId("2").setSource("field", 1)) .add(prepareIndex("test").setId("3").setSource("field", 1)) .get(); assertThat(bulkResponse.hasFailures(), equalTo(false)); assertThat(bulkResponse.getItems().length, equalTo(3)); bulkResponse = client().prepareBulk() .add( client().prepareUpdate() .setIndex("test") .setId("1") .setFetchSource("field", null) .setScript( new Script( ScriptType.INLINE, CustomScriptPlugin.NAME, "throw script exception on unknown var", Collections.emptyMap() ) ) ) .add( client().prepareUpdate() .setIndex("test") .setId("2") .setFetchSource("field", null) .setScript(new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "ctx._source.field += 1", Collections.emptyMap())) ) .add( client().prepareUpdate() .setIndex("test") .setId("3") .setFetchSource("field", null) .setScript( new Script( ScriptType.INLINE, CustomScriptPlugin.NAME, "throw script exception on unknown var", Collections.emptyMap() ) ) ) .get(); assertThat(bulkResponse.hasFailures(), equalTo(true)); assertThat(bulkResponse.getItems().length, equalTo(3)); assertThat(bulkResponse.getItems()[0].getFailure().getId(), equalTo("1")); assertThat(bulkResponse.getItems()[0].getFailure().getMessage(), containsString("failed to execute script")); assertThat(bulkResponse.getItems()[0].getResponse(), nullValue()); assertThat(bulkResponse.getItems()[1].getResponse().getId(), equalTo("2")); assertThat(bulkResponse.getItems()[1].getResponse().getVersion(), equalTo(2L)); assertThat(((UpdateResponse) bulkResponse.getItems()[1].getResponse()).getGetResult().sourceAsMap().get("field"), equalTo(2)); assertThat(bulkResponse.getItems()[1].getFailure(), nullValue()); assertThat(bulkResponse.getItems()[2].getFailure().getId(), equalTo("3")); assertThat(bulkResponse.getItems()[2].getFailure().getMessage(), containsString("failed to execute script")); assertThat(bulkResponse.getItems()[2].getResponse(), nullValue()); } public void testBulkUpdateLargerVolume() throws Exception { createIndex("test"); ensureGreen(); int numDocs = scaledRandomIntBetween(100, 2000); if (numDocs % 2 == 1) { numDocs++; // this test needs an even num of docs } final Script script = new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "ctx._source.counter += 1", Collections.emptyMap()); BulkRequestBuilder builder = client().prepareBulk(); for (int i = 0; i < numDocs; i++) { builder.add( client().prepareUpdate() .setIndex("test") .setId(Integer.toString(i)) .setFetchSource("counter", null) .setScript(script) .setUpsert(jsonBuilder().startObject().field("counter", 1).endObject()) ); } BulkResponse response = builder.get(); assertThat(response.hasFailures(), equalTo(false)); assertThat(response.getItems().length, equalTo(numDocs)); for (int i = 0; i < numDocs; i++) { assertThat(response.getItems()[i].getId(), equalTo(Integer.toString(i))); assertThat(response.getItems()[i].getVersion(), equalTo(1L)); assertThat(response.getItems()[i].getIndex(), equalTo("test")); assertThat(response.getItems()[i].getOpType(), equalTo(OpType.UPDATE)); assertThat(response.getItems()[i].getResponse().getId(), equalTo(Integer.toString(i))); assertThat(response.getItems()[i].getResponse().getVersion(), equalTo(1L)); assertThat(((UpdateResponse) response.getItems()[i].getResponse()).getGetResult().sourceAsMap().get("counter"), equalTo(1)); for (int j = 0; j < 5; j++) { GetResponse getResponse = client().prepareGet("test", Integer.toString(i)).get(); assertThat(getResponse.isExists(), equalTo(true)); assertThat(getResponse.getVersion(), equalTo(1L)); assertThat(((Number) getResponse.getSource().get("counter")).longValue(), equalTo(1L)); } } builder = client().prepareBulk(); for (int i = 0; i < numDocs; i++) { UpdateRequestBuilder updateBuilder = client().prepareUpdate() .setIndex("test") .setId(Integer.toString(i)) .setFetchSource("counter", null); if (i % 2 == 0) { updateBuilder.setScript(script); } else { updateBuilder.setDoc(jsonBuilder().startObject().field("counter", 2).endObject()); } if (i % 3 == 0) { updateBuilder.setRetryOnConflict(3); } builder.add(updateBuilder); } response = builder.get(); assertThat(response.hasFailures(), equalTo(false)); assertThat(response.getItems().length, equalTo(numDocs)); for (int i = 0; i < numDocs; i++) { assertThat(response.getItems()[i].getId(), equalTo(Integer.toString(i))); assertThat(response.getItems()[i].getVersion(), equalTo(2L)); assertThat(response.getItems()[i].getIndex(), equalTo("test")); assertThat(response.getItems()[i].getOpType(), equalTo(OpType.UPDATE)); assertThat(response.getItems()[i].getResponse().getId(), equalTo(Integer.toString(i))); assertThat(response.getItems()[i].getResponse().getVersion(), equalTo(2L)); assertThat(((UpdateResponse) response.getItems()[i].getResponse()).getGetResult().sourceAsMap().get("counter"), equalTo(2)); } builder = client().prepareBulk(); int maxDocs = numDocs / 2 + numDocs; for (int i = (numDocs / 2); i < maxDocs; i++) { builder.add(client().prepareUpdate().setIndex("test").setId(Integer.toString(i)).setScript(script)); } response = builder.get(); assertThat(response.hasFailures(), equalTo(true)); assertThat(response.getItems().length, equalTo(numDocs)); for (int i = 0; i < numDocs; i++) { int id = i + (numDocs / 2); if (i >= (numDocs / 2)) { assertThat(response.getItems()[i].getFailure().getId(), equalTo(Integer.toString(id))); assertThat(response.getItems()[i].getFailure().getMessage(), containsString("document missing")); } else { assertThat(response.getItems()[i].getId(), equalTo(Integer.toString(id))); assertThat(response.getItems()[i].getVersion(), equalTo(3L)); assertThat(response.getItems()[i].getIndex(), equalTo("test")); assertThat(response.getItems()[i].getOpType(), equalTo(OpType.UPDATE)); } } builder = client().prepareBulk(); for (int i = 0; i < numDocs; i++) { builder.add( client().prepareUpdate() .setIndex("test") .setId(Integer.toString(i)) .setScript(new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "ctx.op = \"none\"", Collections.emptyMap())) ); } response = builder.get(); assertThat(response.buildFailureMessage(), response.hasFailures(), equalTo(false)); assertThat(response.getItems().length, equalTo(numDocs)); for (int i = 0; i < numDocs; i++) { assertThat(response.getItems()[i].getItemId(), equalTo(i)); assertThat(response.getItems()[i].getId(), equalTo(Integer.toString(i))); assertThat(response.getItems()[i].getIndex(), equalTo("test")); assertThat(response.getItems()[i].getOpType(), equalTo(OpType.UPDATE)); } builder = client().prepareBulk(); for (int i = 0; i < numDocs; i++) { builder.add( client().prepareUpdate() .setIndex("test") .setId(Integer.toString(i)) .setScript(new Script(ScriptType.INLINE, CustomScriptPlugin.NAME, "ctx.op = \"delete\"", Collections.emptyMap())) ); } response = builder.get(); assertThat("expected no failures but got: " + response.buildFailureMessage(), response.hasFailures(), equalTo(false)); assertThat(response.getItems().length, equalTo(numDocs)); for (int i = 0; i < numDocs; i++) { final BulkItemResponse itemResponse = response.getItems()[i]; assertThat(itemResponse.getFailure(), nullValue()); assertThat(itemResponse.isFailed(), equalTo(false)); assertThat(itemResponse.getItemId(), equalTo(i)); assertThat(itemResponse.getId(), equalTo(Integer.toString(i))); assertThat(itemResponse.getIndex(), equalTo("test")); assertThat(itemResponse.getOpType(), equalTo(OpType.UPDATE)); for (int j = 0; j < 5; j++) { GetResponse getResponse = client().prepareGet("test", Integer.toString(i)).get(); assertThat(getResponse.isExists(), equalTo(false)); } } assertThat(response.hasFailures(), equalTo(false)); } public void testBulkIndexingWhileInitializing() throws Exception { int replica = randomInt(2); internalCluster().ensureAtLeastNumDataNodes(1 + replica); assertAcked(prepareCreate("test").setSettings(Settings.builder().put(indexSettings()).put("index.number_of_replicas", replica))); int numDocs = scaledRandomIntBetween(100, 5000); int bulk = scaledRandomIntBetween(1, 99); for (int i = 0; i < numDocs;) { final BulkRequestBuilder builder = client().prepareBulk(); for (int j = 0; j < bulk && i < numDocs; j++, i++) { builder.add(prepareIndex("test").setId(Integer.toString(i)).setSource("val", i)); } logger.info("bulk indexing {}-{}", i - bulk, i - 1); BulkResponse response = builder.get(); if (response.hasFailures()) { fail(response.buildFailureMessage()); } } refresh(); assertHitCount(prepareSearch().setSize(0), numDocs); } public void testFailingVersionedUpdatedOnBulk() throws Exception { createIndex("test"); indexDoc("test", "1", "field", "1"); final BulkResponse[] responses = new BulkResponse[30]; startInParallel(responses.length, threadID -> { BulkRequestBuilder requestBuilder = client().prepareBulk(); requestBuilder.add( client().prepareUpdate("test", "1") .setIfSeqNo(0L) .setIfPrimaryTerm(1) .setDoc(Requests.INDEX_CONTENT_TYPE, "field", threadID) ); responses[threadID] = requestBuilder.get(); }); int successes = 0; for (BulkResponse response : responses) { if (response.hasFailures() == false) { successes++; } } assertThat(successes, equalTo(1)); } // issue 4987 public void testThatInvalidIndexNamesShouldNotBreakCompleteBulkRequest() { int bulkEntryCount = randomIntBetween(10, 50); BulkRequestBuilder builder = client().prepareBulk(); boolean[] expectedFailures = new boolean[bulkEntryCount]; ArrayList<String> badIndexNames = new ArrayList<>(); for (int i = randomIntBetween(1, 5); i > 0; i--) { badIndexNames.add("INVALID.NAME" + i); } boolean expectFailure = false; for (int i = 0; i < bulkEntryCount; i++) { expectFailure |= expectedFailures[i] = randomBoolean(); String name; if (expectedFailures[i]) { name = randomFrom(badIndexNames); } else { name = "test"; } builder.add(prepareIndex(name).setId("1").setSource("field", 1)); } BulkResponse bulkResponse = builder.get(); assertThat(bulkResponse.hasFailures(), is(expectFailure)); assertThat(bulkResponse.getItems().length, is(bulkEntryCount)); for (int i = 0; i < bulkEntryCount; i++) { assertThat(bulkResponse.getItems()[i].isFailed(), is(expectedFailures[i])); } } // issue 6630 public void testThatFailedUpdateRequestReturnsCorrectType() throws Exception { BulkResponse indexBulkItemResponse = client().prepareBulk() .add(new IndexRequest("test").id("3").source("{ \"title\" : \"Great Title of doc 3\" }", XContentType.JSON)) .add(new IndexRequest("test").id("4").source("{ \"title\" : \"Great Title of doc 4\" }", XContentType.JSON)) .add(new IndexRequest("test").id("5").source("{ \"title\" : \"Great Title of doc 5\" }", XContentType.JSON)) .add(new IndexRequest("test").id("6").source("{ \"title\" : \"Great Title of doc 6\" }", XContentType.JSON)) .setRefreshPolicy(RefreshPolicy.IMMEDIATE) .get(); assertNoFailures(indexBulkItemResponse); BulkResponse bulkItemResponse = client().prepareBulk() .add(new IndexRequest("test").id("1").source("{ \"title\" : \"Great Title of doc 1\" }", XContentType.JSON)) .add(new IndexRequest("test").id("2").source("{ \"title\" : \"Great Title of doc 2\" }", XContentType.JSON)) .add(new UpdateRequest("test", "3").doc("{ \"date\" : \"2014-01-30T23:59:57\"}", XContentType.JSON)) .add(new UpdateRequest("test", "4").doc("{ \"date\" : \"2014-13-30T23:59:57\"}", XContentType.JSON)) .add(new DeleteRequest("test", "5")) .add(new DeleteRequest("test", "6")) .get(); assertNoFailures(indexBulkItemResponse); assertThat(bulkItemResponse.getItems().length, is(6)); assertThat(bulkItemResponse.getItems()[0].getOpType(), is(OpType.INDEX)); assertThat(bulkItemResponse.getItems()[1].getOpType(), is(OpType.INDEX)); assertThat(bulkItemResponse.getItems()[2].getOpType(), is(OpType.UPDATE)); assertThat(bulkItemResponse.getItems()[3].getOpType(), is(OpType.UPDATE)); assertThat(bulkItemResponse.getItems()[4].getOpType(), is(OpType.DELETE)); assertThat(bulkItemResponse.getItems()[5].getOpType(), is(OpType.DELETE)); } private static String indexOrAlias() { return randomBoolean() ? "test" : "alias"; } // issue 6410 public void testThatMissingIndexDoesNotAbortFullBulkRequest() throws Exception { createIndex("bulkindex1", "bulkindex2"); BulkRequest bulkRequest = new BulkRequest(); bulkRequest.add(new IndexRequest("bulkindex1").id("1").source(Requests.INDEX_CONTENT_TYPE, "text", "hallo1")) .add(new IndexRequest("bulkindex2").id("1").source(Requests.INDEX_CONTENT_TYPE, "text", "hallo2")) .add(new IndexRequest("bulkindex2").source(Requests.INDEX_CONTENT_TYPE, "text", "hallo2")) .add(new UpdateRequest("bulkindex2", "2").doc(Requests.INDEX_CONTENT_TYPE, "foo", "bar")) .add(new DeleteRequest("bulkindex2", "3")) .setRefreshPolicy(RefreshPolicy.IMMEDIATE); client().bulk(bulkRequest).get(); assertHitCount(prepareSearch("bulkindex*"), 3); assertBusy(() -> assertAcked(indicesAdmin().prepareClose("bulkindex2"))); BulkRequest bulkRequest2 = new BulkRequest(); bulkRequest2.add(new IndexRequest("bulkindex1").id("1").source(Requests.INDEX_CONTENT_TYPE, "text", "hallo1")) .add(new IndexRequest("bulkindex2").id("1").source(Requests.INDEX_CONTENT_TYPE, "text", "hallo2")) .add(new IndexRequest("bulkindex2").source(Requests.INDEX_CONTENT_TYPE, "text", "hallo2")) .add(new UpdateRequest("bulkindex2", "2").doc(Requests.INDEX_CONTENT_TYPE, "foo", "bar")) .add(new DeleteRequest("bulkindex2", "3")) .setRefreshPolicy(RefreshPolicy.IMMEDIATE); BulkResponse bulkResponse = client().bulk(bulkRequest2).get(); assertThat(bulkResponse.hasFailures(), is(true)); assertThat(bulkResponse.getItems().length, is(5)); } // issue 9821 public void testFailedRequestsOnClosedIndex() throws Exception { createIndex("bulkindex1"); prepareIndex("bulkindex1").setId("1").setSource("text", "test").get(); assertBusy(() -> assertAcked(indicesAdmin().prepareClose("bulkindex1"))); BulkRequest bulkRequest = new BulkRequest().setRefreshPolicy(RefreshPolicy.IMMEDIATE); bulkRequest.add(new IndexRequest("bulkindex1").id("1").source(Requests.INDEX_CONTENT_TYPE, "text", "hallo1")) .add(new UpdateRequest("bulkindex1", "1").doc(Requests.INDEX_CONTENT_TYPE, "foo", "bar")) .add(new DeleteRequest("bulkindex1", "1")); BulkResponse bulkResponse = client().bulk(bulkRequest).get(); assertThat(bulkResponse.hasFailures(), is(true)); BulkItemResponse[] responseItems = bulkResponse.getItems(); assertThat(responseItems.length, is(3)); assertThat(responseItems[0].getOpType(), is(OpType.INDEX)); assertThat(responseItems[0].getFailure().getCause(), instanceOf(IndexClosedException.class)); assertThat(responseItems[1].getOpType(), is(OpType.UPDATE)); assertThat(responseItems[1].getFailure().getCause(), instanceOf(IndexClosedException.class)); assertThat(responseItems[2].getOpType(), is(OpType.DELETE)); assertThat(responseItems[2].getFailure().getCause(), instanceOf(IndexClosedException.class)); } // issue 9821 public void testInvalidIndexNamesCorrectOpType() { BulkResponse bulkResponse = client().prepareBulk() .add(prepareIndex("INVALID.NAME").setId("1").setSource(Requests.INDEX_CONTENT_TYPE, "field", 1)) .add(client().prepareUpdate().setIndex("INVALID.NAME").setId("1").setDoc(Requests.INDEX_CONTENT_TYPE, "field", randomInt())) .add(client().prepareDelete().setIndex("INVALID.NAME").setId("1")) .get(); assertThat(bulkResponse.getItems().length, is(3)); assertThat(bulkResponse.getItems()[0].getOpType(), is(OpType.INDEX)); assertThat(bulkResponse.getItems()[1].getOpType(), is(OpType.UPDATE)); assertThat(bulkResponse.getItems()[2].getOpType(), is(OpType.DELETE)); } public void testNoopUpdate() { String indexName = "test"; createIndex(indexName, Settings.builder().put(IndexMetadata.SETTING_NUMBER_OF_REPLICAS, 1).build()); internalCluster().ensureAtLeastNumDataNodes(2); ensureGreen(indexName); DocWriteResponse doc = index(indexName, "1", Map.of("user", "xyz")); assertThat(doc.getShardInfo().getSuccessful(), equalTo(2)); final BulkResponse bulkResponse = client().prepareBulk() .add(new UpdateRequest().index(indexName).id("1").detectNoop(true).doc("user", "xyz")) // noop update .add(new UpdateRequest().index(indexName).id("2").docAsUpsert(false).doc("f", "v")) // not_found update .add(new DeleteRequest().index(indexName).id("2")) // not_found delete .get(); assertThat(bulkResponse.getItems(), arrayWithSize(3)); final BulkItemResponse noopUpdate = bulkResponse.getItems()[0]; assertThat(noopUpdate.getResponse().getResult(), equalTo(DocWriteResponse.Result.NOOP)); assertThat(Strings.toString(noopUpdate), noopUpdate.getResponse().getShardInfo().getSuccessful(), equalTo(2)); final BulkItemResponse notFoundUpdate = bulkResponse.getItems()[1]; assertNotNull(notFoundUpdate.getFailure()); final BulkItemResponse notFoundDelete = bulkResponse.getItems()[2]; assertThat(notFoundDelete.getResponse().getResult(), equalTo(DocWriteResponse.Result.NOT_FOUND)); assertThat(Strings.toString(notFoundDelete), notFoundDelete.getResponse().getShardInfo().getSuccessful(), equalTo(2)); } }
CustomScriptPlugin
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/processor/ValidationTest.java
{ "start": 1256, "end": 2219 }
class ____ extends ContextTestSupport { protected final Processor validator = new MyValidator(); protected MockEndpoint validEndpoint; protected MockEndpoint invalidEndpoint; @Test public void testValidMessage() throws Exception { validEndpoint.expectedMessageCount(1); invalidEndpoint.expectedMessageCount(0); Object result = template.requestBodyAndHeader("direct:start", "<valid/>", "foo", "bar"); assertEquals("validResult", result); assertMockEndpointsSatisfied(); } @Test public void testInvalidMessage() throws Exception { validEndpoint.expectedMessageCount(0); invalidEndpoint.expectedMessageCount(1); try { template.sendBodyAndHeader("direct:start", "<invalid/>", "foo", "notMatchedHeaderValue"); } catch (RuntimeCamelException e) { // the expected empty catch block here is not intended for this //
ValidationTest
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/deser/enums/EnumSetPolymorphicDeser4214Test.java
{ "start": 601, "end": 657 }
enum ____ { ITEM_A, ITEM_B; } static
MyEnum
java
quarkusio__quarkus
integration-tests/test-extension/extension/deployment/src/test/java/io/quarkus/commandmode/launch/IgnorePrivateMainCommandModeTestCase.java
{ "start": 1149, "end": 1293 }
class ____ { protected void main() { System.out.println("Hello World"); } } public static
HelloWorldSuperSuper
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/jpa/boot/internal/MergedSettings.java
{ "start": 696, "end": 2437 }
class ____ { private final Map<String, Object> configurationValues = new ConcurrentHashMap<>(16, 0.75f, 1); private List<CacheRegionDefinition> cacheRegionDefinitions; /** * {@code MergedSettings} is initialized with {@code hibernate.properties} */ MergedSettings() { getConfigurationValues().putAll( PropertiesHelper.map( Environment.getProperties() ) ); } List<CacheRegionDefinition> getCacheRegionDefinitions() { return cacheRegionDefinitions; } void processPersistenceUnitDescriptorProperties(PersistenceUnitDescriptor persistenceUnit) { final Properties properties = persistenceUnit.getProperties(); if ( properties != null ) { getConfigurationValues().putAll( PropertiesHelper.map( properties ) ); } getConfigurationValues().put( PERSISTENCE_UNIT_NAME, persistenceUnit.getName() ); } void processHibernateConfigXmlResources(LoadedConfig loadedConfig) { if ( !getConfigurationValues().containsKey( SESSION_FACTORY_NAME) ) { // there is not already a SF-name in the merged settings final String sessionFactoryName = loadedConfig.getSessionFactoryName(); if ( sessionFactoryName != null ) { // but the cfg.xml file we are processing named one getConfigurationValues().put( SESSION_FACTORY_NAME, sessionFactoryName ); } } // else { // make sure they match? // } getConfigurationValues().putAll( loadedConfig.getConfigurationValues() ); } public Map<String, Object> getConfigurationValues() { return configurationValues; } void addCacheRegionDefinition(CacheRegionDefinition cacheRegionDefinition) { if ( cacheRegionDefinitions == null ) { cacheRegionDefinitions = new ArrayList<>(); } cacheRegionDefinitions.add( cacheRegionDefinition ); } }
MergedSettings
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/SseEmitter.java
{ "start": 4516, "end": 5327 }
interface ____ { /** * Add an SSE "id" line. */ SseEventBuilder id(String id); /** * Add an SSE "event" line. */ SseEventBuilder name(String eventName); /** * Add an SSE "retry" line. */ SseEventBuilder reconnectTime(long reconnectTimeMillis); /** * Add an SSE "comment" line. */ SseEventBuilder comment(String comment); /** * Add an SSE "data" line. */ SseEventBuilder data(Object object); /** * Add an SSE "data" line. */ SseEventBuilder data(Object object, @Nullable MediaType mediaType); /** * Return one or more Object-MediaType pairs to write via * {@link #send(Object, MediaType)}. * @since 4.2.3 */ Set<DataWithMediaType> build(); } /** * Default implementation of SseEventBuilder. */ private static
SseEventBuilder
java
apache__kafka
streams/src/main/java/org/apache/kafka/streams/TopologyDescription.java
{ "start": 4110, "end": 4953 }
interface ____ { /** * The name of the node. Will never be {@code null}. * @return the name of the node */ @SuppressWarnings("unused") String name(); /** * The predecessors of this node within a sub-topology. * Note, sources do not have any predecessors. * Will never be {@code null}. * @return set of all predecessors */ @SuppressWarnings("unused") Set<Node> predecessors(); /** * The successor of this node within a sub-topology. * Note, sinks do not have any successors. * Will never be {@code null}. * @return set of all successor */ @SuppressWarnings("unused") Set<Node> successors(); } /** * A source node of a topology. */
Node
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/subclassmapping/fixture/SubSourceOverride.java
{ "start": 211, "end": 506 }
class ____ extends ImplementedParentSource implements InterfaceParentSource { private final String finalValue; public SubSourceOverride(String finalValue) { this.finalValue = finalValue; } public String getFinalValue() { return finalValue; } }
SubSourceOverride
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/stereotypes/SimpleInterceptor.java
{ "start": 254, "end": 430 }
class ____ { @AroundInvoke Object mySuperCoolAroundInvoke(InvocationContext ctx) throws Exception { return "intercepted" + ctx.proceed(); } }
SimpleInterceptor
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/nested/ConstructorInjectionTestMethodScopedExtensionContextNestedTests.java
{ "start": 2673, "end": 2970 }
class ____ { final String bar; @Autowired AutowiredConstructorTests(String bar) { this.bar = bar; } @Test void nestedTest() { assertThat(foo).isEqualTo("bar"); assertThat(bar).isEqualTo("bar"); } } @Nested @SpringJUnitConfig(NestedConfig.class)
AutowiredConstructorTests
java
alibaba__nacos
config/src/main/java/com/alibaba/nacos/config/server/model/form/ConfigFormV3.java
{ "start": 979, "end": 2165 }
class ____ extends ConfigForm { private static final long serialVersionUID = 1105715502736280287L; private String groupName; public String getGroupName() { return groupName; } public void setGroupName(String groupName) { this.groupName = groupName; } @Override public void validate() throws NacosApiException { if (StringUtils.isBlank(groupName)) { throw new NacosApiException(HttpStatus.BAD_REQUEST.value(), ErrorCode.PARAMETER_MISSING, "Required parameter 'groupName' type String is not present"); } super.setGroup(groupName); super.validate(); } /** * Validate for blur search API, which allow user input empty groupName and dataId to search all configs. * * @throws NacosApiException when form parameters is invalid. */ public void blurSearchValidate() throws NacosApiException { if (null == groupName) { groupName = StringUtils.EMPTY; super.setGroup(groupName); } if (null == getDataId()) { setDataId(StringUtils.EMPTY); } } }
ConfigFormV3
java
apache__camel
core/camel-api/src/main/java/org/apache/camel/cloud/ServiceExpressionFactory.java
{ "start": 1017, "end": 1091 }
interface ____ extends ServiceFactory<Expression> { }
ServiceExpressionFactory
java
quarkusio__quarkus
extensions/azure-functions/deployment/src/main/java/io/quarkus/azure/functions/deployment/AzureFunctionsDeployCommand.java
{ "start": 18749, "end": 19683 }
class ____ implements IAzureMessager, IAzureMessage.ValueDecorator { @Override public boolean show(IAzureMessage message) { switch (message.getType()) { case ALERT: case CONFIRM: case WARNING: String content = message.getContent(); log.warn(content); return true; case ERROR: log.error(message.getContent(), ((Throwable) message.getPayload())); return true; case INFO: case SUCCESS: default: log.info(message.getContent()); return true; } } @Override public String decorateValue(@Nonnull Object p, @Nullable IAzureMessage message) { return TextUtils.cyan(p.toString()); } } }
QuarkusAzureMessager
java
grpc__grpc-java
services/src/generated/test/grpc/io/grpc/reflection/testing/ReflectableServiceGrpc.java
{ "start": 5230, "end": 5595 }
class ____ implements io.grpc.BindableService, AsyncService { @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { return ReflectableServiceGrpc.bindService(this); } } /** * A stub to allow clients to do asynchronous rpc calls to service ReflectableService. */ public static final
ReflectableServiceImplBase
java
elastic__elasticsearch
x-pack/plugin/enrich/src/javaRestTest/java/org/elasticsearch/test/enrich/EnrichIT.java
{ "start": 389, "end": 652 }
class ____ extends CommonEnrichRestTestCase { @ClassRule public static ElasticsearchCluster cluster = enrichCluster("basic", false).build(); @Override protected String getTestRestCluster() { return cluster.getHttpAddresses(); } }
EnrichIT
java
apache__flink
flink-table/flink-table-planner/src/test/java/org/apache/flink/connector/source/ValuesSourceReader.java
{ "start": 1775, "end": 5827 }
class ____ implements SourceReader<RowData, ValuesSourceSplit> { private static final Logger LOG = LoggerFactory.getLogger(ValuesSourceReader.class); /** The context for this reader, to communicate with the enumerator. */ private final SourceReaderContext context; /** The availability future. This reader is available as soon as a split is assigned. */ private CompletableFuture<Void> availability; private final List<byte[]> serializedElements; private final TypeSerializer<RowData> serializer; private List<RowData> elements; /** The remaining splits that were assigned but not yet processed. */ private final Queue<ValuesSourceSplit> remainingSplits; private boolean noMoreSplits; public ValuesSourceReader( List<byte[]> serializedElements, TypeSerializer<RowData> serializer, SourceReaderContext context) { this.serializedElements = serializedElements; this.serializer = serializer; this.context = context; this.availability = new CompletableFuture<>(); this.remainingSplits = new ArrayDeque<>(); } @Override public void start() { elements = new ArrayList<>(); for (byte[] bytes : serializedElements) { try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes)) { DataInputView input = new DataInputViewStreamWrapper(bais); RowData element = serializer.deserialize(input); elements.add(element); } catch (Exception e) { throw new TableException( "Failed to deserialize an element from the source. " + "If you are using user-defined serialization (Value and Writable types), check the " + "serialization functions.\nSerializer is " + serializer, e); } } // request a split if we don't have one if (remainingSplits.isEmpty()) { context.sendSplitRequest(); } } @Override public InputStatus pollNext(ReaderOutput<RowData> output) throws Exception { ValuesSourceSplit currentSplit = remainingSplits.poll(); if (currentSplit != null) { if (currentSplit.isInfinite()) { remainingSplits.add(currentSplit); resetAvailability(); return InputStatus.NOTHING_AVAILABLE; } else { output.collect(elements.get(currentSplit.getIndex())); // request another split context.sendSplitRequest(); return InputStatus.MORE_AVAILABLE; } } else if (noMoreSplits) { return InputStatus.END_OF_INPUT; } else { resetAvailability(); return InputStatus.NOTHING_AVAILABLE; } } private void resetAvailability() { // ensure we are not called in a loop by resetting the availability future if (availability.isDone()) { availability = new CompletableFuture<>(); } } @Override public List<ValuesSourceSplit> snapshotState(long checkpointId) { return Collections.emptyList(); } @Override public CompletableFuture<Void> isAvailable() { return availability; } @Override public void addSplits(List<ValuesSourceSplit> splits) { remainingSplits.addAll(splits); // set availability so that pollNext is actually called availability.complete(null); } @Override public void notifyNoMoreSplits() { noMoreSplits = true; // set availability so that pollNext is actually called availability.complete(null); } @Override public void close() throws Exception {} @Override public void notifyCheckpointComplete(long checkpointId) throws Exception { LOG.info("checkpoint {} finished.", checkpointId); } }
ValuesSourceReader
java
quarkusio__quarkus
extensions/reactive-pg-client/deployment/src/test/java/io/quarkus/reactive/pg/client/MultipleDataSourcesTest.java
{ "start": 1772, "end": 2294 }
class ____ { @Inject @ReactiveDataSource("hibernate") Pool pgClient; public CompletionStage<Void> verify() { CompletableFuture<Void> cf = new CompletableFuture<>(); pgClient.query("SELECT 1").execute(ar -> { if (ar.failed()) { cf.completeExceptionally(ar.cause()); } else { cf.complete(null); } }); return cf; } } }
BeanUsingHibernateDataSource
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/aggfunctions/RankLikeAggFunctionBase.java
{ "start": 2330, "end": 5826 }
class ____ extends DeclarativeAggregateFunction { protected UnresolvedReferenceExpression sequence = unresolvedRef("sequence"); protected UnresolvedReferenceExpression[] lastValues; protected LogicalType[] orderKeyTypes; public RankLikeAggFunctionBase(LogicalType[] orderKeyTypes) { this.orderKeyTypes = orderKeyTypes; lastValues = new UnresolvedReferenceExpression[orderKeyTypes.length]; for (int i = 0; i < orderKeyTypes.length; ++i) { lastValues[i] = unresolvedRef("lastValue_" + i); } } @Override public int operandCount() { return orderKeyTypes.length; } @Override public DataType getResultType() { return DataTypes.BIGINT(); } @Override public Expression[] retractExpressions() { throw new TableException("This function does not support retraction."); } @Override public Expression[] mergeExpressions() { throw new TableException("This function does not support merge."); } @Override public Expression getValueExpression() { return sequence; } protected Expression orderKeyEqualsExpression() { Expression[] orderKeyEquals = new Expression[orderKeyTypes.length]; for (int i = 0; i < orderKeyTypes.length; ++i) { // pseudo code: // if (lastValue_i is null) { // if (operand(i) is null) true else false // } else { // lastValue_i equalTo orderKey(i) // } Expression lasValue = lastValues[i]; orderKeyEquals[i] = ifThenElse( isNull(lasValue), ifThenElse(isNull(operand(i)), literal(true), literal(false)), equalTo(lasValue, operand(i))); } Optional<Expression> ret = Arrays.stream(orderKeyEquals).reduce(ExpressionBuilder::and); return ret.orElseGet(() -> literal(false)); } protected Expression generateInitLiteral(LogicalType orderType) { Object value; switch (orderType.getTypeRoot()) { case BOOLEAN: value = false; break; case TINYINT: value = (byte) 0; break; case SMALLINT: value = (short) 0; break; case INTEGER: value = 0; break; case BIGINT: value = 0L; break; case FLOAT: value = 0.0f; break; case DOUBLE: value = 0.0d; break; case DECIMAL: value = BigDecimal.ZERO; break; case CHAR: case VARCHAR: value = ""; break; case DATE: value = LocalDateSerializer.INSTANCE.createInstance(); break; case TIME_WITHOUT_TIME_ZONE: value = LocalTimeSerializer.INSTANCE.createInstance(); break; case TIMESTAMP_WITHOUT_TIME_ZONE: value = LocalDateTimeSerializer.INSTANCE.createInstance(); break; default: throw new TableException("Unsupported type: " + orderType); } return valueLiteral(value, fromLogicalTypeToDataType(orderType).notNull()); } }
RankLikeAggFunctionBase
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-core/src/main/java/org/apache/hadoop/mapreduce/lib/input/UncompressedSplitLineReader.java
{ "start": 1354, "end": 3745 }
class ____ extends SplitLineReader { private boolean needAdditionalRecord = false; private long splitLength; /** Total bytes read from the input stream. */ private long totalBytesRead = 0; private boolean finished = false; private boolean usingCRLF; public UncompressedSplitLineReader(FSDataInputStream in, Configuration conf, byte[] recordDelimiterBytes, long splitLength) throws IOException { super(in, conf, recordDelimiterBytes); this.splitLength = splitLength; usingCRLF = (recordDelimiterBytes == null); } @Override protected int fillBuffer(InputStream in, byte[] buffer, boolean inDelimiter) throws IOException { int maxBytesToRead = buffer.length; if (totalBytesRead < splitLength) { long bytesLeftInSplit = splitLength - totalBytesRead; if (bytesLeftInSplit < maxBytesToRead) { maxBytesToRead = (int)bytesLeftInSplit; } } int bytesRead = in.read(buffer, 0, maxBytesToRead); // If the split ended in the middle of a record delimiter then we need // to read one additional record, as the consumer of the next split will // not recognize the partial delimiter as a record. // However if using the default delimiter and the next character is a // linefeed then next split will treat it as a delimiter all by itself // and the additional record read should not be performed. if (totalBytesRead == splitLength && inDelimiter && bytesRead > 0) { if (usingCRLF) { needAdditionalRecord = (buffer[0] != '\n'); } else { needAdditionalRecord = true; } } if (bytesRead > 0) { totalBytesRead += bytesRead; } return bytesRead; } @Override public int readLine(Text str, int maxLineLength, int maxBytesToConsume) throws IOException { int bytesRead = 0; if (!finished) { // only allow at most one more record to be read after the stream // reports the split ended if (totalBytesRead > splitLength) { finished = true; } bytesRead = super.readLine(str, maxLineLength, maxBytesToConsume); } return bytesRead; } @Override public boolean needAdditionalRecordAfterSplit() { return !finished && needAdditionalRecord; } @Override protected void unsetNeedAdditionalRecordAfterSplit() { needAdditionalRecord = false; } }
UncompressedSplitLineReader
java
elastic__elasticsearch
modules/lang-painless/src/main/java/org/elasticsearch/painless/antlr/ParserErrorStrategy.java
{ "start": 946, "end": 2927 }
class ____ extends DefaultErrorStrategy { final String sourceName; ParserErrorStrategy(String sourceName) { this.sourceName = sourceName; } @Override public void recover(final Parser recognizer, final RecognitionException re) { final Token token = re.getOffendingToken(); String message; if (token == null) { message = "no parse token found."; } else if (re instanceof InputMismatchException) { message = "unexpected token [" + getTokenErrorDisplay(token) + "]" + " was expecting one of [" + re.getExpectedTokens().toString(recognizer.getVocabulary()) + "]."; } else if (re instanceof NoViableAltException) { if (token.getType() == PainlessParser.EOF) { message = "unexpected end of script."; } else { message = "invalid sequence of tokens near [" + getTokenErrorDisplay(token) + "]."; } } else { message = "unexpected token near [" + getTokenErrorDisplay(token) + "]."; } Location location = new Location(sourceName, token == null ? -1 : token.getStartIndex()); throw location.createError(new IllegalArgumentException(message, re)); } @Override public Token recoverInline(final Parser recognizer) throws RecognitionException { final Token token = recognizer.getCurrentToken(); final String message = "unexpected token [" + getTokenErrorDisplay(token) + "]" + " was expecting one of [" + recognizer.getExpectedTokens().toString(recognizer.getVocabulary()) + "]."; Location location = new Location(sourceName, token.getStartIndex()); throw location.createError(new IllegalArgumentException(message)); } @Override public void sync(final Parser recognizer) {} }
ParserErrorStrategy
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/injection/Planner.java
{ "start": 1900, "end": 5277 }
class ____ be injected * @param requiredTypes the classes of which we need instances * @param allParameterTypes the classes that appear as the type of any parameter of any constructor we might call */ Planner(Map<Class<?>, InjectionSpec> specsByClass, Set<Class<?>> requiredTypes, Set<Class<?>> allParameterTypes) { this.requiredTypes = requiredTypes; this.plan = new ArrayList<>(); this.specsByClass = unmodifiableMap(specsByClass); this.allParameterTypes = unmodifiableSet(allParameterTypes); this.startedPlanning = new HashSet<>(); this.finishedPlanning = new HashSet<>(); this.alreadyProxied = new HashSet<>(); } /** * Intended to be called once. * <p> * Note that not all proxies are resolved once this plan has been executed. * <p> * * <em>Evolution note</em>: in a world with multiple domains/subsystems, * it will become necessary to defer proxy resolution until after other plans * have been executed, because they could create additional objects that ought * to be included in the proxies created by this plan. * * @return the {@link InjectionStep} objects listed in execution order. */ List<InjectionStep> injectionPlan() { for (Class<?> c : requiredTypes) { planForClass(c, 0); } return plan; } /** * Recursive procedure that determines what effect <code>requestedClass</code> * should have on the plan under construction. * * @param depth is used just for indenting the logs */ private void planForClass(Class<?> requestedClass, int depth) { InjectionSpec spec = specsByClass.get(requestedClass); if (spec == null) { throw new IllegalStateException("Cannot instantiate " + requestedClass + ": no specification provided"); } planForSpec(spec, depth); } private void planForSpec(InjectionSpec spec, int depth) { if (finishedPlanning.contains(spec)) { logger.trace("{}Already planned {}", indent(depth), spec); return; } logger.trace("{}Planning for {}", indent(depth), spec); if (startedPlanning.add(spec) == false) { // TODO: Better cycle detection and reporting. Use SCCs throw new IllegalStateException("Cyclic dependency involving " + spec); } if (spec instanceof MethodHandleSpec m) { for (var p : m.parameters()) { logger.trace("{}- Recursing into {} for actual parameter {}", indent(depth), p.injectableType(), p); planForClass(p.injectableType(), depth + 1); } addStep(new InstantiateStep(m), depth); } else if (spec instanceof ExistingInstanceSpec e) { logger.trace("{}- Plan {}", indent(depth), e); // Nothing to do. The injector will already have the required object. } else { throw new AssertionError("Unexpected injection spec: " + spec); } finishedPlanning.add(spec); } private void addStep(InjectionStep newStep, int depth) { logger.trace("{}- Add step {}", indent(depth), newStep); plan.add(newStep); } private static Supplier<String> indent(int depth) { return () -> "\t".repeat(depth); } }
should
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/sql/exec/manytoone/EntityWithManyToOneJoinTableTest.java
{ "start": 1316, "end": 10660 }
class ____ { @BeforeEach public void setUp(SessionFactoryScope scope) { EntityWithManyToOneJoinTable entity = new EntityWithManyToOneJoinTable( 1, "first", Integer.MAX_VALUE ); SimpleEntity other = new SimpleEntity( 2, Calendar.getInstance().getTime(), null, Integer.MAX_VALUE, Long.MAX_VALUE, null ); entity.setOther( other ); scope.inTransaction( session -> { session.persist( entity ); session.persist( other ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testSaveInDifferentTransactions(SessionFactoryScope scope) { EntityWithManyToOneJoinTable entity = new EntityWithManyToOneJoinTable( 3, "second", Integer.MAX_VALUE ); SimpleEntity other = new SimpleEntity( 4, Calendar.getInstance().getTime(), Calendar.getInstance().toInstant(), Integer.MAX_VALUE - 1, Long.MAX_VALUE, null ); entity.setOther( other ); scope.inTransaction( session -> { session.persist( other ); } ); scope.inTransaction( session -> { session.persist( entity ); } ); scope.inTransaction( session -> { final EntityWithManyToOneJoinTable loaded = session.get( EntityWithManyToOneJoinTable.class, 1 ); assert loaded != null; assertThat( loaded.getName(), equalTo( "first" ) ); assert loaded.getOther() != null; assertThat( loaded.getOther().getId(), equalTo( 2 ) ); } ); } @Test public void testHqlSelect(SessionFactoryScope scope) { final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( session -> { final EntityWithManyToOneJoinTable result = session.createQuery( "select e from EntityWithManyToOneJoinTable e where e.id = 1", EntityWithManyToOneJoinTable.class ).uniqueResult(); assertThat( result, notNullValue() ); assertThat( result.getId(), is( 1 ) ); assertThat( result.getName(), is( "first" ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); SimpleEntity other = result.getOther(); assertTrue( Hibernate.isInitialized( other ) ); assertThat( other.getSomeInteger(), is( Integer.MAX_VALUE ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); // it is null so able to initialize assertTrue( Hibernate.isInitialized( result.getLazyOther() ) ); } ); scope.inTransaction( session -> { final EntityWithManyToOneJoinTable result = session.createQuery( "select e from EntityWithManyToOneJoinTable e where e.id = 1", EntityWithManyToOneJoinTable.class ).uniqueResult(); BasicEntity basicEntity = new BasicEntity( 5, "basic" ); result.setLazyOther( basicEntity ); session.persist( basicEntity ); } ); statistics.clear(); scope.inTransaction( session -> { final EntityWithManyToOneJoinTable result = session.createQuery( "select e from EntityWithManyToOneJoinTable e where e.id = 1", EntityWithManyToOneJoinTable.class ).uniqueResult(); assertThat( result, notNullValue() ); assertThat( result.getId(), is( 1 ) ); assertThat( result.getName(), is( "first" ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); SimpleEntity other = result.getOther(); assertTrue( Hibernate.isInitialized( other ) ); assertThat( other.getSomeInteger(), is( Integer.MAX_VALUE ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); BasicEntity lazyOther = result.getLazyOther(); assertFalse( Hibernate.isInitialized( lazyOther ) ); assertThat( lazyOther.getId(), is( 5 ) ); assertThat( lazyOther.getData(), is( "basic" ) ); assertThat( statistics.getPrepareStatementCount(), is( 3L ) ); } ); } @Test public void testHqlSelectAField(SessionFactoryScope scope) { final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( session -> { final String value = session.createQuery( "select e.name from EntityWithManyToOneJoinTable e where e.other.id = 2", String.class ).uniqueResult(); assertThat( value, equalTo( "first" ) ); assertThat( statistics.getPrepareStatementCount(), is( 1L ) ); } ); } @Test public void testHqlSelectWithJoin(SessionFactoryScope scope) { final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( session -> { final EntityWithManyToOneJoinTable result = session.createQuery( "select e from EntityWithManyToOneJoinTable e join e.other where e.id = 1", EntityWithManyToOneJoinTable.class ).uniqueResult(); assertThat( result, notNullValue() ); assertThat( result.getId(), is( 1 ) ); assertThat( result.getName(), is( "first" ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); assertThat( result.getOther().getId(), is( 2 ) ); assertThat( result.getOther().getSomeInteger(), is( Integer.MAX_VALUE ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); } ); } @Test public void testHqlSelectWithJoinFetch(SessionFactoryScope scope) { final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( session -> { final EntityWithManyToOneJoinTable result = session.createQuery( "select e from EntityWithManyToOneJoinTable e join fetch e.other where e.id = 1", EntityWithManyToOneJoinTable.class ).uniqueResult(); assertThat( result, notNullValue() ); assertThat( result.getId(), is( 1 ) ); assertThat( result.getName(), is( "first" ) ); assertThat( statistics.getPrepareStatementCount(), is( 1L ) ); assertThat( result.getOther().getId(), is( 2 ) ); assertThat( result.getOther().getSomeInteger(), is( Integer.MAX_VALUE ) ); assertThat( statistics.getPrepareStatementCount(), is( 1L ) ); } ); } @Test public void testGet(SessionFactoryScope scope){ final StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( session -> { EntityWithManyToOneJoinTable result = session.get( EntityWithManyToOneJoinTable.class, 1 ); assertThat( statistics.getPrepareStatementCount(), is( 1L ) ); assertThat( result, notNullValue() ); assertThat( result.getId(), is( 1 ) ); assertTrue( Hibernate.isInitialized( result.getOther()) ); assertTrue( Hibernate.isInitialized( result.getLazyOther()) ); } ); scope.inTransaction( session -> { final EntityWithManyToOneJoinTable result = session.createQuery( "select e from EntityWithManyToOneJoinTable e where e.id = 1", EntityWithManyToOneJoinTable.class ).uniqueResult(); BasicEntity basicEntity = new BasicEntity( 5, "basic" ); result.setLazyOther( basicEntity ); session.persist( basicEntity ); } ); statistics.clear(); scope.inTransaction( session -> { final EntityWithManyToOneJoinTable result = session.createQuery( "select e from EntityWithManyToOneJoinTable e where e.id = 1", EntityWithManyToOneJoinTable.class ).uniqueResult(); assertThat( result, notNullValue() ); assertThat( result.getId(), is( 1 ) ); assertThat( result.getName(), is( "first" ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); SimpleEntity other = result.getOther(); assertTrue( Hibernate.isInitialized( other ) ); assertThat( other.getSomeInteger(), is( Integer.MAX_VALUE ) ); assertThat( statistics.getPrepareStatementCount(), is( 2L ) ); BasicEntity lazyOther = result.getLazyOther(); assertFalse( Hibernate.isInitialized( lazyOther ) ); assertThat( lazyOther.getId(), is( 5 ) ); assertThat( lazyOther.getData(), is( "basic" ) ); assertThat( statistics.getPrepareStatementCount(), is( 3L ) ); } ); } @Test public void testUpdate(SessionFactoryScope scope) { EntityWithManyToOneJoinTable entity = new EntityWithManyToOneJoinTable( 2, "second", Integer.MAX_VALUE ); SimpleEntity other = new SimpleEntity( 4, Calendar.getInstance().getTime(), null, 100, Long.MAX_VALUE, null ); entity.setOther( other ); scope.inTransaction( session -> { session.persist( other ); session.persist( entity ); } ); SimpleEntity anOther = new SimpleEntity( 5, Calendar.getInstance().getTime(), null, Integer.MIN_VALUE + 5, Long.MIN_VALUE, null ); scope.inTransaction( session -> { final EntityWithManyToOneJoinTable loaded = session.get( EntityWithManyToOneJoinTable.class, 2 ); assert loaded != null; session.persist( anOther ); loaded.setOther( anOther ); } ); scope.inTransaction( session -> { final EntityWithManyToOneJoinTable loaded = session.get( EntityWithManyToOneJoinTable.class, 2 ); assertThat( loaded.getOther(), notNullValue() ); assertThat( loaded.getOther().getId(), equalTo( 5 ) ); } ); } }
EntityWithManyToOneJoinTableTest
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-jobclient/src/test/java/org/apache/hadoop/mapred/ThreadedMapBenchmark.java
{ "start": 2673, "end": 2928 }
enum ____ { RECORDS_WRITTEN, BYTES_WRITTEN } /** * Generates random input data of given size with keys and values of given * sizes. By default it generates 128mb input data with 10 byte keys and 10 * byte values. */ public static
Counters
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/aot/AbstractAotProcessor.java
{ "start": 1162, "end": 1744 }
class ____ filesystem-based ahead-of-time (AOT) processing. * * <p>Concrete implementations should override {@link #doProcess()} that kicks * off the optimization of the target, usually an application. * * @author Stephane Nicoll * @author Andy Wilkinson * @author Phillip Webb * @author Sam Brannen * @since 6.0 * @param <T> the type of the processing result * @see FileSystemGeneratedFiles * @see FileNativeConfigurationWriter * @see org.springframework.context.aot.ContextAotProcessor * @see org.springframework.test.context.aot.TestAotProcessor */ public abstract
for
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/exc/IgnoredPropertyException.java
{ "start": 392, "end": 2173 }
class ____ extends PropertyBindingException { private static final long serialVersionUID = 1L; public IgnoredPropertyException(JsonParser p, String msg, TokenStreamLocation loc, Class<?> referringClass, String propName, Collection<Object> propertyIds) { super(p, msg, loc, referringClass, propName, propertyIds); } /** * Factory method used for constructing instances of this exception type. * * @param p Underlying parser used for reading input being used for data-binding * @param fromObjectOrClass Reference to either instance of problematic type ( * if available), or if not, type itself * @param propertyName Name of unrecognized property * @param propertyIds (optional, null if not available) Set of properties that * type would recognize, if completely known: null if set cannot be determined. */ public static IgnoredPropertyException from(JsonParser p, Object fromObjectOrClass, String propertyName, Collection<Object> propertyIds) { Class<?> ref; if (fromObjectOrClass instanceof Class<?> class1) { ref = class1; } else { // also acts as null check: ref = fromObjectOrClass.getClass(); } String msg = String.format("Ignored field \"%s\" (class %s) encountered; mapper configured not to allow this", propertyName, ref.getName()); IgnoredPropertyException e = new IgnoredPropertyException(p, msg, p.currentLocation(), ref, propertyName, propertyIds); // but let's also ensure path includes this last (missing) segment e.prependPath(fromObjectOrClass, propertyName); return e; } }
IgnoredPropertyException
java
apache__flink
flink-examples/flink-examples-table/src/main/java/org/apache/flink/table/examples/java/connectors/SocketSource.java
{ "start": 5408, "end": 5713 }
class ____ implements SourceSplit { @Override public String splitId() { return "dummy"; } } /** * Placeholder because the SocketSource does not support fault-tolerance and thus does not * require actual checkpointing. */ public static
DummySplit
java
apache__hadoop
hadoop-tools/hadoop-azure-datalake/src/test/java/org/apache/hadoop/fs/adl/live/TestAdlInternalCreateNonRecursive.java
{ "start": 1572, "end": 5325 }
class ____ { private Path inputFileName; private FsPermission inputPermission; private boolean inputOverride; private boolean inputFileAlreadyExist; private boolean inputParentAlreadyExist; private Class<IOException> expectedExceptionType; private FileSystem adlStore; public void initTestAdlInternalCreateNonRecursive(String testScenario, String fileName, FsPermission permission, boolean override, boolean fileAlreadyExist, boolean parentAlreadyExist, Class<IOException> exceptionType) throws Exception { // Random parent path for each test so that parallel execution does not fail // other running test. inputFileName = new Path( "/test/createNonRecursive/" + UUID.randomUUID().toString(), fileName); inputPermission = permission; inputFileAlreadyExist = fileAlreadyExist; inputOverride = override; inputParentAlreadyExist = parentAlreadyExist; expectedExceptionType = exceptionType; setUp(); } public static Collection adlCreateNonRecursiveTestData() throws UnsupportedEncodingException { /* Test Data File name, Permission, Override flag, File already exist, Parent already exist shouldCreateSucceed, expectedExceptionIfFileCreateFails File already exist and Parent already exist are mutually exclusive. */ return Arrays.asList(new Object[][] { {"CNR - When file do not exist.", UUID.randomUUID().toString(), FsPermission.getFileDefault(), false, false, true, null}, {"CNR - When file exist. Override false", UUID.randomUUID().toString(), FsPermission.getFileDefault(), false, true, true, FileAlreadyExistsException.class}, {"CNR - When file exist. Override true", UUID.randomUUID().toString(), FsPermission.getFileDefault(), true, true, true, null}, //TODO: This test is skipped till the fixes are not made it to prod. /*{ "CNR - When parent do no exist.", UUID.randomUUID().toString(), FsPermission.getFileDefault(), false, false, true, false, IOException.class }*/}); } public void setUp() throws Exception { assumeTrue(AdlStorageConfiguration.isContractTestEnabled()); adlStore = AdlStorageConfiguration.createStorageConnector(); } @MethodSource("adlCreateNonRecursiveTestData") @ParameterizedTest(name = "{0}") public void testCreateNonRecursiveFunctionality(String testScenario, String fileName, FsPermission permission, boolean override, boolean fileAlreadyExist, boolean parentAlreadyExist, Class<IOException> exceptionType) throws Exception { initTestAdlInternalCreateNonRecursive(testScenario, fileName, permission, override, fileAlreadyExist, parentAlreadyExist, exceptionType); if (inputFileAlreadyExist) { FileSystem.create(adlStore, inputFileName, inputPermission); } // Mutually exclusive to inputFileAlreadyExist if (inputParentAlreadyExist) { adlStore.mkdirs(inputFileName.getParent()); } else { adlStore.delete(inputFileName.getParent(), true); } try { adlStore.createNonRecursive(inputFileName, inputPermission, inputOverride, CommonConfigurationKeysPublic.IO_FILE_BUFFER_SIZE_DEFAULT, adlStore.getDefaultReplication(inputFileName), adlStore.getDefaultBlockSize(inputFileName), null); } catch (IOException e) { if (expectedExceptionType == null) { throw e; } assertEquals(expectedExceptionType, e.getClass()); return; } if (expectedExceptionType != null) { fail("CreateNonRecursive should have failed with exception " + expectedExceptionType.getName()); } } }
TestAdlInternalCreateNonRecursive
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/beanbuilder/TestBeanDefiningVisitor.java
{ "start": 978, "end": 4764 }
class ____ implements TypeElementVisitor<SomeInterceptor, AroundInvoke> { private ClassElement classElement; private Set<String> interceptorBindings = Collections.emptySet(); @Override public void visitClass(ClassElement element, VisitorContext context) { this.interceptorBindings = new HashSet<>(element.getAnnotationNamesByStereotype(AnnotationUtil.ANN_INTERCEPTOR_BINDINGS)); element.removeStereotype(AnnotationUtil.ANN_INTERCEPTOR_BINDINGS); element.removeAnnotation(AnnotationUtil.ANN_INTERCEPTOR_BINDINGS); element.annotate(Bean.class); context.getClassElement(TestBeanWithStaticCreator.class) .ifPresent(e -> element.addAssociatedBean(e) .typed(ClassElement.of(BeanWithStaticCreator.class)) .createWith(e.getEnclosedElement( ElementQuery.ALL_METHODS .onlyDeclared() .modifiers((modifiers) -> modifiers.contains(ElementModifier.STATIC)) .onlyAccessible(element) .typed((returnType) -> returnType.equals(e)) ).get() ) ); this.classElement = element; } @NonNull @Override public VisitorKind getVisitorKind() { return VisitorKind.ISOLATING; } @Override public void visitMethod(MethodElement element, VisitorContext context) { element.annotate(Executable.class); context.getClassElement(TestInterceptorAdapter.class) .ifPresent(type -> element.addAssociatedBean(type) .annotate(InterceptorBean.class) .annotate(InterceptorBindingDefinitions.class, (builder) -> { final AnnotationValue[] annotationValues = interceptorBindings.stream() .map(name -> AnnotationValue.builder(InterceptorBinding.class) .value(name) .member("kind", InterceptorKind.AROUND).build() ).toArray(AnnotationValue[]::new); builder.values(annotationValues); }) .typeArguments(classElement) .typeArgumentsForType(context.getClassElement(Supplier.class).orElse(null), classElement) .qualifier("test") .withParameters((parameters) -> { parameters[0].typeArguments(classElement); parameters[1].injectValue(element.getName()); }) .withMethods( ElementQuery.ALL_METHODS.named(name -> name.equals("testMethod")), (method) -> method.inject() .withParameters((parameters) -> parameters[1].injectValue("test") ) ) .withFields( ElementQuery.ALL_FIELDS.typed((ce) -> ce.isAssignable(Environment.class)), BeanFieldElement::inject ) ); } }
TestBeanDefiningVisitor
java
apache__camel
components/camel-jcache/src/test/java/org/apache/camel/component/jcache/support/HazelcastTest.java
{ "start": 1367, "end": 1453 }
interface ____ { String value() default "classpath:hazelcast.xml";
HazelcastTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/analysis/Analyzer.java
{ "start": 75845, "end": 77357 }
class ____ extends ParameterizedAnalyzerRule<LogicalPlan, AnalyzerContext> { @Override protected LogicalPlan rule(LogicalPlan plan, AnalyzerContext context) { // Allow resolving snapshot-only functions, but do not include them in the documentation final EsqlFunctionRegistry snapshotRegistry = context.functionRegistry().snapshotRegistry(); return plan.transformExpressionsOnly( UnresolvedFunction.class, uf -> resolveFunction(uf, context.configuration(), snapshotRegistry) ); } public static org.elasticsearch.xpack.esql.core.expression.function.Function resolveFunction( UnresolvedFunction uf, Configuration configuration, EsqlFunctionRegistry functionRegistry ) { org.elasticsearch.xpack.esql.core.expression.function.Function f = null; if (uf.analyzed()) { f = uf; } else { String functionName = functionRegistry.resolveAlias(uf.name()); if (functionRegistry.functionExists(functionName) == false) { f = uf.missing(functionName, functionRegistry.listFunctions()); } else { FunctionDefinition def = functionRegistry.resolveFunction(functionName); f = uf.buildResolved(configuration, def); } } return f; } } private static
ResolveFunctions
java
spring-projects__spring-boot
core/spring-boot-test/src/test/java/org/springframework/boot/test/context/SpringBootContextLoaderTests.java
{ "start": 15703, "end": 15892 }
class ____ { } @SpringBootTest(classes = ConfigWithPackagePrivateMain.class, useMainMethod = UseMainMethod.WHEN_AVAILABLE) static
UsePublicParameterlessMainMethodWhenAvailableAndMainMethod
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/validators/BaseTypeParser.java
{ "start": 951, "end": 1716 }
class ____ { public String signature; public String backpressureKind; public String schedulerKind; public String javadoc; public String backpressureDocumentation; public String schedulerDocumentation; public int javadocLine; public int methodLine; public int backpressureDocLine; public int schedulerDocLine; } public static List<RxMethod> parse(File f, String baseClassName) throws Exception { List<RxMethod> list = new ArrayList<>(); StringBuilder b = JavadocForAnnotations.readFile(f); int baseIndex = b.indexOf("public abstract class " + baseClassName); if (baseIndex < 0) { throw new AssertionError("Wrong base
RxMethod
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/utils/persistence/LimitAwareBulkIndexerTests.java
{ "start": 818, "end": 3386 }
class ____ extends ESTestCase { private List<BulkRequest> executedBulkRequests = new ArrayList<>(); public void testAddAndExecuteIfNeeded_GivenRequestsReachingBytesLimit() { try (LimitAwareBulkIndexer bulkIndexer = createIndexer(100)) { bulkIndexer.addAndExecuteIfNeeded(mockIndexRequest(50)); assertThat(executedBulkRequests, is(empty())); bulkIndexer.addAndExecuteIfNeeded(mockIndexRequest(50)); assertThat(executedBulkRequests, is(empty())); bulkIndexer.addAndExecuteIfNeeded(mockIndexRequest(50)); assertThat(executedBulkRequests, hasSize(1)); assertThat(executedBulkRequests.get(0).numberOfActions(), equalTo(2)); bulkIndexer.addAndExecuteIfNeeded(mockIndexRequest(50)); assertThat(executedBulkRequests, hasSize(1)); bulkIndexer.addAndExecuteIfNeeded(mockIndexRequest(50)); assertThat(executedBulkRequests, hasSize(2)); assertThat(executedBulkRequests.get(1).numberOfActions(), equalTo(2)); } assertThat(executedBulkRequests, hasSize(3)); assertThat(executedBulkRequests.get(2).numberOfActions(), equalTo(1)); } public void testAddAndExecuteIfNeeded_GivenRequestsReachingBatchSize() { try (LimitAwareBulkIndexer bulkIndexer = createIndexer(10000)) { for (int i = 0; i < 1000; i++) { bulkIndexer.addAndExecuteIfNeeded(mockIndexRequest(1)); } assertThat(executedBulkRequests, is(empty())); bulkIndexer.addAndExecuteIfNeeded(mockIndexRequest(1)); assertThat(executedBulkRequests, hasSize(1)); assertThat(executedBulkRequests.get(0).numberOfActions(), equalTo(1000)); } assertThat(executedBulkRequests, hasSize(2)); assertThat(executedBulkRequests.get(1).numberOfActions(), equalTo(1)); } public void testNoRequests() { try (LimitAwareBulkIndexer bulkIndexer = createIndexer(10000)) {} assertThat(executedBulkRequests, is(empty())); } private LimitAwareBulkIndexer createIndexer(long bytesLimit) { return new LimitAwareBulkIndexer(bytesLimit, executedBulkRequests::add); } private static IndexRequest mockIndexRequest(long ramBytes) { IndexRequest indexRequest = mock(IndexRequest.class); when(indexRequest.ramBytesUsed()).thenReturn(ramBytes); when(indexRequest.indexSource()).thenReturn(new IndexSource()); return indexRequest; } }
LimitAwareBulkIndexerTests
java
apache__thrift
lib/java/src/main/java/org/apache/thrift/protocol/TJSONProtocol.java
{ "start": 1432, "end": 1532 }
class ____ extends TProtocol { /** Factory for JSON protocol objects */ public static
TJSONProtocol
java
apache__camel
components/camel-digitalocean/src/main/java/org/apache/camel/component/digitalocean/DigitalOceanEndpoint.java
{ "start": 2924, "end": 6884 }
class ____ extends DefaultEndpoint implements EndpointServiceLocation { private static final transient Logger LOG = LoggerFactory.getLogger(DigitalOceanEndpoint.class); @UriParam private DigitalOceanConfiguration configuration; private DigitalOceanClient digitalOceanClient; public DigitalOceanEndpoint(String uri, DigitalOceanComponent component, DigitalOceanConfiguration configuration) { super(uri, component); this.configuration = configuration; } @Override public String getServiceUrl() { return "api.digitalocean.com"; } @Override public String getServiceProtocol() { return "rest"; } @Override public Producer createProducer() throws Exception { LOG.trace("Resolve producer digitalocean endpoint {{}}", configuration.getResource()); switch (configuration.getResource()) { case account: return new DigitalOceanAccountProducer(this, configuration); case actions: return new DigitalOceanActionsProducer(this, configuration); case blockStorages: return new DigitalOceanBlockStoragesProducer(this, configuration); case droplets: return new DigitalOceanDropletsProducer(this, configuration); case images: return new DigitalOceanImagesProducer(this, configuration); case snapshots: return new DigitalOceanSnapshotsProducer(this, configuration); case keys: return new DigitalOceanKeysProducer(this, configuration); case regions: return new DigitalOceanRegionsProducer(this, configuration); case sizes: return new DigitalOceanSizesProducer(this, configuration); case floatingIPs: return new DigitalOceanFloatingIPsProducer(this, configuration); case tags: return new DigitalOceanTagsProducer(this, configuration); default: throw new UnsupportedOperationException("Operation specified is not valid for producer"); } } @Override public Consumer createConsumer(Processor processor) throws Exception { throw new UnsupportedOperationException("You cannot receive messages from this endpoint"); } @Override public void doStart() throws Exception { super.doStart(); if (configuration.getDigitalOceanClient() != null) { digitalOceanClient = configuration.getDigitalOceanClient(); } else if (configuration.getHttpProxyHost() != null && configuration.getHttpProxyPort() != null) { HttpClientBuilder builder = HttpClients.custom() .useSystemProperties() .setProxy(new HttpHost(configuration.getHttpProxyHost(), configuration.getHttpProxyPort())); if (configuration.getHttpProxyUser() != null && configuration.getHttpProxyPassword() != null) { BasicCredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials( new AuthScope(configuration.getHttpProxyHost(), configuration.getHttpProxyPort()), new UsernamePasswordCredentials( configuration.getHttpProxyUser(), configuration.getHttpProxyPassword())); builder.setDefaultCredentialsProvider(credsProvider); } digitalOceanClient = new DigitalOceanClient("v2", configuration.getOAuthToken(), builder.build()); } else { digitalOceanClient = new DigitalOceanClient(configuration.getOAuthToken()); } } public DigitalOceanConfiguration getConfiguration() { return configuration; } public DigitalOceanClient getDigitalOceanClient() { return digitalOceanClient; } }
DigitalOceanEndpoint
java
alibaba__nacos
plugin-default-impl/nacos-default-auth-plugin/src/main/java/com/alibaba/nacos/plugin/auth/impl/constant/AuthSystemTypes.java
{ "start": 781, "end": 910 }
enum ____ { /** * Nacos builtin auth system. */ NACOS, /** * LDAP. */ LDAP }
AuthSystemTypes
java
google__auto
value/src/main/java/com/google/auto/value/AutoAnnotation.java
{ "start": 926, "end": 1110 }
interface ____ be generated. The * annotation is applied to a method whose return type is an annotation interface. The method can * then create and return an instance of the generated
to
java
micronaut-projects__micronaut-core
inject-groovy/src/test/groovy/io/micronaut/inject/visitor/IntroductionVisitor.java
{ "start": 919, "end": 1970 }
class ____ implements TypeElementVisitor<Stub, Object> { public static List<String> VISITED_ELEMENTS = new ArrayList<>(); public static List<ClassElement> VISITED_CLASS_ELEMENTS = new ArrayList<>(); public static List<MethodElement> VISITED_METHOD_ELEMENTS = new ArrayList<>(); @Override public void start(VisitorContext visitorContext) { VISITED_ELEMENTS.clear(); VISITED_CLASS_ELEMENTS.clear(); VISITED_METHOD_ELEMENTS.clear(); } @Override public void visitClass(ClassElement element, VisitorContext context) { visit(element); VISITED_CLASS_ELEMENTS.add(element); } @Override public void visitMethod(MethodElement element, VisitorContext context) { VISITED_METHOD_ELEMENTS.add(element); visit(element); } @Override public void visitField(FieldElement element, VisitorContext context) { visit(element); } private void visit(Element element) { VISITED_ELEMENTS.add(element.getName()); } }
IntroductionVisitor
java
elastic__elasticsearch
x-pack/plugin/ml/src/main/java/org/elasticsearch/xpack/ml/rest/calendar/RestPutCalendarJobAction.java
{ "start": 1072, "end": 1923 }
class ____ extends BaseRestHandler { @Override public List<Route> routes() { return List.of(new Route(PUT, BASE_PATH + "calendars/{" + ID + "}/jobs/{" + Job.ID + "}")); } @Override public String getName() { return "ml_put_calendar_job_action"; } @Override protected RestChannelConsumer prepareRequest(RestRequest restRequest, NodeClient client) throws IOException { String calendarId = restRequest.param(Calendar.ID.getPreferredName()); String jobId = restRequest.param(Job.ID.getPreferredName()); UpdateCalendarJobAction.Request putCalendarRequest = new UpdateCalendarJobAction.Request(calendarId, jobId, null); return channel -> client.execute(UpdateCalendarJobAction.INSTANCE, putCalendarRequest, new RestToXContentListener<>(channel)); } }
RestPutCalendarJobAction
java
netty__netty
codec-dns/src/main/java/io/netty/handler/codec/dns/DefaultDnsRecordDecoder.java
{ "start": 812, "end": 2563 }
class ____ implements DnsRecordDecoder { static final String ROOT = "."; /** * Creates a new instance. */ protected DefaultDnsRecordDecoder() { } @Override public final DnsQuestion decodeQuestion(ByteBuf in) throws Exception { String name = decodeName(in); DnsRecordType type = DnsRecordType.valueOf(in.readUnsignedShort()); int qClass = in.readUnsignedShort(); return new DefaultDnsQuestion(name, type, qClass); } @Override public final <T extends DnsRecord> T decodeRecord(ByteBuf in) throws Exception { final int startOffset = in.readerIndex(); final String name = decodeName(in); final int endOffset = in.writerIndex(); if (endOffset - in.readerIndex() < 10) { // Not enough data in.readerIndex(startOffset); return null; } final DnsRecordType type = DnsRecordType.valueOf(in.readUnsignedShort()); final int aClass = in.readUnsignedShort(); final long ttl = in.readUnsignedInt(); final int length = in.readUnsignedShort(); final int offset = in.readerIndex(); if (endOffset - offset < length) { // Not enough data in.readerIndex(startOffset); return null; } @SuppressWarnings("unchecked") T record = (T) decodeRecord(name, type, aClass, ttl, in, offset, length); in.readerIndex(offset + length); return record; } /** * Decodes a record from the information decoded so far by {@link #decodeRecord(ByteBuf)}. * * @param name the domain name of the record * @param type the type of the record * @param dnsClass the
DefaultDnsRecordDecoder
java
quarkusio__quarkus
extensions/arc/runtime/src/main/java/io/quarkus/arc/profile/IfBuildProfile.java
{ "start": 1350, "end": 1871 }
interface ____ { /** * A single profile name to enable a bean if a profile with the same name is active in Quarkus build time config. */ String value() default ""; /** * Multiple profiles names to enable a bean if all the profile names are active in Quarkus build time config. */ String[] allOf() default {}; /** * Multiple profiles names to enable a bean if any the profile names is active in Quarkus build time config. */ String[] anyOf() default {}; }
IfBuildProfile
java
apache__logging-log4j2
log4j-layout-template-json/src/main/java/org/apache/logging/log4j/layout/template/json/util/JsonWriter.java
{ "start": 2130, "end": 2283 }
class ____ no protection against recursive collections, * e.g., an array where one or more elements reference to the array itself. */ public final
provides
java
apache__camel
components/camel-hazelcast/src/test/java/org/apache/camel/component/hazelcast/HazelcastTopicConsumerTest.java
{ "start": 1636, "end": 3924 }
class ____ extends HazelcastCamelTestSupport { @Mock private ITopic<String> topic; @Captor private ArgumentCaptor<MessageListener<String>> argument; @Override protected void trainHazelcastInstance(HazelcastInstance hazelcastInstance) { when(hazelcastInstance.<String> getTopic("foo")).thenReturn(topic); when(topic.addMessageListener(any())).thenReturn(UUID.randomUUID()); } @Override @SuppressWarnings("unchecked") protected void verifyHazelcastInstance(HazelcastInstance hazelcastInstance) { verify(hazelcastInstance).getTopic("foo"); verify(topic).addMessageListener(any(MessageListener.class)); } @Test public void receive() throws InterruptedException { MockEndpoint out = getMockEndpoint("mock:received"); out.expectedMessageCount(1); verify(topic).addMessageListener(argument.capture()); final Message<String> msg = new Message<>("foo", "foo", new java.util.Date().getTime(), null); argument.getValue().onMessage(msg); MockEndpoint.assertIsSatisfied(context, 2000, TimeUnit.MILLISECONDS); this.checkHeaders(out.getExchanges().get(0).getIn().getHeaders(), HazelcastConstants.RECEIVED); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from(String.format("hazelcast-%sfoo", HazelcastConstants.TOPIC_PREFIX)).log("object...") .choice() .when(header(HazelcastConstants.LISTENER_ACTION).isEqualTo(HazelcastConstants.RECEIVED)) .log("...received").to("mock:received") .otherwise() .log("fail!"); } }; } private void checkHeaders(Map<String, Object> headers, String action) { assertEquals(action, headers.get(HazelcastConstants.LISTENER_ACTION)); assertEquals(HazelcastConstants.CACHE_LISTENER, headers.get(HazelcastConstants.LISTENER_TYPE)); assertNull(headers.get(HazelcastConstants.OBJECT_ID)); assertNotNull(headers.get(HazelcastConstants.LISTENER_TIME)); } }
HazelcastTopicConsumerTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/onetoone/bidirectional/BidirectionalOneToOneWithIdClassesTest.java
{ "start": 2343, "end": 2494 }
class ____ { @Id private String productId; @OneToOne( mappedBy = "product" ) private Price wholesalePrice; } @Embeddable public static
Product
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java
{ "start": 66638, "end": 67101 }
class ____ extends BaseFinalTransition { public LaunchFailedTransition() { super(RMAppAttemptState.FAILED); } @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { // Use diagnostic from launcher appAttempt.diagnostics.append(event.getDiagnosticMsg()); // Tell the app, scheduler super.transition(appAttempt, event); } } private static final
LaunchFailedTransition
java
apache__avro
lang/java/ipc/src/main/java/org/apache/avro/ipc/stats/Histogram.java
{ "start": 6330, "end": 6492 }
class ____<B> { public Entry(B bucket, int count) { this.bucket = bucket; this.count = count; } B bucket; int count; } private
Entry
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/test/java/org/apache/hadoop/yarn/api/TestApplicationAttemptId.java
{ "start": 1256, "end": 2771 }
class ____ { @Test void testApplicationAttemptId() { ApplicationAttemptId a1 = createAppAttemptId(10l, 1, 1); ApplicationAttemptId a2 = createAppAttemptId(10l, 1, 2); ApplicationAttemptId a3 = createAppAttemptId(10l, 2, 1); ApplicationAttemptId a4 = createAppAttemptId(8l, 1, 4); ApplicationAttemptId a5 = createAppAttemptId(10l, 1, 1); assertEquals(a1, a5); assertNotEquals(a1, a2); assertNotEquals(a1, a3); assertNotEquals(a1, a4); assertTrue(a1.compareTo(a5) == 0); assertTrue(a1.compareTo(a2) < 0); assertTrue(a1.compareTo(a3) < 0); assertTrue(a1.compareTo(a4) > 0); assertTrue(a1.hashCode() == a5.hashCode()); assertFalse(a1.hashCode() == a2.hashCode()); assertFalse(a1.hashCode() == a3.hashCode()); assertFalse(a1.hashCode() == a4.hashCode()); long ts = System.currentTimeMillis(); ApplicationAttemptId a6 = createAppAttemptId(ts, 543627, 33492611); assertEquals("appattempt_10_0001_000001", a1.toString()); assertEquals("appattempt_" + ts + "_543627_33492611", a6.toString()); } private ApplicationAttemptId createAppAttemptId( long clusterTimeStamp, int id, int attemptId) { ApplicationId appId = ApplicationId.newInstance(clusterTimeStamp, id); return ApplicationAttemptId.newInstance(appId, attemptId); } public static void main(String[] args) throws Exception { TestApplicationAttemptId t = new TestApplicationAttemptId(); t.testApplicationAttemptId(); } }
TestApplicationAttemptId
java
quarkusio__quarkus
integration-tests/smallrye-graphql/src/main/java/io/quarkus/it/smallrye/graphql/Greeting.java
{ "start": 77, "end": 682 }
class ____ extends Salutation { private String message; private LocalTime time; public Greeting() { } public Greeting(String message, LocalTime time) { this.message = message; this.time = time; } public String getMessage() { return message; } public LocalTime getTime() { return time; } public void setMessage(String message) { this.message = message; } public void setTime(LocalTime time) { this.time = time; } @Override public String getType() { return "Greet"; } }
Greeting
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/action/fieldcaps/FieldCapabilitiesIndexResponse.java
{ "start": 1090, "end": 10600 }
class ____ implements Writeable { private static final TransportVersion MAPPING_HASH_VERSION = TransportVersions.V_8_2_0; private final String indexName; @Nullable private final String indexMappingHash; private final Map<String, IndexFieldCapabilities> responseMap; private final boolean canMatch; private final transient TransportVersion originVersion; private final IndexMode indexMode; public FieldCapabilitiesIndexResponse( String indexName, @Nullable String indexMappingHash, Map<String, IndexFieldCapabilities> responseMap, boolean canMatch, IndexMode indexMode ) { this.indexName = indexName; this.indexMappingHash = indexMappingHash; this.responseMap = responseMap; this.canMatch = canMatch; this.originVersion = TransportVersion.current(); this.indexMode = indexMode; } FieldCapabilitiesIndexResponse(StreamInput in) throws IOException { this.indexName = in.readString(); this.responseMap = in.readMap(IndexFieldCapabilities::readFrom); this.canMatch = in.readBoolean(); this.originVersion = in.getTransportVersion(); if (in.getTransportVersion().onOrAfter(MAPPING_HASH_VERSION)) { this.indexMappingHash = in.readOptionalString(); } else { this.indexMappingHash = null; } if (in.getTransportVersion().onOrAfter(TransportVersions.V_8_16_0)) { this.indexMode = IndexMode.readFrom(in); } else { this.indexMode = IndexMode.STANDARD; } } @Override public void writeTo(StreamOutput out) throws IOException { out.writeString(indexName); out.writeMap(responseMap, StreamOutput::writeWriteable); out.writeBoolean(canMatch); if (out.getTransportVersion().onOrAfter(MAPPING_HASH_VERSION)) { out.writeOptionalString(indexMappingHash); } if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_16_0)) { IndexMode.writeTo(indexMode, out); } } private record CompressedGroup(String[] indices, IndexMode indexMode, String mappingHash, int[] fields) {} static List<FieldCapabilitiesIndexResponse> readList(StreamInput input) throws IOException { if (input.getTransportVersion().before(MAPPING_HASH_VERSION)) { return input.readCollectionAsList(FieldCapabilitiesIndexResponse::new); } final int ungrouped = input.readVInt(); final ArrayList<FieldCapabilitiesIndexResponse> responses = new ArrayList<>(ungrouped); for (int i = 0; i < ungrouped; i++) { responses.add(new FieldCapabilitiesIndexResponse(input)); } final int groups = input.readVInt(); if (input.getTransportVersion().onOrAfter(TransportVersions.V_8_11_X)) { collectCompressedResponses(input, groups, responses); } else { collectResponsesLegacyFormat(input, groups, responses); } return responses; } private static void collectCompressedResponses(StreamInput input, int groups, ArrayList<FieldCapabilitiesIndexResponse> responses) throws IOException { final CompressedGroup[] compressedGroups = new CompressedGroup[groups]; final boolean readIndexMode = input.getTransportVersion().onOrAfter(TransportVersions.V_8_16_0); for (int i = 0; i < groups; i++) { final String[] indices = input.readStringArray(); final IndexMode indexMode = readIndexMode ? IndexMode.readFrom(input) : IndexMode.STANDARD; final String mappingHash = input.readString(); compressedGroups[i] = new CompressedGroup(indices, indexMode, mappingHash, input.readIntArray()); } final IndexFieldCapabilities[] ifcLookup = input.readArray(IndexFieldCapabilities::readFrom, IndexFieldCapabilities[]::new); for (CompressedGroup compressedGroup : compressedGroups) { final Map<String, IndexFieldCapabilities> ifc = Maps.newMapWithExpectedSize(compressedGroup.fields.length); for (int i : compressedGroup.fields) { var val = ifcLookup[i]; ifc.put(val.name(), val); } for (String index : compressedGroup.indices) { responses.add(new FieldCapabilitiesIndexResponse(index, compressedGroup.mappingHash, ifc, true, compressedGroup.indexMode)); } } } private static void collectResponsesLegacyFormat(StreamInput input, int groups, ArrayList<FieldCapabilitiesIndexResponse> responses) throws IOException { for (int i = 0; i < groups; i++) { final List<String> indices = input.readStringCollectionAsList(); final String mappingHash = input.readString(); final Map<String, IndexFieldCapabilities> ifc = input.readMap(IndexFieldCapabilities::readFrom); for (String index : indices) { responses.add(new FieldCapabilitiesIndexResponse(index, mappingHash, ifc, true, IndexMode.STANDARD)); } } } static void writeList(StreamOutput output, List<FieldCapabilitiesIndexResponse> responses) throws IOException { if (output.getTransportVersion().before(MAPPING_HASH_VERSION)) { output.writeCollection(responses); return; } Map<String, List<FieldCapabilitiesIndexResponse>> groupedResponsesMap = new HashMap<>(); final List<FieldCapabilitiesIndexResponse> ungroupedResponses = new ArrayList<>(); for (FieldCapabilitiesIndexResponse r : responses) { if (r.canMatch && r.indexMappingHash != null) { groupedResponsesMap.computeIfAbsent(r.indexMappingHash, k -> new ArrayList<>()).add(r); } else { ungroupedResponses.add(r); } } output.writeCollection(ungroupedResponses); if (output.getTransportVersion().onOrAfter(TransportVersions.V_8_11_X)) { writeCompressedResponses(output, groupedResponsesMap); } else { writeResponsesLegacyFormat(output, groupedResponsesMap); } } private static void writeResponsesLegacyFormat( StreamOutput output, Map<String, List<FieldCapabilitiesIndexResponse>> groupedResponsesMap ) throws IOException { output.writeCollection(groupedResponsesMap.values(), (o, fieldCapabilitiesIndexResponses) -> { o.writeCollection(fieldCapabilitiesIndexResponses, (oo, r) -> oo.writeString(r.indexName)); var first = fieldCapabilitiesIndexResponses.get(0); o.writeString(first.indexMappingHash); o.writeMap(first.responseMap, StreamOutput::writeWriteable); }); } private static void writeCompressedResponses(StreamOutput output, Map<String, List<FieldCapabilitiesIndexResponse>> groupedResponsesMap) throws IOException { final Map<IndexFieldCapabilities, Integer> fieldDedupMap = new LinkedHashMap<>(); output.writeCollection(groupedResponsesMap.values(), (o, fieldCapabilitiesIndexResponses) -> { o.writeCollection(fieldCapabilitiesIndexResponses, (oo, r) -> oo.writeString(r.indexName)); var first = fieldCapabilitiesIndexResponses.get(0); if (output.getTransportVersion().onOrAfter(TransportVersions.V_8_16_0)) { IndexMode.writeTo(first.indexMode, o); } o.writeString(first.indexMappingHash); o.writeVInt(first.responseMap.size()); for (IndexFieldCapabilities ifc : first.responseMap.values()) { Integer offset = fieldDedupMap.size(); final Integer found = fieldDedupMap.putIfAbsent(ifc, offset); o.writeInt(found == null ? offset : found); } }); // this is a linked hash map so the key-set is written in insertion order, so we can just write it out in order and then read it // back as an array of FieldCapabilitiesIndexResponse in #collectCompressedResponses to use as a lookup output.writeCollection(fieldDedupMap.keySet()); } /** * Get the index name */ public String getIndexName() { return indexName; } /** * Returns the index mapping hash associated with this index if exists */ @Nullable public String getIndexMappingHash() { return indexMappingHash; } public IndexMode getIndexMode() { return indexMode; } public boolean canMatch() { return canMatch; } /** * Get the field capabilities map */ public Map<String, IndexFieldCapabilities> get() { return responseMap; } TransportVersion getOriginVersion() { return originVersion; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; FieldCapabilitiesIndexResponse that = (FieldCapabilitiesIndexResponse) o; return canMatch == that.canMatch && Objects.equals(indexName, that.indexName) && Objects.equals(indexMappingHash, that.indexMappingHash) && Objects.equals(responseMap, that.responseMap); } @Override public int hashCode() { return Objects.hash(indexName, indexMappingHash, responseMap, canMatch); } }
FieldCapabilitiesIndexResponse
java
spring-projects__spring-boot
module/spring-boot-webmvc-test/src/main/java/org/springframework/boot/webmvc/test/autoconfigure/WebDriverContextCustomizerFactory.java
{ "start": 1216, "end": 1485 }
class ____ implements ContextCustomizerFactory { @Override public ContextCustomizer createContextCustomizer(Class<?> testClass, List<ContextConfigurationAttributes> configAttributes) { return new WebDriverContextCustomizer(); } }
WebDriverContextCustomizerFactory