language
stringclasses
1 value
repo
stringclasses
60 values
path
stringlengths
22
294
class_span
dict
source
stringlengths
13
1.16M
target
stringlengths
1
113
java
quarkusio__quarkus
independent-projects/tools/registry-client/src/main/java/io/quarkus/registry/client/spi/RegistryClientFactoryProvider.java
{ "start": 247, "end": 375 }
interface ____ { RegistryClientFactory newRegistryClientFactory(RegistryClientEnvironment env); }
RegistryClientFactoryProvider
java
junit-team__junit5
junit-jupiter-engine/src/main/java/org/junit/jupiter/engine/descriptor/ClassBasedTestDescriptor.java
{ "start": 25283, "end": 26110 }
class ____ { private final List<DiscoveryIssue> discoveryIssues = new ArrayList<>(); private final List<Method> beforeAll; private final List<Method> afterAll; private final List<Method> beforeEach; private final List<Method> afterEach; LifecycleMethods(ClassInfo classInfo) { Class<?> testClass = classInfo.testClass; boolean requireStatic = classInfo.lifecycle == Lifecycle.PER_METHOD; DiscoveryIssueReporter issueReporter = DiscoveryIssueReporter.collecting(discoveryIssues); this.beforeAll = findBeforeAllMethods(testClass, requireStatic, issueReporter); this.afterAll = findAfterAllMethods(testClass, requireStatic, issueReporter); this.beforeEach = findBeforeEachMethods(testClass, issueReporter); this.afterEach = findAfterEachMethods(testClass, issueReporter); } } }
LifecycleMethods
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/SubmittedRecords.java
{ "start": 8284, "end": 14677 }
class ____ { private final Map<String, Object> partition; private final Map<String, Object> offset; private final AtomicBoolean acked; public SubmittedRecord(Map<String, Object> partition, Map<String, Object> offset) { this.partition = partition; this.offset = offset; this.acked = new AtomicBoolean(false); } /** * Acknowledge this record; signals that its offset may be safely committed. * This is safe to be called from a different thread than what called {@link SubmittedRecords#submit(SourceRecord)}. */ public void ack() { if (this.acked.compareAndSet(false, true)) { messageAcked(); } } /** * Remove this record and do not take it into account any longer when tracking offsets. * Useful if the record has been synchronously rejected by the producer. * If multiple instances of this record have been submitted already, only the first one found * (traversing from the end of the deque backward) will be removed. * <p> * This is <strong>not safe</strong> to be called from a different thread * than what called {@link SubmittedRecords#submit(SourceRecord)}. * @return whether this instance was dropped */ public boolean drop() { Deque<SubmittedRecord> deque = records.get(partition); if (deque == null) { log.warn("Attempted to remove record from submitted queue for partition {}, but no records with that partition appear to have been submitted", partition); return false; } boolean result = deque.removeLastOccurrence(this); if (deque.isEmpty()) { records.remove(partition); } if (result) { messageAcked(); } else { log.warn("Attempted to remove record from submitted queue for partition {}, but the record has not been submitted or has already been removed", partition); } return result; } private boolean acked() { return acked.get(); } private Map<String, Object> partition() { return partition; } private Map<String, Object> offset() { return offset; } } /** * Contains a snapshot of offsets that can be committed for a source task and metadata for that offset commit * (such as the number of messages for which offsets can and cannot be committed). * @param offsets the offsets that can be committed at the time of the snapshot * @param numCommittableMessages the number of committable messages at the time of the snapshot, where a * committable message is both acknowledged and not preceded by any unacknowledged * messages in the deque for its source partition * @param numUncommittableMessages the number of uncommittable messages at the time of the snapshot, where an * uncommittable message is either unacknowledged, or preceded in the deque for its * source partition by an unacknowledged message * @param numDeques the number of non-empty deques tracking uncommittable messages at the time of the snapshot * @param largestDequeSize the size of the largest deque at the time of the snapshot * @param largestDequePartition the applicable partition, which may be null, or null if there are no uncommitted * messages; it is the caller's responsibility to distinguish between these two cases * via {@link #hasPending()} */ record CommittableOffsets(Map<Map<String, Object>, Map<String, Object>> offsets, int numCommittableMessages, int numUncommittableMessages, int numDeques, int largestDequeSize, Map<String, Object> largestDequePartition) { /** * An "empty" snapshot that contains no offsets to commit and whose metadata contains no committable or uncommitable messages. */ public static final CommittableOffsets EMPTY = new CommittableOffsets(Map.of(), 0, 0, 0, 0, null); CommittableOffsets { offsets = Collections.unmodifiableMap(offsets); } /** * @return whether there were any uncommittable messages at the time of the snapshot */ public boolean hasPending() { return numUncommittableMessages > 0; } /** * @return whether there were any committable or uncommittable messages at the time of the snapshot */ public boolean isEmpty() { return numCommittableMessages == 0 && numUncommittableMessages == 0 && offsets.isEmpty(); } /** * Create a new snapshot by combining the data for this snapshot with newer data in a more recent snapshot. * Offsets are combined (giving precedence to the newer snapshot in case of conflict), the total number of * committable messages is summed across the two snapshots, and the newer snapshot's information on pending * messages (num deques, largest deque size, etc.) is used. * * @param newerOffsets the newer snapshot to combine with this snapshot * @return the new offset snapshot containing information from this snapshot and the newer snapshot; never null */ public CommittableOffsets updatedWith(CommittableOffsets newerOffsets) { Map<Map<String, Object>, Map<String, Object>> offsets = new HashMap<>(this.offsets); offsets.putAll(newerOffsets.offsets); return new CommittableOffsets( offsets, this.numCommittableMessages + newerOffsets.numCommittableMessages, newerOffsets.numUncommittableMessages, newerOffsets.numDeques, newerOffsets.largestDequeSize, newerOffsets.largestDequePartition ); } } }
SubmittedRecord
java
spring-projects__spring-security
config/src/integration-test/java/org/springframework/security/config/annotation/authentication/ldap/NamespaceLdapAuthenticationProviderTestsConfigs.java
{ "start": 1756, "end": 3284 }
class ____ { @Autowired void configure(AuthenticationManagerBuilder auth) throws Exception { // @formatter:off auth .ldapAuthentication() .groupRoleAttribute("cn") // ldap-authentication-provider@group-role-attribute .groupSearchBase("ou=groups") // ldap-authentication-provider@group-search-base .groupSearchFilter("(member={0})") // ldap-authentication-provider@group-search-filter .rolePrefix("PREFIX_") // ldap-authentication-provider@group-search-filter .userDetailsContextMapper(new PersonContextMapper()) // ldap-authentication-provider@user-context-mapper-ref / ldap-authentication-provider@user-details-class .userDnPatterns("uid={0},ou=people") // ldap-authentication-provider@user-dn-pattern .userSearchBase("ou=users") // ldap-authentication-provider@user-dn-pattern .userSearchFilter("(uid={0})") // ldap-authentication-provider@user-search-filter // .contextSource(contextSource) // ldap-authentication-provider@server-ref .contextSource() .ldif("classpath:users.xldif") // ldap-server@ldif .managerDn("uid=admin,ou=system") // ldap-server@manager-dn .managerPassword("secret") // ldap-server@manager-password .port(0) // ldap-server@port .root("dc=springframework,dc=org"); // ldap-server@root // .url("ldap://localhost:33389/dc-springframework,dc=org") this overrides root and port and is used for external // @formatter:on } } @Configuration @EnableWebSecurity static
CustomLdapAuthenticationProviderConfig
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit4/JUnitTestingUtils.java
{ "start": 1657, "end": 1763 }
class ____ use or {@code null} * if the default JUnit runner should be used * @param testClass the test
to
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/path/JSONPath_set_test5.java
{ "start": 225, "end": 642 }
class ____ extends TestCase { public void test_jsonpath_1() throws Exception { Map<String, Object> root = new HashMap<String, Object>(); JSONPath.set(root, "/a[0]/b[0]", 1001); String json = JSON.toJSONString(root); Assert.assertEquals("{\"a\":[{\"b\":[1001]}]}", json); Assert.assertEquals(1001, JSONPath.eval(root, "/a[0]/b[0]")); } }
JSONPath_set_test5
java
quarkusio__quarkus
extensions/mailer/runtime/src/main/java/io/quarkus/mailer/runtime/MailTemplateInstanceImpl.java
{ "start": 547, "end": 6147 }
class ____ implements MailTemplate.MailTemplateInstance { private final ReactiveMailer mailer; private final TemplateInstance templateInstance; private Mail mail; MailTemplateInstanceImpl(ReactiveMailer mailer, TemplateInstance templateInstance) { this.mailer = mailer; this.templateInstance = templateInstance; this.mail = new Mail(); } @Override public MailTemplateInstance mail(Mail mail) { this.mail = mail; return this; } @Override public MailTemplateInstance to(String... to) { this.mail.addTo(to); return this; } @Override public MailTemplateInstance cc(String... cc) { this.mail.addCc(cc); return this; } @Override public MailTemplateInstance bcc(String... bcc) { this.mail.addBcc(bcc); return this; } @Override public MailTemplateInstance subject(String subject) { this.mail.setSubject(subject); return this; } @Override public MailTemplateInstance from(String from) { this.mail.setFrom(from); return this; } @Override public MailTemplateInstance replyTo(String replyTo) { this.mail.setReplyTo(replyTo); return this; } @Override public MailTemplateInstance replyTo(String... replyTo) { this.mail.setReplyTo(replyTo); return this; } @Override public MailTemplateInstance bounceAddress(String bounceAddress) { this.mail.setBounceAddress(bounceAddress); return this; } @Override public MailTemplateInstance addInlineAttachment(String name, File file, String contentType, String contentId) { this.mail.addInlineAttachment(name, file, contentType, contentId); return this; } @Override public MailTemplateInstance addInlineAttachment(String name, byte[] data, String contentType, String contentId) { this.mail.addInlineAttachment(name, data, contentType, contentId); return this; } @Override public MailTemplateInstance addAttachment(String name, File file, String contentType) { this.mail.addAttachment(name, file, contentType); return this; } @Override public MailTemplateInstance addAttachment(String name, byte[] data, String contentType) { this.mail.addAttachment(name, data, contentType); return this; } @Override public MailTemplateInstance data(String key, Object value) { this.templateInstance.data(key, value); return this; } @Override public MailTemplateInstance setAttribute(String key, Object value) { this.templateInstance.setAttribute(key, value); return this; } @Override public TemplateInstance templateInstance() { return templateInstance; } @Override public Uni<Void> send() { Object variantsAttr = templateInstance.getAttribute(TemplateInstance.VARIANTS); if (variantsAttr != null) { List<Result> results = new ArrayList<>(); @SuppressWarnings("unchecked") List<Variant> variants = (List<Variant>) variantsAttr; for (Variant variant : variants) { if (variant.getContentType().equals(Variant.TEXT_HTML) || variant.getContentType().equals(Variant.TEXT_PLAIN)) { results.add(new Result(variant, Uni.createFrom().completionStage( new Supplier<CompletionStage<? extends String>>() { @Override public CompletionStage<? extends String> get() { return templateInstance .setAttribute(TemplateInstance.SELECTED_VARIANT, variant).renderAsync(); } }))); } } if (results.isEmpty()) { throw new IllegalStateException("No suitable template variant found"); } List<Uni<String>> unis = results.stream().map(Result::resolve).collect(Collectors.toList()); return Uni.combine().all().unis(unis) .combinedWith(combine(results)) .chain(new Function<Mail, Uni<? extends Void>>() { @Override public Uni<? extends Void> apply(Mail m) { return mailer.send(m); } }); } else { throw new IllegalStateException("No template variant found"); } } private Function<List<?>, Mail> combine(List<Result> results) { return new Function<List<?>, Mail>() { @Override public Mail apply(List<?> resolved) { for (int i = 0; i < resolved.size(); i++) { Result result = results.get(i); // We can safely cast, as we know that the results are Strings. String content = (String) resolved.get(i); if (result.variant.getContentType().equals(Variant.TEXT_HTML)) { mail.setHtml(content); } else if (result.variant.getContentType().equals(Variant.TEXT_PLAIN)) { mail.setText(content); } } return mail; } }; } static
MailTemplateInstanceImpl
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/locking/JoinedInheritanceOptimisticForceIncrementTest.java
{ "start": 2062, "end": 2511 }
class ____ { @Id @Column(name = "PERSON_ID") private Long id; @Version @Column(name = "ver") private Integer version; private String name; public Person() { } public Person(Long id, String name) { this.id = id; this.name = name; } public Integer getVersion() { return version; } } @Entity(name = "Employee") @PrimaryKeyJoinColumn(name = "EMPLOYEE_ID", referencedColumnName = "PERSON_ID") public static
Person
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/checkreturnvalue/CanIgnoreReturnValueSuggesterTest.java
{ "start": 7343, "end": 7851 }
class ____ { @CanIgnoreReturnValue public static StringBuilder append(StringBuilder input, String name) { input.append("name = ").append(name); return input; } } """) .doTest(); } @Test public void returnsInputParamWithMultipleReturns() { helper .addInputLines( "Client.java", """ package com.google.frobber; public final
ReturnInputParam
java
grpc__grpc-java
api/src/main/java/io/grpc/ServerCallHandler.java
{ "start": 883, "end": 2550 }
interface ____<RequestT, ResponseT> { /** * Starts asynchronous processing of an incoming call. * * <p>Callers of this method transfer their ownership of the non-thread-safe {@link ServerCall} * and {@link Metadata} arguments to the {@link ServerCallHandler} implementation for processing. * Ownership means that the implementation may invoke methods on {@code call} and {@code headers} * while {@link #startCall} runs and at any time after it returns normally. On the other hand, if * {@link #startCall} throws, ownership of {@code call} and {@code headers} reverts to the caller * and the implementation loses the right to call methods on these objects (from some other * thread, say). * * <p>Ownership also includes the responsibility to eventually close {@code call}. In particular, * if {@link #startCall} throws an exception, the caller must handle it by closing {@code call} * with an error. Since {@code call} can only be closed once, an implementation can report errors * either to {@link ServerCall#close} for itself or by throwing an exception, but not both. * * <p>Returns a non-{@code null} listener for the incoming call. Callers of this method must * arrange for events associated with {@code call} to be delivered there. * * @param call object for responding to the remote client. * @param headers request headers received from the client but open to modification by an owner * @return listener for processing incoming request messages for {@code call} */ ServerCall.Listener<RequestT> startCall( ServerCall<RequestT, ResponseT> call, Metadata headers); }
ServerCallHandler
java
spring-projects__spring-boot
module/spring-boot-http-client/src/test/java/org/springframework/boot/http/client/AbstractClientHttpRequestFactoryBuilderTests.java
{ "start": 2521, "end": 9149 }
class ____<T extends ClientHttpRequestFactory> { private static final Function<HttpMethod, HttpStatus> ALWAYS_FOUND = (method) -> HttpStatus.FOUND; private final Class<T> requestFactoryType; private final ClientHttpRequestFactoryBuilder<T> builder; AbstractClientHttpRequestFactoryBuilderTests(Class<T> requestFactoryType, ClientHttpRequestFactoryBuilder<T> builder) { this.requestFactoryType = requestFactoryType; this.builder = builder; } @Test void buildReturnsRequestFactoryOfExpectedType() { T requestFactory = this.builder.build(); assertThat(requestFactory).isInstanceOf(this.requestFactoryType); } @Test void buildWhenHasConnectTimeout() { HttpClientSettings settings = HttpClientSettings.defaults().withConnectTimeout(Duration.ofSeconds(60)); T requestFactory = this.builder.build(settings); assertThat(connectTimeout(requestFactory)).isEqualTo(Duration.ofSeconds(60).toMillis()); } @Test void buildWhenHadReadTimeout() { HttpClientSettings settings = HttpClientSettings.defaults().withReadTimeout(Duration.ofSeconds(120)); T requestFactory = this.builder.build(settings); assertThat(readTimeout(requestFactory)).isEqualTo(Duration.ofSeconds(120).toMillis()); } @ParameterizedTest @WithPackageResources("test.jks") @ValueSource(strings = { "GET", "POST" }) void connectWithSslBundle(String httpMethod) throws Exception { TomcatServletWebServerFactory webServerFactory = new TomcatServletWebServerFactory(0); webServerFactory.setSsl(ssl()); WebServer webServer = webServerFactory .getWebServer((context) -> context.addServlet("test", TestServlet.class).addMapping("/")); try { webServer.start(); int port = webServer.getPort(); URI uri = new URI("https://localhost:%s".formatted(port)); ClientHttpRequestFactory insecureRequestFactory = this.builder.build(); ClientHttpRequest insecureRequest = request(insecureRequestFactory, uri, httpMethod); assertThatExceptionOfType(SSLHandshakeException.class) .isThrownBy(() -> insecureRequest.execute().getBody()); ClientHttpRequestFactory secureRequestFactory = this.builder .build(HttpClientSettings.ofSslBundle(sslBundle())); ClientHttpRequest secureRequest = request(secureRequestFactory, uri, httpMethod); String secureResponse = StreamUtils.copyToString(secureRequest.execute().getBody(), StandardCharsets.UTF_8); assertThat(secureResponse).contains("Received " + httpMethod + " request to /"); } finally { webServer.stop(); } } @ParameterizedTest @WithPackageResources("test.jks") @ValueSource(strings = { "GET", "POST" }) void connectWithSslBundleAndOptionsMismatch(String httpMethod) throws Exception { TomcatServletWebServerFactory webServerFactory = new TomcatServletWebServerFactory(0); webServerFactory.setSsl(ssl("TLS_AES_128_GCM_SHA256")); WebServer webServer = webServerFactory .getWebServer((context) -> context.addServlet("test", TestServlet.class).addMapping("/")); try { webServer.start(); int port = webServer.getPort(); URI uri = new URI("https://localhost:%s".formatted(port)); ClientHttpRequestFactory requestFactory = this.builder.build( HttpClientSettings.ofSslBundle(sslBundle(SslOptions.of(Set.of("TLS_AES_256_GCM_SHA384"), null)))); ClientHttpRequest secureRequest = request(requestFactory, uri, httpMethod); assertThatExceptionOfType(SSLHandshakeException.class).isThrownBy(() -> secureRequest.execute().getBody()); } finally { webServer.stop(); } } @ParameterizedTest @ValueSource(strings = { "GET", "POST", "PUT", "PATCH", "DELETE" }) void redirectDefault(String httpMethod) throws Exception { testRedirect(null, HttpMethod.valueOf(httpMethod), this::getExpectedRedirect); } @ParameterizedTest @ValueSource(strings = { "GET", "POST", "PUT", "PATCH", "DELETE" }) void redirectFollow(String httpMethod) throws Exception { HttpClientSettings settings = HttpClientSettings.defaults().withRedirects(HttpRedirects.FOLLOW); testRedirect(settings, HttpMethod.valueOf(httpMethod), this::getExpectedRedirect); } @ParameterizedTest @ValueSource(strings = { "GET", "POST", "PUT", "PATCH", "DELETE" }) void redirectDontFollow(String httpMethod) throws Exception { HttpClientSettings settings = HttpClientSettings.defaults().withRedirects(HttpRedirects.DONT_FOLLOW); testRedirect(settings, HttpMethod.valueOf(httpMethod), ALWAYS_FOUND); } protected final void testRedirect(@Nullable HttpClientSettings settings, HttpMethod httpMethod, Function<HttpMethod, HttpStatus> expectedStatusForMethod) throws URISyntaxException, IOException { HttpStatus expectedStatus = expectedStatusForMethod.apply(httpMethod); TomcatServletWebServerFactory webServerFactory = new TomcatServletWebServerFactory(0); WebServer webServer = webServerFactory .getWebServer((context) -> context.addServlet("test", TestServlet.class).addMapping("/")); try { webServer.start(); int port = webServer.getPort(); URI uri = new URI("http://localhost:%s".formatted(port) + "/redirect"); ClientHttpRequestFactory requestFactory = this.builder.build(settings); ClientHttpRequest request = requestFactory.createRequest(uri, httpMethod); ClientHttpResponse response = request.execute(); assertThat(response.getStatusCode()).isEqualTo(expectedStatus); if (expectedStatus == HttpStatus.OK) { assertThat(response.getBody()).asString(StandardCharsets.UTF_8).contains("request to /redirected"); } } finally { webServer.stop(); } } private ClientHttpRequest request(ClientHttpRequestFactory factory, URI uri, String method) throws IOException { return factory.createRequest(uri, HttpMethod.valueOf(method)); } private Ssl ssl(String... ciphers) { Ssl ssl = new Ssl(); ssl.setClientAuth(ClientAuth.NEED); ssl.setKeyPassword("password"); ssl.setKeyStore("classpath:test.jks"); ssl.setTrustStore("classpath:test.jks"); if (ciphers.length > 0) { ssl.setCiphers(ciphers); } return ssl; } protected final SslBundle sslBundle() { return sslBundle(SslOptions.NONE); } protected final SslBundle sslBundle(SslOptions sslOptions) { JksSslStoreDetails storeDetails = JksSslStoreDetails.forLocation("classpath:test.jks"); JksSslStoreBundle stores = new JksSslStoreBundle(storeDetails, storeDetails); return SslBundle.of(stores, SslBundleKey.of("password"), sslOptions); } protected HttpStatus getExpectedRedirect(HttpMethod httpMethod) { return HttpStatus.OK; } protected abstract long connectTimeout(T requestFactory); protected abstract long readTimeout(T requestFactory); public static
AbstractClientHttpRequestFactoryBuilderTests
java
apache__camel
components/camel-opensearch/src/test/java/org/apache/camel/component/opensearch/integration/OpensearchScrollSearchIT.java
{ "start": 2183, "end": 8257 }
class ____ extends OpensearchTestSupport { private static final String TWITTER_OPENSEARCH_INDEX_NAME = "scroll-search"; private static final String SPLIT_TWITTER_OPENSEARCH_INDEX_NAME = "split-" + TWITTER_OPENSEARCH_INDEX_NAME; @Test void testScrollSearch() throws IOException { // add some documents for (int i = 0; i < 10; i++) { Map<String, String> map = createIndexedData(); String indexId = template().requestBody("direct:scroll-index", map, String.class); assertNotNull(indexId, "indexId should be set"); } // perform a refresh Response refreshResponse = getClient().performRequest(new Request("post", "/" + TWITTER_OPENSEARCH_INDEX_NAME + "/_refresh")); assertEquals(200, refreshResponse.getStatusLine().getStatusCode(), "Cannot perform a refresh"); SearchRequest.Builder req = getScrollSearchRequestBuilder(TWITTER_OPENSEARCH_INDEX_NAME); Exchange exchange = ExchangeBuilder.anExchange(camelContext()) .withHeader(PARAM_SCROLL_KEEP_ALIVE_MS, 50000) .withHeader(PARAM_SCROLL, true) .withBody(req) .build(); exchange = template().send("direct:scroll-search", exchange); try (OpensearchScrollRequestIterator<?> scrollRequestIterator = exchange.getIn().getBody(OpensearchScrollRequestIterator.class)) { assertNotNull(scrollRequestIterator, "response should not be null"); List<Hit<?>> result = new ArrayList<>(); scrollRequestIterator.forEachRemaining(result::add); assertEquals(10, result.size(), "response hits should be == 10"); assertEquals(11, scrollRequestIterator.getRequestCount(), "11 request should have been send to OpenSearch"); } OpensearchScrollRequestIterator<?> scrollRequestIterator = exchange.getIn().getBody(OpensearchScrollRequestIterator.class); assertTrue(scrollRequestIterator.isClosed(), "iterator should be closed"); assertEquals(11, (int) exchange.getProperty(PROPERTY_SCROLL_OPENSEARCH_QUERY_COUNT, Integer.class), "11 request should have been send to OpenSearch"); } @Test void testScrollAndSplitSearch() throws IOException, InterruptedException { // add some documents for (int i = 0; i < 10; i++) { Map<String, String> map = createIndexedData(); String indexId = template().requestBody("direct:scroll-n-split-index", map, String.class); assertNotNull(indexId, "indexId should be set"); } // perform a refresh Response refreshResponse = getClient().performRequest(new Request("post", "/" + SPLIT_TWITTER_OPENSEARCH_INDEX_NAME + "/_refresh")); assertEquals(200, refreshResponse.getStatusLine().getStatusCode(), "Cannot perform a refresh"); MockEndpoint mock = getMockEndpoint("mock:output"); mock.expectedMessageCount(1); mock.setResultWaitTime(8000); SearchRequest.Builder req = getScrollSearchRequestBuilder(SPLIT_TWITTER_OPENSEARCH_INDEX_NAME); Exchange exchange = ExchangeBuilder.anExchange(camelContext()).withBody(req).build(); exchange = template().send("direct:scroll-n-split-search", exchange); // wait for aggregation mock.assertIsSatisfied(); Iterator<Exchange> iterator = mock.getReceivedExchanges().iterator(); assertTrue(iterator.hasNext(), "response should contain 1 exchange"); Collection<?> aggregatedExchanges = iterator.next().getIn().getBody(Collection.class); assertEquals(10, aggregatedExchanges.size(), "response hits should be == 10"); OpensearchScrollRequestIterator<?> scrollRequestIterator = exchange.getIn().getBody(OpensearchScrollRequestIterator.class); assertTrue(scrollRequestIterator.isClosed(), "iterator should be closed"); assertEquals(11, scrollRequestIterator.getRequestCount(), "11 request should have been send to Opensearch"); assertEquals(11, (int) exchange.getProperty(PROPERTY_SCROLL_OPENSEARCH_QUERY_COUNT, Integer.class), "11 request should have been send to Opensearch"); } private SearchRequest.Builder getScrollSearchRequestBuilder(String indexName) { SearchRequest.Builder builder = new SearchRequest.Builder().index(indexName); builder.size(1); builder.query(new Query.Builder().matchAll(new MatchAllQuery.Builder().build()).build()); return builder; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:scroll-index") .to("opensearch://opensearch?operation=Index&indexName=" + TWITTER_OPENSEARCH_INDEX_NAME); from("direct:scroll-search") .to("opensearch://opensearch?operation=Search&indexName=" + TWITTER_OPENSEARCH_INDEX_NAME); from("direct:scroll-n-split-index") .to("opensearch://opensearch?operation=Index&indexName=" + SPLIT_TWITTER_OPENSEARCH_INDEX_NAME); from("direct:scroll-n-split-search") .to("opensearch://opensearch?" + "useScroll=true&scrollKeepAliveMs=50000&operation=Search&indexName=" + SPLIT_TWITTER_OPENSEARCH_INDEX_NAME) .split() .body() .streaming() .parallelProcessing() .threads(12) .aggregate(AggregationStrategies.groupedExchange()) .constant(true) .completionSize(20) .completionTimeout(2000) .to("mock:output") .end(); } }; } }
OpensearchScrollSearchIT
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/ResourceAlreadyUploadedException.java
{ "start": 588, "end": 880 }
class ____ extends ResourceNotFoundException { public ResourceAlreadyUploadedException(String msg, Object... args) { super(msg, args); } public ResourceAlreadyUploadedException(StreamInput in) throws IOException { super(in); } }
ResourceAlreadyUploadedException
java
spring-projects__spring-boot
module/spring-boot-mongodb/src/test/java/org/springframework/boot/data/mongodb/autoconfigure/health/MongoReactiveHealthContributorAutoConfigurationTests.java
{ "start": 1660, "end": 2874 }
class ____ { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(MongoAutoConfiguration.class, MongoReactiveAutoConfiguration.class, MongoReactiveHealthContributorAutoConfiguration.class, HealthContributorAutoConfiguration.class)); @Test void runShouldCreateIndicator() { this.contextRunner.run((context) -> assertThat(context).hasSingleBean(MongoReactiveHealthIndicator.class) .hasBean("mongoHealthContributor")); } @Test void runWithRegularIndicatorShouldOnlyCreateReactiveIndicator() { this.contextRunner.withConfiguration(AutoConfigurations.of(MongoHealthContributorAutoConfiguration.class)) .run((context) -> assertThat(context).hasSingleBean(MongoReactiveHealthIndicator.class) .hasBean("mongoHealthContributor") .doesNotHaveBean(MongoHealthIndicator.class)); } @Test void runWhenDisabledShouldNotCreateIndicator() { this.contextRunner.withPropertyValues("management.health.mongodb.enabled:false") .run((context) -> assertThat(context).doesNotHaveBean(MongoReactiveHealthIndicator.class) .doesNotHaveBean("mongoHealthContributor")); } }
MongoReactiveHealthContributorAutoConfigurationTests
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GrpcEndpointBuilderFactory.java
{ "start": 36504, "end": 43307 }
interface ____ extends EndpointConsumerBuilder { default GrpcEndpointConsumerBuilder basic() { return (GrpcEndpointConsumerBuilder) this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option is a: <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedGrpcEndpointConsumerBuilder bridgeErrorHandler(boolean bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * Allows for bridging the consumer to the Camel routing Error Handler, * which mean any exceptions (if possible) occurred while the Camel * consumer is trying to pickup incoming messages, or the likes, will * now be processed as a message and handled by the routing Error * Handler. Important: This is only possible if the 3rd party component * allows Camel to be alerted if an exception was thrown. Some * components handle this internally only, and therefore * bridgeErrorHandler is not possible. In other situations we may * improve the Camel component to hook into the 3rd party component and * make this possible for future releases. By default the consumer will * use the org.apache.camel.spi.ExceptionHandler to deal with * exceptions, that will be logged at WARN or ERROR level and ignored. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: consumer (advanced) * * @param bridgeErrorHandler the value to set * @return the dsl builder */ default AdvancedGrpcEndpointConsumerBuilder bridgeErrorHandler(String bridgeErrorHandler) { doSetProperty("bridgeErrorHandler", bridgeErrorHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option is a: <code>org.apache.camel.spi.ExceptionHandler</code> * type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedGrpcEndpointConsumerBuilder exceptionHandler(org.apache.camel.spi.ExceptionHandler exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * To let the consumer use a custom ExceptionHandler. Notice if the * option bridgeErrorHandler is enabled then this option is not in use. * By default the consumer will deal with exceptions, that will be * logged at WARN or ERROR level and ignored. * * The option will be converted to a * <code>org.apache.camel.spi.ExceptionHandler</code> type. * * Group: consumer (advanced) * * @param exceptionHandler the value to set * @return the dsl builder */ default AdvancedGrpcEndpointConsumerBuilder exceptionHandler(String exceptionHandler) { doSetProperty("exceptionHandler", exceptionHandler); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option is a: <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedGrpcEndpointConsumerBuilder exchangePattern(org.apache.camel.ExchangePattern exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets the exchange pattern when the consumer creates an exchange. * * The option will be converted to a * <code>org.apache.camel.ExchangePattern</code> type. * * Group: consumer (advanced) * * @param exchangePattern the value to set * @return the dsl builder */ default AdvancedGrpcEndpointConsumerBuilder exchangePattern(String exchangePattern) { doSetProperty("exchangePattern", exchangePattern); return this; } /** * Sets whether synchronous processing should be strictly used. * * The option is a: <code>boolean</code> type. * * Default: false * Group: advanced * * @param synchronous the value to set * @return the dsl builder */ default AdvancedGrpcEndpointConsumerBuilder synchronous(boolean synchronous) { doSetProperty("synchronous", synchronous); return this; } /** * Sets whether synchronous processing should be strictly used. * * The option will be converted to a <code>boolean</code> type. * * Default: false * Group: advanced * * @param synchronous the value to set * @return the dsl builder */ default AdvancedGrpcEndpointConsumerBuilder synchronous(String synchronous) { doSetProperty("synchronous", synchronous); return this; } } /** * Builder for endpoint producers for the gRPC component. */ public
AdvancedGrpcEndpointConsumerBuilder
java
hibernate__hibernate-orm
hibernate-testing/src/main/java/org/hibernate/testing/jdbc/JdbcSpies.java
{ "start": 11637, "end": 14685 }
class ____ implements InvocationHandler, Spy { private final DatabaseMetaData databaseMetaData; private final Connection connectionProxy; private final SpyContext context; public DatabaseMetaDataHandler( DatabaseMetaData databaseMetaData, Connection connectionProxy, SpyContext context) { this.databaseMetaData = databaseMetaData; this.connectionProxy = connectionProxy; this.context = context; } @Override public Object getSpiedInstance() { return databaseMetaData; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { switch ( method.getName() ) { case "getConnection": return context.onCall( proxy, method, args, connectionProxy ); case "toString": return context.onCall( proxy, method, args, "DatabaseMetaData proxy [@" + hashCode() + "]" ); case "hashCode": return context.onCall( proxy, method, args, hashCode() ); case "equals": return context.onCall( proxy, method, args, proxy == args[0] ); case "getProcedures": case "getProcedureColumns": case "getTables": case "getSchemas": case "getCatalogs": case "getTableTypes": case "getColumns": case "getColumnPrivileges": case "getTablePrivileges": case "getBestRowIdentifier": case "getVersionColumns": case "getPrimaryKeys": case "getImportedKeys": case "getExportedKeys": case "getCrossReference": case "getTypeInfo": case "getIndexInfo": case "getUDTs": case "getSuperTypes": case "getSuperTables": case "getAttributes": case "getClientInfoProperties": case "getFunctions": case "getFunctionColumns": case "getPseudoColumns": final ResultSet resultSet = (ResultSet) context.callOnly( databaseMetaData, method, args ); return context.onCall( proxy, method, args, getResultSetProxy( resultSet, getStatementProxy( resultSet.getStatement() ) ) ); default: return context.call( proxy, databaseMetaData, method, args ); } } protected ResultSet getResultSetProxy(ResultSet resultSet, Statement statementProxy) throws Throwable { return (ResultSet) Proxy.newProxyInstance( ClassLoader.getSystemClassLoader(), new Class[] {ResultSet.class}, new ResultSetHandler( resultSet, context, statementProxy ) ); } protected Statement getStatementProxy(Statement statement) throws Throwable { final InvocationHandler handler; if ( statement instanceof CallableStatement ) { handler = new CallableStatementHandler( (CallableStatement) statement, context, connectionProxy ); } else if ( statement instanceof PreparedStatement ) { handler = new PreparedStatementHandler( (PreparedStatement) statement, context, connectionProxy ); } else { handler = new StatementHandler( statement, context, connectionProxy ); } return (Statement) Proxy.newProxyInstance( ClassLoader.getSystemClassLoader(), new Class[] {Statement.class}, handler ); } } private static
DatabaseMetaDataHandler
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/tck/UnicastProcessorTckTest.java
{ "start": 898, "end": 1868 }
class ____ extends IdentityProcessorVerification<Integer> { public UnicastProcessorTckTest() { super(new TestEnvironment(50)); } @Override public Processor<Integer, Integer> createIdentityProcessor(int bufferSize) { UnicastProcessor<Integer> up = UnicastProcessor.create(); return new RefCountProcessor<>(up); } @Override public Publisher<Integer> createFailedPublisher() { UnicastProcessor<Integer> up = UnicastProcessor.create(); up.onError(new TestException()); return up; } @Override public ExecutorService publisherExecutorService() { return Executors.newCachedThreadPool(); } @Override public Integer createElement(int element) { return element; } @Override public long maxSupportedSubscribers() { return 1; } @Override public long maxElementsFromPublisher() { return 1024; } }
UnicastProcessorTckTest
java
alibaba__fastjson
src/test/java/com/alibaba/json/bvt/serializer/GenericTypeNotMatchTest2.java
{ "start": 522, "end": 703 }
class ____<T> { private T xid; public void setId(T id) { this.xid = id; } public T getId() { return xid; } } }
Base
java
spring-projects__spring-framework
framework-docs/src/main/java/org/springframework/docs/web/webmvc/mvcconfig/mvcconfigvalidation/WebConfiguration.java
{ "start": 1011, "end": 1223 }
class ____ implements WebMvcConfigurer { @Override public Validator getValidator() { Validator validator = new OptionalValidatorFactoryBean(); // ... return validator; } } // end::snippet[]
WebConfiguration
java
apache__dubbo
dubbo-common/src/main/java/org/apache/dubbo/config/annotation/DubboService.java
{ "start": 1508, "end": 1744 }
class ____ { * * &#64;Bean * &#64;DubboService(group="demo") * public DemoService demoServiceImpl() { * return new DemoServiceImpl(); * } * } * </pre> * * <b>2. Using on implementation
ProviderConfiguration
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/propagation/PropagatedContextImpl.java
{ "start": 7265, "end": 8746 }
class ____ avoid lambda in hot path @Override public void close() { ctx.restoreState(threadState); if (prevCtx == null) { ThreadContext.remove(); } else { ThreadContext.set(prevCtx); } } }; } return restore; } private ThreadState[] updateThreadState() { ThreadState[] threadState = new ThreadState[elements.length]; int index = 0; for (PropagatedContextElement element : elements) { if (isThreadElement(element)) { ThreadPropagatedContextElement<Object> threadPropagatedContextElement = (ThreadPropagatedContextElement<Object>) element; Object state = threadPropagatedContextElement.updateThreadContext(); threadState[index++] = new ThreadState(threadPropagatedContextElement, state); } } return threadState; } private void restoreState(ThreadState[] threadState) { for (int i = threadState.length - 1; i >= 0; i--) { ThreadState s = threadState[i]; if (s != null) { s.restore(); } } } private record ThreadState(ThreadPropagatedContextElement<Object> element, Object state) { void restore() { element.restoreThreadContext(state); } } }
to
java
apache__hadoop
hadoop-tools/hadoop-dynamometer/hadoop-dynamometer-workload/src/main/java/org/apache/hadoop/tools/dynamometer/workloadgenerator/audit/AuditReplayThread.java
{ "start": 3021, "end": 12775 }
class ____ extends SubjectInheritingThread { private static final Logger LOG = LoggerFactory.getLogger(AuditReplayThread.class); private DelayQueue<AuditReplayCommand> commandQueue; private ConcurrentMap<String, FileSystem> fsCache; private URI namenodeUri; private UserGroupInformation loginUser; private Configuration mapperConf; // If any exception is encountered it will be stored here private Exception exception; private long startTimestampMs; private boolean createBlocks; // Counters are not thread-safe so we store a local mapping in our thread // and merge them all together at the end. private Map<REPLAYCOUNTERS, Counter> replayCountersMap = new HashMap<>(); private Map<String, Counter> individualCommandsMap = new HashMap<>(); private Map<UserCommandKey, CountTimeWritable> commandLatencyMap = new HashMap<>(); AuditReplayThread(Mapper.Context mapperContext, DelayQueue<AuditReplayCommand> queue, ConcurrentMap<String, FileSystem> fsCache) throws IOException { commandQueue = queue; this.fsCache = fsCache; loginUser = UserGroupInformation.getLoginUser(); mapperConf = mapperContext.getConfiguration(); namenodeUri = URI.create(mapperConf.get(WorkloadDriver.NN_URI)); startTimestampMs = mapperConf.getLong(WorkloadDriver.START_TIMESTAMP_MS, -1); createBlocks = mapperConf.getBoolean(AuditReplayMapper.CREATE_BLOCKS_KEY, AuditReplayMapper.CREATE_BLOCKS_DEFAULT); LOG.info("Start timestamp: " + startTimestampMs); for (REPLAYCOUNTERS rc : REPLAYCOUNTERS.values()) { replayCountersMap.put(rc, new GenericCounter()); } for (ReplayCommand replayCommand : ReplayCommand.values()) { individualCommandsMap.put( replayCommand + INDIVIDUAL_COMMANDS_COUNT_SUFFIX, new GenericCounter()); individualCommandsMap.put( replayCommand + INDIVIDUAL_COMMANDS_LATENCY_SUFFIX, new GenericCounter()); individualCommandsMap.put( replayCommand + INDIVIDUAL_COMMANDS_INVALID_SUFFIX, new GenericCounter()); } } /** * Merge all of this thread's counter values into the counters contained * within the passed context. * * @param context The context holding the counters to increment. */ void drainCounters(Mapper.Context context) { for (Map.Entry<REPLAYCOUNTERS, Counter> ent : replayCountersMap .entrySet()) { context.getCounter(ent.getKey()).increment(ent.getValue().getValue()); } for (Map.Entry<String, Counter> ent : individualCommandsMap.entrySet()) { context.getCounter(INDIVIDUAL_COMMANDS_COUNTER_GROUP, ent.getKey()) .increment(ent.getValue().getValue()); } } void drainCommandLatencies(Mapper.Context context) throws InterruptedException, IOException { for (Map.Entry<UserCommandKey, CountTimeWritable> ent : commandLatencyMap.entrySet()) { context.write(ent.getKey(), ent.getValue()); } } /** * Add a command to this thread's processing queue. * * @param cmd Command to add. */ void addToQueue(AuditReplayCommand cmd) { commandQueue.put(cmd); } /** * Get the Exception that caused this thread to stop running, if any, else * null. Should not be called until this thread has already completed (i.e., * after {@link #join()} has been called). * * @return The exception which was thrown, if any. */ Exception getException() { return exception; } @Override public void work() { long currentEpoch = System.currentTimeMillis(); long delay = startTimestampMs - currentEpoch; try { if (delay > 0) { LOG.info("Sleeping for " + delay + " ms"); Thread.sleep(delay); } else { LOG.warn("Starting late by " + (-1 * delay) + " ms"); } AuditReplayCommand cmd = commandQueue.take(); while (!cmd.isPoison()) { replayCountersMap.get(REPLAYCOUNTERS.TOTALCOMMANDS).increment(1); delay = cmd.getDelay(TimeUnit.MILLISECONDS); if (delay < -5) { // allow some tolerance here replayCountersMap.get(REPLAYCOUNTERS.LATECOMMANDS).increment(1); replayCountersMap.get(REPLAYCOUNTERS.LATECOMMANDSTOTALTIME) .increment(-1 * delay); } if (!replayLog(cmd)) { replayCountersMap.get(REPLAYCOUNTERS.TOTALINVALIDCOMMANDS) .increment(1); } cmd = commandQueue.take(); } } catch (InterruptedException e) { LOG.error("Interrupted; exiting from thread.", e); } catch (Exception e) { exception = e; LOG.error("ReplayThread encountered exception; exiting.", e); } } /** * Attempt to replay the provided command. Updates counters accordingly. * * @param command The command to replay * @return True iff the command was successfully replayed (i.e., no exceptions * were thrown). */ private boolean replayLog(final AuditReplayCommand command) { final String src = command.getSrc(); final String dst = command.getDest(); FileSystem proxyFs = fsCache.get(command.getSimpleUgi()); if (proxyFs == null) { UserGroupInformation ugi = UserGroupInformation .createProxyUser(command.getSimpleUgi(), loginUser); proxyFs = ugi.doAs((PrivilegedAction<FileSystem>) () -> { try { FileSystem fs = new DistributedFileSystem(); fs.initialize(namenodeUri, mapperConf); return fs; } catch (IOException ioe) { throw new RuntimeException(ioe); } }); fsCache.put(command.getSimpleUgi(), proxyFs); } final FileSystem fs = proxyFs; ReplayCommand replayCommand; try { replayCommand = ReplayCommand .valueOf(command.getCommand().split(" ")[0].toUpperCase()); } catch (IllegalArgumentException iae) { LOG.warn("Unsupported/invalid command: " + command); replayCountersMap.get(REPLAYCOUNTERS.TOTALUNSUPPORTEDCOMMANDS) .increment(1); return false; } try { long startTime = System.currentTimeMillis(); switch (replayCommand) { case CREATE: FSDataOutputStream fsDos = fs.create(new Path(src)); if (createBlocks) { fsDos.writeByte(0); } fsDos.close(); break; case GETFILEINFO: fs.getFileStatus(new Path(src)); break; case CONTENTSUMMARY: fs.getContentSummary(new Path(src)); break; case MKDIRS: fs.mkdirs(new Path(src)); break; case RENAME: fs.rename(new Path(src), new Path(dst)); break; case LISTSTATUS: ((DistributedFileSystem) fs).getClient().listPaths(src, HdfsFileStatus.EMPTY_NAME); break; case APPEND: fs.append(new Path(src)); return true; case DELETE: fs.delete(new Path(src), true); break; case OPEN: fs.open(new Path(src)).close(); break; case SETPERMISSION: fs.setPermission(new Path(src), FsPermission.getDefault()); break; case SETOWNER: fs.setOwner(new Path(src), UserGroupInformation.getCurrentUser().getShortUserName(), UserGroupInformation.getCurrentUser().getPrimaryGroupName()); break; case SETTIMES: fs.setTimes(new Path(src), System.currentTimeMillis(), System.currentTimeMillis()); break; case SETREPLICATION: fs.setReplication(new Path(src), (short) 1); break; case CONCAT: // dst is like [path1, path2] - strip brackets and split on comma String bareDist = dst.length() < 2 ? "" : dst.substring(1, dst.length() - 1).trim(); List<Path> dsts = new ArrayList<>(); for (String s : Splitter.on(",").omitEmptyStrings().trimResults() .split(bareDist)) { dsts.add(new Path(s)); } fs.concat(new Path(src), dsts.toArray(new Path[] {})); break; default: throw new RuntimeException("Unexpected command: " + replayCommand); } long latency = System.currentTimeMillis() - startTime; UserCommandKey userCommandKey = new UserCommandKey(command.getSimpleUgi(), replayCommand.toString(), replayCommand.getType().toString()); commandLatencyMap.putIfAbsent(userCommandKey, new CountTimeWritable()); CountTimeWritable latencyWritable = commandLatencyMap.get(userCommandKey); latencyWritable.setCount(latencyWritable.getCount() + 1); latencyWritable.setTime(latencyWritable.getTime() + latency); switch (replayCommand.getType()) { case WRITE: replayCountersMap.get(REPLAYCOUNTERS.TOTALWRITECOMMANDLATENCY) .increment(latency); replayCountersMap.get(REPLAYCOUNTERS.TOTALWRITECOMMANDS).increment(1); break; case READ: replayCountersMap.get(REPLAYCOUNTERS.TOTALREADCOMMANDLATENCY) .increment(latency); replayCountersMap.get(REPLAYCOUNTERS.TOTALREADCOMMANDS).increment(1); break; default: throw new RuntimeException("Unexpected command type: " + replayCommand.getType()); } individualCommandsMap .get(replayCommand + INDIVIDUAL_COMMANDS_LATENCY_SUFFIX) .increment(latency); individualCommandsMap .get(replayCommand + INDIVIDUAL_COMMANDS_COUNT_SUFFIX).increment(1); return true; } catch (IOException e) { LOG.debug("IOException: " + e.getLocalizedMessage()); individualCommandsMap .get(replayCommand + INDIVIDUAL_COMMANDS_INVALID_SUFFIX).increment(1); return false; } } }
AuditReplayThread
java
google__truth
core/src/main/java/com/google/common/truth/OptionalSubject.java
{ "start": 960, "end": 3726 }
class ____ extends Subject { @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type private final @Nullable Optional<?> actual; private OptionalSubject( FailureMetadata failureMetadata, @SuppressWarnings("NullableOptional") // Truth always accepts nulls, no matter the type @Nullable Optional<?> actual) { super(failureMetadata, actual); this.actual = actual; } // TODO(cpovirk): Consider making OptionalIntSubject and OptionalLongSubject delegate to this. /** Checks that the actual {@link Optional} contains a value. */ public void isPresent() { if (actual == null) { failWithActual(simpleFact("expected present optional")); } else if (!actual.isPresent()) { failWithoutActual(simpleFact("expected to be present")); } } /** Checks that the actual {@link Optional} does not contain a value. */ public void isEmpty() { if (actual == null) { failWithActual(simpleFact("expected empty optional")); } else if (actual.isPresent()) { failWithoutActual( simpleFact("expected to be empty"), fact("but was present with value", actual.get())); } } /** * Checks that the actual {@link Optional} contains the given value. * * <p>To make more complex assertions on the optional's value, split your assertion in two: * * <pre>{@code * assertThat(myOptional).isPresent(); * assertThat(myOptional.get()).contains("foo"); * }</pre> */ public void hasValue(@Nullable Object expected) { if (expected == null) { failWithoutActual( simpleFact("expected an optional with a null value, but that is impossible"), fact("was", actual)); } else if (actual == null) { failWithActual("expected an optional with value", expected); } else if (!actual.isPresent()) { failWithoutActual(fact("expected to have value", expected), simpleFact("but was empty")); } else { checkNoNeedToDisplayBothValues("get()").that(actual.get()).isEqualTo(expected); } } /** * Obsolete factory instance. This factory was previously necessary for assertions like {@code * assertWithMessage(...).about(paths()).that(path)....}. Now, you can perform assertions like * that without the {@code about(...)} call. * * @deprecated Instead of {@code about(optionals()).that(...)}, use just {@code that(...)}. * Similarly, instead of {@code assertAbout(optionals()).that(...)}, use just {@code * assertThat(...)}. */ @Deprecated @SuppressWarnings("InlineMeSuggester") // We want users to remove the surrounding call entirely. public static Factory<OptionalSubject, Optional<?>> optionals() { return OptionalSubject::new; } }
OptionalSubject
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/oracle/createTable/OracleCreateTableTest5.java
{ "start": 983, "end": 2665 }
class ____ extends OracleTest { public void test_0() throws Exception { String sql = // "CREATE GLOBAL TEMPORARY TABLE \"SYS\".\"SYS_TEMP_0FD9D670A_93E068F3\" (\"C0\" VARCHAR2(30),\"C1\" VARCHAR2(27) ) " + "IN_MEMORY_METADATA CURSOR_SPECIFIC_SEGMENT STORAGE (OBJNO 4254951178 )"; OracleStatementParser parser = new OracleStatementParser(sql); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement statemen = statementList.get(0); print(statementList); assertEquals(1, statementList.size()); OracleSchemaStatVisitor visitor = new OracleSchemaStatVisitor(); statemen.accept(visitor); System.out.println("Tables : " + visitor.getTables()); System.out.println("fields : " + visitor.getColumns()); System.out.println("coditions : " + visitor.getConditions()); System.out.println("relationships : " + visitor.getRelationships()); System.out.println("orderBy : " + visitor.getOrderByColumns()); assertEquals(1, visitor.getTables().size()); assertTrue(visitor.getTables().containsKey(new TableStat.Name("SYS.SYS_TEMP_0FD9D670A_93E068F3"))); assertEquals(2, visitor.getColumns().size()); assertTrue(visitor.containsColumn("SYS.SYS_TEMP_0FD9D670A_93E068F3", "C0")); assertTrue(visitor.containsColumn("SYS.SYS_TEMP_0FD9D670A_93E068F3", "C1")); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "YEAR"))); // assertTrue(visitor.getColumns().contains(new TableStat.Column("pivot_table", "order_mode"))); } }
OracleCreateTableTest5
java
lettuce-io__lettuce-core
src/main/java/io/lettuce/core/RedisCredentials.java
{ "start": 213, "end": 2078 }
interface ____ { /** * Retrieve the Redis user, used to identify the user interacting with Redis. Can be used with Redis 6 and newer server * versions. * * @return the user name. Can be {@code null} if not set. * @see #hasUsername() */ String getUsername(); /** * Return whether the username is configured. * * @return {@code true} if the username is configured; {@code false} otherwise. */ boolean hasUsername(); /** * Retrieve the Redis password, used to authenticate the user interacting with Redis. * * @return the password. Can be {@code null} if not set. * @see #hasUsername() */ char[] getPassword(); /** * Return whether the password is configured. * * @return {@code true} if the password is configured; {@code false} otherwise */ boolean hasPassword(); /** * Create a static {@link RedisCredentials} object from {@code username} and {@code password}. * * @param username can be {@code null} * @param password can be {@code null} * @return the static {@link RedisCredentials} object from {@code username} and {@code password} */ static RedisCredentials just(String username, CharSequence password) { return new StaticRedisCredentials(username, password == null ? null : LettuceStrings.toCharArray(password)); } /** * Create a static {@link RedisCredentials} object from {@code username} and {@code password}. * * @param username can be {@code null} * @param password can be {@code null} * @return the static {@link RedisCredentials} object from {@code username} and {@code password} */ static RedisCredentials just(String username, char[] password) { return new StaticRedisCredentials(username, password); } }
RedisCredentials
java
quarkusio__quarkus
integration-tests/openapi/src/main/java/io/quarkus/it/openapi/jaxrs/PojoResource.java
{ "start": 499, "end": 2829 }
class ____ { @GET @Path("/justPojo") public Greeting justPojo() { return new Greeting(0, "justPojo"); } @POST @Path("/justPojo") public Greeting justPojo(Greeting greeting) { return greeting; } @GET @Path("/restResponsePojo") public RestResponse<Greeting> restResponsePojo() { return RestResponse.ok(new Greeting(0, "restResponsePojo")); } @POST @Path("/restResponsePojo") public RestResponse<Greeting> restResponsePojo(Greeting greeting) { return RestResponse.ok(greeting); } @GET @Path("/optionalPojo") public Optional<Greeting> optionalPojo() { return Optional.of(new Greeting(0, "optionalPojo")); } @POST @Path("/optionalPojo") public Optional<Greeting> optionalPojo(Optional<Greeting> greeting) { return greeting; } @GET @Path("/uniPojo") public Uni<Greeting> uniPojo() { return Uni.createFrom().item(new Greeting(0, "uniPojo")); } @GET @Path("/completionStagePojo") public CompletionStage<Greeting> completionStagePojo() { return CompletableFuture.completedStage(new Greeting(0, "completionStagePojo")); } @GET @Path("/completedFuturePojo") public CompletableFuture<Greeting> completedFuturePojo() { return CompletableFuture.completedFuture(new Greeting(0, "completedFuturePojo")); } @GET @Path("/listPojo") public List<Greeting> listPojo() { return Arrays.asList(new Greeting[] { new Greeting(0, "listPojo") }); } @POST @Path("/listPojo") public List<Greeting> listPojo(List<Greeting> greeting) { return greeting; } @GET @Path("/arrayPojo") public Greeting[] arrayPojo() { return new Greeting[] { new Greeting(0, "arrayPojo") }; } @POST @Path("/arrayPojo") public Greeting[] arrayPojo(Greeting[] greeting) { return greeting; } @GET @Path("/mapPojo") public Map<String, Greeting> mapPojo() { Map<String, Greeting> m = new HashMap<>(); Greeting g = new Greeting(0, "mapPojo"); m.put("mapPojo", g); return m; } @POST @Path("/mapPojo") public Map<String, Greeting> mapPojo(Map<String, Greeting> body) { return body; } }
PojoResource
java
quarkusio__quarkus
extensions/oidc/deployment/src/test/java/io/quarkus/oidc/test/ImplicitBasicAuthAndCodeFlowAuthCombinationTest.java
{ "start": 961, "end": 4586 }
class ____ { @RegisterExtension static final QuarkusDevModeTest test = new QuarkusDevModeTest() .withApplicationRoot((jar) -> jar .addClasses(BasicCodeFlowResource.class) .addAsResource( new StringAsset(""" # Disable Dev Services, we use a test resource manager quarkus.keycloak.devservices.enabled=false quarkus.security.users.embedded.enabled=true quarkus.security.users.embedded.plain-text=true quarkus.security.users.embedded.users.alice=alice quarkus.oidc.auth-server-url=${keycloak.url}/realms/quarkus quarkus.oidc.client-id=quarkus-web-app quarkus.oidc.credentials.secret=secret quarkus.oidc.application-type=web-app quarkus.http.auth.permission.code-flow.paths=/basic-code-flow/code-flow quarkus.http.auth.permission.code-flow.policy=authenticated quarkus.http.auth.permission.code-flow.auth-mechanism=code quarkus.http.auth.permission.basic.paths=/basic-code-flow/basic quarkus.http.auth.permission.basic.policy=authenticated quarkus.http.auth.permission.basic.auth-mechanism=basic """), "application.properties")); @Test public void testBasicEnabledAsSelectedWithHttpPerm() throws IOException, InterruptedException { // endpoint is annotated with 'BasicAuthentication', so basic auth must be enabled RestAssured.given().auth().basic("alice", "alice").get("/basic-code-flow/basic") .then().statusCode(204); RestAssured.given().auth().basic("alice", "alice").redirects().follow(false) .get("/basic-code-flow/code-flow").then().statusCode(302); try (final WebClient webClient = createWebClient()) { try { webClient.getPage("http://localhost:8080/basic-code-flow/basic"); fail("Exception is expected because by the basic auth is required"); } catch (FailingHttpStatusCodeException ex) { // Reported by Quarkus assertEquals(401, ex.getStatusCode()); } HtmlPage page = webClient.getPage("http://localhost:8080/basic-code-flow/code-flow"); assertEquals("Sign in to quarkus", page.getTitleText()); HtmlForm loginForm = page.getForms().get(0); loginForm.getInputByName("username").setValueAttribute("alice"); loginForm.getInputByName("password").setValueAttribute("alice"); page = loginForm.getButtonByName("login").click(); assertEquals("alice", page.getBody().asNormalizedText()); webClient.getCookieManager().clearCookies(); } } private WebClient createWebClient() { WebClient webClient = new WebClient(); webClient.setCssErrorHandler(new SilentCssErrorHandler()); return webClient; } private static String getAccessToken() { return KeycloakTestResourceLifecycleManager.getAccessToken("alice"); } @Path("basic-code-flow") public static
ImplicitBasicAuthAndCodeFlowAuthCombinationTest
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
{ "start": 104880, "end": 106415 }
class ____ implements OrderComparator.OrderSourceProvider { private final Map<Object, String> instancesToBeanNames; public FactoryAwareOrderSourceProvider(Map<Object, String> instancesToBeanNames) { this.instancesToBeanNames = instancesToBeanNames; } @Override public @Nullable Object getOrderSource(Object obj) { String beanName = this.instancesToBeanNames.get(obj); if (beanName == null) { return null; } try { BeanDefinition beanDefinition = getMergedBeanDefinition(beanName); List<Object> sources = new ArrayList<>(3); Object orderAttribute = beanDefinition.getAttribute(AbstractBeanDefinition.ORDER_ATTRIBUTE); if (orderAttribute != null) { if (orderAttribute instanceof Integer order) { sources.add((Ordered) () -> order); } else { throw new IllegalStateException("Invalid value type for attribute '" + AbstractBeanDefinition.ORDER_ATTRIBUTE + "': " + orderAttribute.getClass().getName()); } } if (beanDefinition instanceof RootBeanDefinition rootBeanDefinition) { Method factoryMethod = rootBeanDefinition.getResolvedFactoryMethod(); if (factoryMethod != null) { sources.add(factoryMethod); } Class<?> targetType = rootBeanDefinition.getTargetType(); if (targetType != null && targetType != obj.getClass()) { sources.add(targetType); } } return sources.toArray(); } catch (NoSuchBeanDefinitionException ex) { return null; } } } private
FactoryAwareOrderSourceProvider
java
apache__camel
components/camel-kamelet/src/test/java/org/apache/camel/component/kamelet/KameletLocalBeanClassTwoTest.java
{ "start": 1083, "end": 2219 }
class ____ extends CamelTestSupport { @Test public void testOne() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived("Hi John we are going to Murphys"); template.sendBody("direct:bar", "John"); MockEndpoint.assertIsSatisfied(context); } // ********************************************** // // test set-up // // ********************************************** @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { routeTemplate("whereTo") .templateBean("myBar", "#class:org.apache.camel.component.kamelet.KameletLocalBeanClassTwoTest$MyBar") .from("kamelet:source") // must use {{myBar}} to refer to the local bean .to("bean:{{myBar}}"); from("direct:bar") .kamelet("whereTo") .to("mock:result"); } }; } public static
KameletLocalBeanClassTwoTest
java
elastic__elasticsearch
server/src/test/java/org/elasticsearch/health/node/tracker/RepositoriesHealthTrackerTests.java
{ "start": 1265, "end": 4428 }
class ____ extends ESTestCase { private RepositoriesHealthTracker repositoriesHealthTracker; private RepositoriesService repositoriesService; @Before public void setUp() throws Exception { super.setUp(); repositoriesService = mock(RepositoriesService.class); repositoriesHealthTracker = new RepositoriesHealthTracker(repositoriesService); } public void testGetHealthNoRepos() { when(repositoriesService.getRepositories()).thenReturn(List.of()); var health = repositoriesHealthTracker.determineCurrentHealth(); assertTrue(health.unknownRepositories().isEmpty()); assertTrue(health.invalidRepositories().isEmpty()); } public void testGetHealthCorrectRepo() { var metadata = mock(RepositoryMetadata.class); // generation should be != RepositoryData.UNKNOWN_REPO_GEN which is equal to -2. when(metadata.generation()).thenReturn(randomNonNegativeLong()); var repo = mock(Repository.class); when(repo.getMetadata()).thenReturn(metadata); when(repositoriesService.getRepositories()).thenReturn(List.of(repo)); var health = repositoriesHealthTracker.determineCurrentHealth(); assertTrue(health.unknownRepositories().isEmpty()); assertTrue(health.invalidRepositories().isEmpty()); } public void testGetHealthUnknownType() { var repo = createRepositoryMetadata(); when(repositoriesService.getRepositories()).thenReturn(List.of(new UnknownTypeRepository(randomProjectIdOrDefault(), repo))); var health = repositoriesHealthTracker.determineCurrentHealth(); assertEquals(1, health.unknownRepositories().size()); assertEquals(repo.name(), health.unknownRepositories().get(0)); assertTrue(health.invalidRepositories().isEmpty()); } public void testGetHealthInvalid() { var repo = createRepositoryMetadata(); when(repositoriesService.getRepositories()).thenReturn( List.of(new InvalidRepository(randomProjectIdOrDefault(), repo, new RepositoryException(repo.name(), "Test"))) ); var health = repositoriesHealthTracker.determineCurrentHealth(); assertTrue(health.unknownRepositories().isEmpty()); assertEquals(1, health.invalidRepositories().size()); assertEquals(repo.name(), health.invalidRepositories().get(0)); } public void testSetBuilder() { var builder = mock(UpdateHealthInfoCacheAction.Request.Builder.class); var health = new RepositoriesHealthInfo(List.of(), List.of()); repositoriesHealthTracker.addToRequestBuilder(builder, health); verify(builder).repositoriesHealthInfo(health); } private static RepositoryMetadata createRepositoryMetadata() { var generation = randomNonNegativeLong() / 2L; return new RepositoryMetadata( randomAlphaOfLength(10), randomAlphaOfLength(10), randomAlphaOfLength(10), Settings.EMPTY, generation, generation + randomLongBetween(0, generation) ); } }
RepositoriesHealthTrackerTests
java
mockito__mockito
mockito-core/src/test/java/org/mockito/internal/util/reflection/BeanPropertySetterTest.java
{ "start": 4086, "end": 4352 }
class ____ { private File theField; boolean theFieldSetterWasUsed; public void setTheField(final File theField) { theFieldSetterWasUsed = true; this.theField = theField; } } static
SomeBeanWithJustASetter
java
mapstruct__mapstruct
core/src/main/java/org/mapstruct/Mapping.java
{ "start": 12503, "end": 13970 }
class ____ a method. * <p> * Note that {@link #defaultValue()} usage will also be converted using this qualifier. * * @return the qualifiers * @see Qualifier */ Class<? extends Annotation>[] qualifiedBy() default { }; /** * String-based form of qualifiers; When looking for a suitable mapping method for a given property, MapStruct will * only consider those methods carrying directly or indirectly (i.e. on the class-level) a {@link Named} annotation * for each of the specified qualifier names. * <p> * Note that annotation-based qualifiers are generally preferable as they allow more easily to find references and * are safe for refactorings, but name-based qualifiers can be a less verbose alternative when requiring a large * number of qualifiers as no custom annotation types are needed. * <p> * Note that {@link #defaultValue()} usage will also be converted using this qualifier. * * @return One or more qualifier name(s) * @see #qualifiedBy() * @see Named */ String[] qualifiedByName() default { }; /** * A qualifier can be specified to aid the selection process of a suitable presence check method. * This is useful in case multiple presence check methods qualify and thus would result in an * 'Ambiguous presence check methods found' error. * A qualifier is a custom annotation and can be placed on a hand written mapper
or
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/ext/MultipleExternalIds291Test.java
{ "start": 733, "end": 799 }
class ____ implements F2{ public String d; } static
D
java
spring-projects__spring-security
config/src/main/java/org/springframework/security/config/web/server/ServerHttpSecurity.java
{ "start": 97875, "end": 106160 }
class ____ { private final List<ServerHttpHeadersWriter> writers; private CacheControlServerHttpHeadersWriter cacheControl = new CacheControlServerHttpHeadersWriter(); private ContentTypeOptionsServerHttpHeadersWriter contentTypeOptions = new ContentTypeOptionsServerHttpHeadersWriter(); private StrictTransportSecurityServerHttpHeadersWriter hsts = new StrictTransportSecurityServerHttpHeadersWriter(); private XFrameOptionsServerHttpHeadersWriter frameOptions = new XFrameOptionsServerHttpHeadersWriter(); private XXssProtectionServerHttpHeadersWriter xss = new XXssProtectionServerHttpHeadersWriter(); private FeaturePolicyServerHttpHeadersWriter featurePolicy = new FeaturePolicyServerHttpHeadersWriter(); private PermissionsPolicyServerHttpHeadersWriter permissionsPolicy = new PermissionsPolicyServerHttpHeadersWriter(); private ContentSecurityPolicyServerHttpHeadersWriter contentSecurityPolicy = new ContentSecurityPolicyServerHttpHeadersWriter(); private ReferrerPolicyServerHttpHeadersWriter referrerPolicy = new ReferrerPolicyServerHttpHeadersWriter(); private CrossOriginOpenerPolicyServerHttpHeadersWriter crossOriginOpenerPolicy = new CrossOriginOpenerPolicyServerHttpHeadersWriter(); private CrossOriginEmbedderPolicyServerHttpHeadersWriter crossOriginEmbedderPolicy = new CrossOriginEmbedderPolicyServerHttpHeadersWriter(); private CrossOriginResourcePolicyServerHttpHeadersWriter crossOriginResourcePolicy = new CrossOriginResourcePolicyServerHttpHeadersWriter(); private HeaderSpec() { this.writers = new ArrayList<>(Arrays.asList(this.cacheControl, this.contentTypeOptions, this.hsts, this.frameOptions, this.xss, this.featurePolicy, this.permissionsPolicy, this.contentSecurityPolicy, this.referrerPolicy, this.crossOriginOpenerPolicy, this.crossOriginEmbedderPolicy, this.crossOriginResourcePolicy)); } /** * Disables http response headers * @return the {@link ServerHttpSecurity} to continue configuring */ public ServerHttpSecurity disable() { ServerHttpSecurity.this.headers = null; return ServerHttpSecurity.this; } /** * Configures cache control headers * @param cacheCustomizer the {@link Customizer} to provide more options for the * {@link CacheSpec} * @return the {@link HeaderSpec} to customize */ public HeaderSpec cache(Customizer<CacheSpec> cacheCustomizer) { cacheCustomizer.customize(new CacheSpec()); return this; } /** * Configures content type response headers * @param contentTypeOptionsCustomizer the {@link Customizer} to provide more * options for the {@link ContentTypeOptionsSpec} * @return the {@link HeaderSpec} to customize */ public HeaderSpec contentTypeOptions(Customizer<ContentTypeOptionsSpec> contentTypeOptionsCustomizer) { contentTypeOptionsCustomizer.customize(new ContentTypeOptionsSpec()); return this; } /** * Configures frame options response headers * @param frameOptionsCustomizer the {@link Customizer} to provide more options * for the {@link FrameOptionsSpec} * @return the {@link HeaderSpec} to customize */ public HeaderSpec frameOptions(Customizer<FrameOptionsSpec> frameOptionsCustomizer) { frameOptionsCustomizer.customize(new FrameOptionsSpec()); return this; } /** * Configures custom headers writer * @param serverHttpHeadersWriter the {@link ServerHttpHeadersWriter} to provide * custom headers writer * @return the {@link HeaderSpec} to customize * @since 5.3.0 */ public HeaderSpec writer(ServerHttpHeadersWriter serverHttpHeadersWriter) { Assert.notNull(serverHttpHeadersWriter, "serverHttpHeadersWriter cannot be null"); this.writers.add(serverHttpHeadersWriter); return this; } /** * Configures the Strict Transport Security response headers * @param hstsCustomizer the {@link Customizer} to provide more options for the * {@link HstsSpec} * @return the {@link HeaderSpec} to customize */ public HeaderSpec hsts(Customizer<HstsSpec> hstsCustomizer) { hstsCustomizer.customize(new HstsSpec()); return this; } protected void configure(ServerHttpSecurity http) { ServerHttpHeadersWriter writer = new CompositeServerHttpHeadersWriter(this.writers); HttpHeaderWriterWebFilter result = new HttpHeaderWriterWebFilter(writer); http.addFilterAt(result, SecurityWebFiltersOrder.HTTP_HEADERS_WRITER); } /** * Configures x-xss-protection response header. * @param xssProtectionCustomizer the {@link Customizer} to provide more options * for the {@link XssProtectionSpec} * @return the {@link HeaderSpec} to customize */ public HeaderSpec xssProtection(Customizer<XssProtectionSpec> xssProtectionCustomizer) { xssProtectionCustomizer.customize(new XssProtectionSpec()); return this; } /** * Configures {@code Content-Security-Policy} response header. * @param contentSecurityPolicyCustomizer the {@link Customizer} to provide more * options for the {@link ContentSecurityPolicySpec} * @return the {@link HeaderSpec} to customize */ public HeaderSpec contentSecurityPolicy(Customizer<ContentSecurityPolicySpec> contentSecurityPolicyCustomizer) { contentSecurityPolicyCustomizer.customize(new ContentSecurityPolicySpec()); return this; } /** * Configures {@code Feature-Policy} response header. * @param policyDirectives the policy * @return the {@link FeaturePolicySpec} to configure * @deprecated For removal in 7.0. Use {@link #permissionsPolicy(Customizer)} * instead. */ @Deprecated public FeaturePolicySpec featurePolicy(String policyDirectives) { return new FeaturePolicySpec(policyDirectives); } /** * Configures {@code Permissions-Policy} response header. * @param permissionsPolicyCustomizer the {@link Customizer} to provide more * options for the {@link PermissionsPolicySpec} * @return the {@link HeaderSpec} to customize */ public HeaderSpec permissionsPolicy(Customizer<PermissionsPolicySpec> permissionsPolicyCustomizer) { permissionsPolicyCustomizer.customize(new PermissionsPolicySpec()); return this; } /** * Configures {@code Referrer-Policy} response header. * @param referrerPolicyCustomizer the {@link Customizer} to provide more options * for the {@link ReferrerPolicySpec} * @return the {@link HeaderSpec} to customize */ public HeaderSpec referrerPolicy(Customizer<ReferrerPolicySpec> referrerPolicyCustomizer) { referrerPolicyCustomizer.customize(new ReferrerPolicySpec()); return this; } /** * Configures the <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Opener-Policy"> * Cross-Origin-Opener-Policy</a> header. * @return the {@link HeaderSpec} to customize * @since 5.7 * @see CrossOriginOpenerPolicyServerHttpHeadersWriter */ public HeaderSpec crossOriginOpenerPolicy( Customizer<CrossOriginOpenerPolicySpec> crossOriginOpenerPolicyCustomizer) { crossOriginOpenerPolicyCustomizer.customize(new CrossOriginOpenerPolicySpec()); return this; } /** * Configures the <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Embedder-Policy"> * Cross-Origin-Embedder-Policy</a> header. * @return the {@link HeaderSpec} to customize * @since 5.7 * @see CrossOriginEmbedderPolicyServerHttpHeadersWriter */ public HeaderSpec crossOriginEmbedderPolicy( Customizer<CrossOriginEmbedderPolicySpec> crossOriginEmbedderPolicyCustomizer) { crossOriginEmbedderPolicyCustomizer.customize(new CrossOriginEmbedderPolicySpec()); return this; } /** * Configures the <a href= * "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cross-Origin-Resource-Policy"> * Cross-Origin-Resource-Policy</a> header. * @return the {@link HeaderSpec} to customize * @since 5.7 * @see CrossOriginResourcePolicyServerHttpHeadersWriter */ public HeaderSpec crossOriginResourcePolicy( Customizer<CrossOriginResourcePolicySpec> crossOriginResourcePolicyCustomizer) { crossOriginResourcePolicyCustomizer.customize(new CrossOriginResourcePolicySpec()); return this; } /** * Configures cache control headers * * @see #cache() */ public final
HeaderSpec
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/main/java/org/apache/hadoop/yarn/server/nodemanager/amrmproxy/AbstractRequestInterceptor.java
{ "start": 1561, "end": 1708 }
interface ____ provides common functionality * which can can be used and/or extended by other concrete interceptor classes. * */ public abstract
and
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/InfiniteRecursionTest.java
{ "start": 11439, "end": 11821 }
class ____ { String asString() { // BUG: Diagnostic contains: return '{' + asString() + '}'; } } """) .doTest(); } @Test public void positiveCatchAndReturnDoesNotMakeItSafe() { compilationHelper .addSourceLines( "Test.java", """ final
Test
java
apache__camel
components/camel-bonita/src/main/java/org/apache/camel/component/bonita/producer/BonitaStartProducer.java
{ "start": 1304, "end": 2283 }
class ____ extends BonitaProducer { public BonitaStartProducer(BonitaEndpoint endpoint, BonitaConfiguration configuration) { super(endpoint, configuration); } @Override public void process(Exchange exchange) throws Exception { // Setup access type (HTTP on local host) String hostname = this.configuration.getHostname(); String port = this.configuration.getPort(); String processName = this.configuration.getProcessName(); String username = this.configuration.getUsername(); String password = this.configuration.getPassword(); BonitaAPIConfig bonitaAPIConfig = new BonitaAPIConfig(hostname, port, username, password); BonitaAPI bonitaApi = BonitaAPIBuilder.build(bonitaAPIConfig); ProcessDefinitionResponse processDefinition = bonitaApi.getProcessDefinition(processName); bonitaApi.startCase(processDefinition, exchange.getIn().getBody(Map.class)); } }
BonitaStartProducer
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/WildcardImportTest.java
{ "start": 5119, "end": 5282 }
class ____ {} } """) .addOutputLines( "out/test/Test.java", """ package test; public
C
java
apache__camel
components/camel-wal/src/main/java/org/apache/camel/component/wal/WriteAheadResumeStrategyConfigurationBuilder.java
{ "start": 1002, "end": 3323 }
class ____ extends BasicResumeStrategyConfigurationBuilder<WriteAheadResumeStrategyConfigurationBuilder, WriteAheadResumeStrategyConfiguration> { private File logFile; private ResumeStrategy delegateResumeStrategy; private long supervisorInterval; /** * The transaction log file to use * * @param logFile the file * @return this instance */ public WriteAheadResumeStrategyConfigurationBuilder withLogFile(File logFile) { this.logFile = logFile; return this; } public WriteAheadResumeStrategyConfigurationBuilder withDelegateResumeStrategy(ResumeStrategy delegateResumeStrategy) { this.delegateResumeStrategy = delegateResumeStrategy; return this; } public WriteAheadResumeStrategyConfigurationBuilder withSupervisorInterval(long supervisorInterval) { this.supervisorInterval = supervisorInterval; return this; } @Override public WriteAheadResumeStrategyConfiguration build() { final WriteAheadResumeStrategyConfiguration writeAheadResumeStrategyConfiguration = new WriteAheadResumeStrategyConfiguration(); buildCommonConfiguration(writeAheadResumeStrategyConfiguration); writeAheadResumeStrategyConfiguration.setLogFile(logFile); writeAheadResumeStrategyConfiguration.setDelegateResumeStrategy(delegateResumeStrategy); writeAheadResumeStrategyConfiguration.setSupervisorInterval(supervisorInterval); return writeAheadResumeStrategyConfiguration; } /** * Creates an empty builder * * @return an empty configuration builder */ public static WriteAheadResumeStrategyConfigurationBuilder newEmptyBuilder() { return new WriteAheadResumeStrategyConfigurationBuilder(); } /** * Creates the most basic builder possible * * @return a pre-configured basic builder */ public static WriteAheadResumeStrategyConfigurationBuilder newBuilder() { WriteAheadResumeStrategyConfigurationBuilder builder = new WriteAheadResumeStrategyConfigurationBuilder(); builder.withSupervisorInterval(WriteAheadResumeStrategyConfiguration.DEFAULT_SUPERVISOR_INTERVAL); return builder; } }
WriteAheadResumeStrategyConfigurationBuilder
java
spring-projects__spring-security
webauthn/src/main/java/org/springframework/security/web/webauthn/authentication/HttpSessionPublicKeyCredentialRequestOptionsRepository.java
{ "start": 1226, "end": 2177 }
class ____ implements PublicKeyCredentialRequestOptionsRepository { static final String DEFAULT_ATTR_NAME = PublicKeyCredentialRequestOptionsRepository.class.getName() .concat(".ATTR_NAME"); private String attrName = DEFAULT_ATTR_NAME; @Override public void save(HttpServletRequest request, HttpServletResponse response, @Nullable PublicKeyCredentialRequestOptions options) { HttpSession session = request.getSession(); session.setAttribute(this.attrName, options); } @Override public @Nullable PublicKeyCredentialRequestOptions load(HttpServletRequest request) { HttpSession session = request.getSession(false); if (session == null) { return null; } return (PublicKeyCredentialRequestOptions) session.getAttribute(this.attrName); } public void setAttrName(String attrName) { Assert.notNull(attrName, "attrName cannot be null"); this.attrName = attrName; } }
HttpSessionPublicKeyCredentialRequestOptionsRepository
java
quarkusio__quarkus
integration-tests/kubernetes/quarkus-standard-way/src/test/java/io/quarkus/it/kubernetes/KubernetesWithEnvFromSecretTest.java
{ "start": 512, "end": 3251 }
class ____ { @RegisterExtension static final QuarkusProdModeTest config = new QuarkusProdModeTest() .withApplicationRoot((jar) -> jar.addClasses(GreetingResource.class)) .setApplicationName("env-from-secret") .setApplicationVersion("0.1-SNAPSHOT") .withConfigurationResource("kubernetes-with-env-from-secret.properties"); @ProdBuildResults private ProdModeTestResults prodModeTestResults; @Test public void assertGeneratedResources() throws IOException { Path kubernetesDir = prodModeTestResults.getBuildDir().resolve("kubernetes"); assertThat(kubernetesDir) .isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.json")) .isDirectoryContaining(p -> p.getFileName().endsWith("kubernetes.yml")); List<HasMetadata> kubernetesList = DeserializationUtil .deserializeAsList(kubernetesDir.resolve("kubernetes.yml")); assertThat(kubernetesList.get(0)).isInstanceOfSatisfying(Deployment.class, d -> { assertThat(d.getMetadata()).satisfies(m -> { assertThat(m.getName()).isEqualTo("env-from-secret"); }); assertThat(d.getSpec()).satisfies(deploymentSpec -> { assertThat(deploymentSpec.getTemplate()).satisfies(t -> { assertThat(t.getSpec()).satisfies(podSpec -> { assertThat(podSpec.getContainers()).singleElement().satisfies(container -> { assertThat(container.getEnvFrom()).singleElement().satisfies(env -> { assertThat(env.getSecretRef()).satisfies(secretRef -> { assertThat(secretRef.getName()).isEqualTo("my-secret"); }); }); assertThat(container.getEnv()).filteredOn(env -> "DB_PASSWORD".equals(env.getName())) .singleElement().satisfies(env -> { assertThat(env.getValueFrom()).satisfies(valueFrom -> { assertThat(valueFrom.getSecretKeyRef()).satisfies(secretKeyRef -> { assertThat(secretKeyRef.getKey()).isEqualTo("database.password"); assertThat(secretKeyRef.getName()).isEqualTo("db-secret"); }); }); }); }); }); }); }); }); } }
KubernetesWithEnvFromSecretTest
java
apache__camel
components/camel-jaxb/src/test/java/org/apache/camel/example/DataFormatComponentTest.java
{ "start": 892, "end": 1577 }
class ____ extends DataFormatTest { @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { from("direct:start").to("dataformat:jaxb:marshal?contextPath=org.apache.camel.example").to("direct:marshalled"); from("direct:marshalled").to("dataformat:jaxb:unmarshal?contextPath=org.apache.camel.example") .to("mock:result"); from("direct:prettyPrint").to("dataformat:jaxb:marshal?contextPath=org.apache.camel.foo.bar&prettyPrint=true") .to("mock:result"); } }; } }
DataFormatComponentTest
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-router/src/main/java/org/apache/hadoop/yarn/server/router/webapp/RouterBlock.java
{ "start": 6508, "end": 12853 }
interface ____ obtain schedule information String webAppAddress = WebAppUtils.getHttpSchemePrefix(this.conf) + subClusterInfo.getRMWebServiceAddress(); ClusterMetricsInfo metrics = RouterWebServiceUtil .genericForward(webAppAddress, null, ClusterMetricsInfo.class, HTTPMethods.GET, RMWSConsts.RM_WEB_SERVICE_PATH + RMWSConsts.METRICS, null, null, conf, client); client.close(); return metrics; } } catch (Exception e) { LOG.error("getClusterMetricsInfoBySubClusterId subClusterId = {} error.", subclusterId, e); } return null; } /** * Get SubClusterInfo based on subclusterId. * * @param subclusterId subCluster Id * @return SubClusterInfo Collection */ protected Collection<SubClusterInfo> getSubClusterInfoList(String subclusterId) { try { SubClusterId subClusterId = SubClusterId.newInstance(subclusterId); SubClusterInfo subClusterInfo = facade.getSubCluster(subClusterId); return Collections.singletonList(subClusterInfo); } catch (Exception e) { LOG.error("getSubClusterInfoList subClusterId = {} error.", subclusterId, e); } return null; } public FederationStateStoreFacade getFacade() { return facade; } /** * Initialize the Nodes menu. * * @param mainList HTML Object. * @param subClusterIds subCluster List. */ protected void initNodesMenu(Hamlet.UL<Hamlet.DIV<Hamlet>> mainList, List<String> subClusterIds) { if (CollectionUtils.isNotEmpty(subClusterIds)) { Hamlet.UL<Hamlet.LI<Hamlet.UL<Hamlet.DIV<Hamlet>>>> nodesList = mainList.li().a(url("nodes"), "Nodes").ul(). $style("padding:0.3em 1em 0.1em 2em"); // ### nodes info nodesList.li().__(); for (String subClusterId : subClusterIds) { nodesList.li().a(url("nodes", subClusterId), subClusterId).__(); } nodesList.__().__(); } else { mainList.li().a(url("nodes"), "Nodes").__(); } } /** * Initialize the Applications menu. * * @param mainList HTML Object. * @param subClusterIds subCluster List. */ protected void initApplicationsMenu(Hamlet.UL<Hamlet.DIV<Hamlet>> mainList, List<String> subClusterIds) { if (CollectionUtils.isNotEmpty(subClusterIds)) { Hamlet.UL<Hamlet.LI<Hamlet.UL<Hamlet.DIV<Hamlet>>>> apps = mainList.li().a(url("apps"), "Applications").ul(); apps.li().__(); for (String subClusterId : subClusterIds) { Hamlet.LI<Hamlet.UL<Hamlet.LI<Hamlet.UL<Hamlet.DIV<Hamlet>>>>> subClusterList = apps. li().a(url("apps", subClusterId), subClusterId); Hamlet.UL<Hamlet.LI<Hamlet.UL<Hamlet.LI<Hamlet.UL<Hamlet.DIV<Hamlet>>>>>> subAppStates = subClusterList.ul().$style("padding:0.3em 1em 0.1em 2em"); subAppStates.li().__(); for (YarnApplicationState state : YarnApplicationState.values()) { subAppStates. li().a(url("apps", subClusterId, state.toString()), state.toString()).__(); } subAppStates.li().__().__(); subClusterList.__(); } apps.__().__(); } else { mainList.li().a(url("apps"), "Applications").__(); } } /** * Initialize the NodeLabels menu. * * @param mainList HTML Object. * @param subClusterIds subCluster List. */ protected void initNodeLabelsMenu(Hamlet.UL<Hamlet.DIV<Hamlet>> mainList, List<String> subClusterIds) { if (CollectionUtils.isNotEmpty(subClusterIds)) { Hamlet.UL<Hamlet.LI<Hamlet.UL<Hamlet.DIV<Hamlet>>>> nodesList = mainList.li().a(url("nodelabels"), "Node Labels").ul(). $style("padding:0.3em 1em 0.1em 2em"); // ### nodelabels info nodesList.li().__(); for (String subClusterId : subClusterIds) { nodesList.li().a(url("nodelabels", subClusterId), subClusterId).__(); } nodesList.__().__(); } else { mainList.li().a(url("nodelabels"), "Node Labels").__(); } } /** * Generate SubClusterInfo based on local cluster information. * * @param config Configuration. * @return SubClusterInfo. */ protected SubClusterInfo getSubClusterInfoByLocalCluster(Configuration config) { Client client = null; try { // Step1. Retrieve the name of the local cluster and ClusterMetricsInfo. String localClusterName = config.get(YarnConfiguration.RM_CLUSTER_ID, UNAVAILABLE); String webAppAddress = WebAppUtils.getRMWebAppURLWithScheme(config); String rmWebAppURLWithoutScheme = WebAppUtils.getRMWebAppURLWithoutScheme(config); client = RouterWebServiceUtil.createJerseyClient(config); ClusterMetricsInfo clusterMetricsInfos = RouterWebServiceUtil .genericForward(webAppAddress, null, ClusterMetricsInfo.class, HTTPMethods.GET, RMWSConsts.RM_WEB_SERVICE_PATH + RMWSConsts.METRICS, null, null, config, client); if (clusterMetricsInfos == null) { return null; } // Step2. Retrieve cluster information for the local cluster to obtain its startup time. ClusterInfo clusterInfo = RouterWebServiceUtil.genericForward(webAppAddress, null, ClusterInfo.class, HTTPMethods.GET, RMWSConsts.RM_WEB_SERVICE_PATH + RMWSConsts.INFO, null, null, config, client); if (clusterInfo == null) { return null; } // Step3. Get Local-Cluster Capability JettisonJaxbContext jc = new JettisonJaxbContext(ClusterMetricsInfo.class); JettisonMarshaller marshaller = jc.createJsonMarshaller(); StringWriter writer = new StringWriter(); marshaller.marshallToJSON(clusterMetricsInfos, writer); String capability = writer.toString(); // Step4. Generate SubClusterInfo. SubClusterId subClusterId = SubClusterId.newInstance(localClusterName); SubClusterInfo subClusterInfo = SubClusterInfo.newInstance(subClusterId, rmWebAppURLWithoutScheme, SubClusterState.SC_RUNNING, clusterInfo.getStartedOn(), Time.now(), capability); return subClusterInfo; } catch (Exception e) { LOG.error("An error occurred while parsing the local YARN cluster.", e); } finally { if (client != null) { client.close(); } } return null; } }
to
java
apache__camel
components/camel-bindy/src/test/java/org/apache/camel/dataformat/bindy/csv/BindySimpleCsvUnmarshallDslTest.java
{ "start": 2522, "end": 2947 }
class ____ extends * SingleRouteCamelConfiguration { * @Override * @Bean public RouteBuilder route() { return new RouteBuilder() { * @Override public void configure() { // * from("file://src/test/data?noop=true") from(URI_DIRECT_START).unmarshal() * .bindy(BindyType.Csv, * "org.apache.camel.dataformat.bindy.model.simple.oneclass") * .to(URI_MOCK_RESULT); } }; } } */ }
ContextConfig
java
google__guava
android/guava/src/com/google/common/util/concurrent/AbstractFuture.java
{ "start": 6760, "end": 7561 }
class ____ { // constants to use when GENERATE_CANCELLATION_CAUSES = false static final @Nullable Cancellation CAUSELESS_INTERRUPTED; static final @Nullable Cancellation CAUSELESS_CANCELLED; static { if (GENERATE_CANCELLATION_CAUSES) { CAUSELESS_CANCELLED = null; CAUSELESS_INTERRUPTED = null; } else { CAUSELESS_CANCELLED = new Cancellation(false, null); CAUSELESS_INTERRUPTED = new Cancellation(true, null); } } final boolean wasInterrupted; final @Nullable Throwable cause; Cancellation(boolean wasInterrupted, @Nullable Throwable cause) { this.wasInterrupted = wasInterrupted; this.cause = cause; } } /** A special value that encodes the 'setFuture' state. */ private static final
Cancellation
java
quarkusio__quarkus
extensions/funqy/funqy-knative-events/deployment/src/test/java/io/quarkus/funqy/test/OverloadingTest.java
{ "start": 255, "end": 913 }
class ____ { @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest() .withApplicationRoot((jar) -> jar .addClasses(Overloading.class)); @Test public void testMapping() { RestAssured.given().contentType("application/json") .body("\"a\"") .post("/strfun") .then().statusCode(200) .body(equalTo("\"A\"")); RestAssured.given().contentType("application/json") .body("10") .post("/intfun") .then().statusCode(200) .body(equalTo("20")); } }
OverloadingTest
java
quarkusio__quarkus
extensions/arc/deployment/src/test/java/io/quarkus/arc/test/context/session/SimpleBean.java
{ "start": 264, "end": 586 }
class ____ { static final AtomicBoolean DESTROYED = new AtomicBoolean(); private String id; @PostConstruct void init() { id = UUID.randomUUID().toString(); } public String ping() { return id; } @PreDestroy void destroy() { DESTROYED.set(true); } }
SimpleBean
java
alibaba__nacos
plugin-default-impl/nacos-default-control-plugin/src/main/java/com/alibaba/nacos/plugin/control/impl/NacosTpsControlManager.java
{ "start": 1557, "end": 4225 }
class ____ extends TpsControlManager { /** * point name -> tps barrier. */ protected final Map<String, TpsBarrier> points = new ConcurrentHashMap<>(16); /** * point name -> tps control rule. */ protected final Map<String, TpsControlRule> rules = new ConcurrentHashMap<>(16); protected ScheduledExecutorService executorService; public NacosTpsControlManager() { super(); executorService = ExecutorFactory.newSingleScheduledExecutorService(r -> { Thread thread = new Thread(r, "nacos.plugin.tps.control.reporter"); thread.setDaemon(true); return thread; }); startTpsReport(); } protected void startTpsReport() { executorService .scheduleWithFixedDelay(new NacosTpsControlManager.TpsMetricsReporter(), 0, 900, TimeUnit.MILLISECONDS); } /** * apple tps rule. * * @param pointName pointName. */ public synchronized void registerTpsPoint(String pointName) { if (!points.containsKey(pointName)) { points.put(pointName, tpsBarrierCreator.createTpsBarrier(pointName)); if (rules.containsKey(pointName)) { points.get(pointName).applyRule(rules.get(pointName)); } else { initTpsRule(pointName); } } } /** * apple tps rule. * * @param pointName pointName. * @param rule rule. */ public synchronized void applyTpsRule(String pointName, TpsControlRule rule) { if (rule == null) { rules.remove(pointName); } else { rules.put(pointName, rule); } if (points.containsKey(pointName)) { points.get(pointName).applyRule(rule); } } public Map<String, TpsBarrier> getPoints() { return points; } public Map<String, TpsControlRule> getRules() { return rules; } /** * check tps result. * * @param tpsRequest TpsRequest. * @return check current tps is allowed. */ public TpsCheckResponse check(TpsCheckRequest tpsRequest) { if (points.containsKey(tpsRequest.getPointName())) { try { return points.get(tpsRequest.getPointName()).applyTps(tpsRequest); } catch (Throwable throwable) { Loggers.TPS.warn("[{}]apply tps error,error={}", tpsRequest.getPointName(), throwable); } } return new TpsCheckResponse(true, TpsResultCode.CHECK_SKIP, "skip"); }
NacosTpsControlManager
java
apache__camel
components/camel-jq/src/test/java/org/apache/camel/language/jq/JqExpressionSimpleTest.java
{ "start": 1037, "end": 1693 }
class ____ extends JqTestSupport { @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start") .transform().jq(".foo") .to("mock:result"); } }; } @Test public void testExpression() throws Exception { getMockEndpoint("mock:result").expectedBodiesReceived(new TextNode("bar")); template.sendBody("direct:start", node("foo", "bar", "baz", "bak")); MockEndpoint.assertIsSatisfied(context); } }
JqExpressionSimpleTest
java
google__auto
value/src/main/java/com/google/auto/value/AutoValue.java
{ "start": 1986, "end": 2192 }
class ____ { * static Builder builder() { * return new AutoValue_Person.Builder(); * } * * abstract String name(); * abstract int id(); * * @AutoValue.Builder *
Person
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/jsontype/jdk/EnumTypingTest.java
{ "start": 2148, "end": 2201 }
interface ____ {} @JsonTypeName("Test")
Base2775
java
apache__camel
components/camel-aws/camel-aws2-ddb/src/test/java/org/apache/camel/component/aws2/ddb/localstack/AWS2DescribeTableRuleIT.java
{ "start": 1484, "end": 2892 }
class ____ extends Aws2DDBBase { @EndpointInject("direct:start") private ProducerTemplate template; private final String attributeName = "clave"; private final String tableName = "randomTable"; @Test public void describeTable() { Exchange exchange = template.send("direct:start", new Processor() { public void process(Exchange exchange) { exchange.getIn().setHeader(Ddb2Constants.OPERATION, Ddb2Operations.DescribeTable); exchange.getIn().setHeader(Ddb2Constants.CONSISTENT_READ, true); } }); assertEquals(tableName, exchange.getIn().getHeader(Ddb2Constants.TABLE_NAME)); assertEquals(TableStatus.ACTIVE, exchange.getIn().getHeader(Ddb2Constants.TABLE_STATUS)); assertEquals(0L, exchange.getIn().getHeader(Ddb2Constants.TABLE_SIZE)); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:start").to( "aws2-ddb://" + tableName + "?keyAttributeName=" + attributeName + "&keyAttributeType=" + KeyType.HASH + "&keyScalarType=" + ScalarAttributeType.S + "&readCapacity=1&writeCapacity=1"); } }; } }
AWS2DescribeTableRuleIT
java
apache__rocketmq
proxy/src/main/java/org/apache/rocketmq/proxy/remoting/activity/ClientManagerActivity.java
{ "start": 9767, "end": 10205 }
class ____ implements ProducerChangeListener { @Override public void handle(ProducerGroupEvent event, String group, ClientChannelInfo clientChannelInfo) { if (event == ProducerGroupEvent.CLIENT_UNREGISTER) { remotingChannelManager.removeProducerChannel(ProxyContext.createForInner(this.getClass()), group, clientChannelInfo.getChannel()); } } } }
ProducerChangeListenerImpl
java
apache__flink
flink-examples/flink-examples-streaming/src/main/java/org/apache/flink/streaming/examples/windowing/GroupedProcessingTimeWindowExample.java
{ "start": 5017, "end": 5311 }
class ____ a data generator function that generates a stream of tuples. Each tuple * contains a key and a value. The function measures and prints the time it takes to generate * numElements. The key space is limited to numKeys. The value is always 1. */ private static
represents
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/entitygraph/named/parsed/entity/ForeignPublishingHouse.java
{ "start": 345, "end": 432 }
class ____ extends PublishingHouse { private String euIdentifier; }
ForeignPublishingHouse
java
junit-team__junit5
junit-vintage-engine/src/test/java/org/junit/vintage/engine/discovery/RunnerTestDescriptorPostProcessorTests.java
{ "start": 1696, "end": 3281 }
class ____ { @Test void doesNotLogAnythingForFilterableRunner(LogRecordListener listener) { resolve(selectMethod(PlainJUnit4TestCaseWithFiveTestMethods.class, "successfulTest")); assertThat(listener.stream(RunnerTestDescriptor.class)).isEmpty(); } @Test void doesNotLogAnythingForNonFilterableRunnerIfNoFiltersAreToBeApplied(LogRecordListener listener) { resolve(selectClass(IgnoredJUnit4TestCase.class)); assertThat(listener.stream(RunnerTestDescriptor.class)).isEmpty(); } @Test void logsWarningOnNonFilterableRunner(LogRecordListener listener) { Class<?> testClass = IgnoredJUnit4TestCaseWithNotFilterableRunner.class; resolve(selectMethod(testClass, "someTest")); // @formatter:off assertThat(listener.stream(RunnerTestDescriptor.class, Level.WARNING).map(LogRecord::getMessage)) .containsOnlyOnce("Runner " + NotFilterableRunner.class.getName() + " (used on class " + testClass.getName() + ") does not support filtering" + " and will therefore be run completely."); // @formatter:on } private void resolve(DiscoverySelector selector) { var request = LauncherDiscoveryRequestBuilder.request().selectors(selector).listeners( mock(LauncherDiscoveryListener.class)).build(); TestDescriptor engineDescriptor = new VintageDiscoverer().discover(request, VintageUniqueIdBuilder.engineId()); var runnerTestDescriptor = (RunnerTestDescriptor) getOnlyElement(engineDescriptor.getChildren()); new RunnerTestDescriptorPostProcessor().applyFiltersAndCreateDescendants(runnerTestDescriptor); } }
RunnerTestDescriptorPostProcessorTests
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableRepeatWhen.java
{ "start": 2268, "end": 4916 }
class ____<T> extends AtomicInteger implements Observer<T>, Disposable { private static final long serialVersionUID = 802743776666017014L; final Observer<? super T> downstream; final AtomicInteger wip; final AtomicThrowable error; final Subject<Object> signaller; final InnerRepeatObserver inner; final AtomicReference<Disposable> upstream; final ObservableSource<T> source; volatile boolean active; RepeatWhenObserver(Observer<? super T> actual, Subject<Object> signaller, ObservableSource<T> source) { this.downstream = actual; this.signaller = signaller; this.source = source; this.wip = new AtomicInteger(); this.error = new AtomicThrowable(); this.inner = new InnerRepeatObserver(); this.upstream = new AtomicReference<>(); } @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(this.upstream, d); } @Override public void onNext(T t) { HalfSerializer.onNext(downstream, t, this, error); } @Override public void onError(Throwable e) { DisposableHelper.dispose(inner); HalfSerializer.onError(downstream, e, this, error); } @Override public void onComplete() { DisposableHelper.replace(upstream, null); active = false; signaller.onNext(0); } @Override public boolean isDisposed() { return DisposableHelper.isDisposed(upstream.get()); } @Override public void dispose() { DisposableHelper.dispose(upstream); DisposableHelper.dispose(inner); } void innerNext() { subscribeNext(); } void innerError(Throwable ex) { DisposableHelper.dispose(upstream); HalfSerializer.onError(downstream, ex, this, error); } void innerComplete() { DisposableHelper.dispose(upstream); HalfSerializer.onComplete(downstream, this, error); } void subscribeNext() { if (wip.getAndIncrement() == 0) { do { if (isDisposed()) { return; } if (!active) { active = true; source.subscribe(this); } } while (wip.decrementAndGet() != 0); } } final
RepeatWhenObserver
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/checkpoint/DefaultCompletedCheckpointStore.java
{ "start": 2433, "end": 11255 }
class ____<R extends ResourceVersion<R>> extends AbstractCompleteCheckpointStore { private static final Logger LOG = LoggerFactory.getLogger(DefaultCompletedCheckpointStore.class); /** Completed checkpoints state handle store. */ private final StateHandleStore<CompletedCheckpoint, R> checkpointStateHandleStore; /** The maximum number of checkpoints to retain (at least 1). */ private final int maxNumberOfCheckpointsToRetain; /** * Local copy of the completed checkpoints in state handle store. This is restored from state * handle store when recovering and is maintained in parallel to the state in state handle store * during normal operations. */ private final ArrayDeque<CompletedCheckpoint> completedCheckpoints; private final Executor ioExecutor; private final CheckpointStoreUtil completedCheckpointStoreUtil; /** False if store has been shutdown. */ private final AtomicBoolean running = new AtomicBoolean(true); /** * Creates a {@link DefaultCompletedCheckpointStore} instance. * * @param maxNumberOfCheckpointsToRetain The maximum number of checkpoints to retain (at least * 1). Adding more checkpoints than this results in older checkpoints being discarded. On * recovery, we will only start with a single checkpoint. * @param stateHandleStore Completed checkpoints in external store * @param completedCheckpointStoreUtil utilities for completed checkpoint store * @param executor to execute blocking calls */ public DefaultCompletedCheckpointStore( int maxNumberOfCheckpointsToRetain, StateHandleStore<CompletedCheckpoint, R> stateHandleStore, CheckpointStoreUtil completedCheckpointStoreUtil, Collection<CompletedCheckpoint> completedCheckpoints, SharedStateRegistry sharedStateRegistry, Executor executor) { super(sharedStateRegistry); checkArgument(maxNumberOfCheckpointsToRetain >= 1, "Must retain at least one checkpoint."); this.maxNumberOfCheckpointsToRetain = maxNumberOfCheckpointsToRetain; this.checkpointStateHandleStore = checkNotNull(stateHandleStore); this.completedCheckpoints = new ArrayDeque<>(maxNumberOfCheckpointsToRetain + 1); this.completedCheckpoints.addAll(completedCheckpoints); this.ioExecutor = checkNotNull(executor); this.completedCheckpointStoreUtil = checkNotNull(completedCheckpointStoreUtil); } @Override public boolean requiresExternalizedCheckpoints() { return true; } /** * Synchronously writes the new checkpoints to state handle store and asynchronously removes * older ones. * * @param checkpoint Completed checkpoint to add. * @throws PossibleInconsistentStateException if adding the checkpoint failed and leaving the * system in a possibly inconsistent state, i.e. it's uncertain whether the checkpoint * metadata was fully written to the underlying systems or not. */ @Override public CompletedCheckpoint addCheckpointAndSubsumeOldestOne( final CompletedCheckpoint checkpoint, CheckpointsCleaner checkpointsCleaner, Runnable postCleanup) throws Exception { Preconditions.checkState(running.get(), "Checkpoint store has already been shutdown."); checkNotNull(checkpoint, "Checkpoint"); final String path = completedCheckpointStoreUtil.checkpointIDToName(checkpoint.getCheckpointID()); // Now add the new one. If it fails, we don't want to lose existing data. checkpointStateHandleStore.addAndLock(path, checkpoint); completedCheckpoints.addLast(checkpoint); // Remove completed checkpoint from queue and checkpointStateHandleStore, not discard. Optional<CompletedCheckpoint> subsume = CheckpointSubsumeHelper.subsume( completedCheckpoints, maxNumberOfCheckpointsToRetain, completedCheckpoint -> { tryRemove(completedCheckpoint.getCheckpointID()); checkpointsCleaner.addSubsumedCheckpoint(completedCheckpoint); }); findLowest(completedCheckpoints) .ifPresent( id -> checkpointsCleaner.cleanSubsumedCheckpoints( id, getSharedStateRegistry().unregisterUnusedState(id), postCleanup, ioExecutor)); return subsume.orElse(null); } @Override public List<CompletedCheckpoint> getAllCheckpoints() { return new ArrayList<>(completedCheckpoints); } @Override public int getNumberOfRetainedCheckpoints() { return completedCheckpoints.size(); } @Override public int getMaxNumberOfRetainedCheckpoints() { return maxNumberOfCheckpointsToRetain; } @Override public void shutdown(JobStatus jobStatus, CheckpointsCleaner checkpointsCleaner) throws Exception { super.shutdown(jobStatus, checkpointsCleaner); if (running.compareAndSet(true, false)) { if (jobStatus.isGloballyTerminalState()) { LOG.info("Shutting down"); long lowestRetained = Long.MAX_VALUE; for (CompletedCheckpoint checkpoint : completedCheckpoints) { try { if (!tryRemoveCompletedCheckpoint( checkpoint, checkpoint.shouldBeDiscardedOnShutdown(jobStatus), checkpointsCleaner, () -> {})) { lowestRetained = Math.min(lowestRetained, checkpoint.getCheckpointID()); } } catch (Exception e) { LOG.warn("Fail to remove checkpoint during shutdown.", e); if (!checkpoint.shouldBeDiscardedOnShutdown(jobStatus)) { lowestRetained = Math.min(lowestRetained, checkpoint.getCheckpointID()); } } } completedCheckpoints.clear(); checkpointStateHandleStore.clearEntries(); // Now discard the shared state of not subsumed checkpoints - only if: // - the job is in a globally terminal state. Otherwise, // it can be a suspension, after which this state might still be needed. // - checkpoint is not retained (it might be used externally) // - checkpoint handle removal succeeded (e.g. from ZK) - otherwise, it might still // be used in recovery if the job status is lost checkpointsCleaner.cleanSubsumedCheckpoints( lowestRetained, getSharedStateRegistry().unregisterUnusedState(lowestRetained), () -> {}, ioExecutor); } else { LOG.info("Suspending"); // Clear the local handles, but don't remove any state completedCheckpoints.clear(); checkpointStateHandleStore.releaseAll(); } } } // --------------------------------------------------------------------------------------------------------- // Private methods // --------------------------------------------------------------------------------------------------------- private boolean tryRemoveCompletedCheckpoint( CompletedCheckpoint completedCheckpoint, boolean shouldDiscard, CheckpointsCleaner checkpointsCleaner, Runnable postCleanup) throws Exception { if (tryRemove(completedCheckpoint.getCheckpointID())) { checkpointsCleaner.cleanCheckpoint( completedCheckpoint, shouldDiscard, postCleanup, ioExecutor); return shouldDiscard; } return shouldDiscard; } /** * Tries to remove the checkpoint identified by the given checkpoint id. * * @param checkpointId identifying the checkpoint to remove * @return true if the checkpoint could be removed */ private boolean tryRemove(long checkpointId) throws Exception { return checkpointStateHandleStore.releaseAndTryRemove( completedCheckpointStoreUtil.checkpointIDToName(checkpointId)); } }
DefaultCompletedCheckpointStore
java
quarkusio__quarkus
extensions/websockets-next/deployment/src/test/java/io/quarkus/websockets/next/test/endpoints/TooManyOnOpenTest.java
{ "start": 763, "end": 910 }
class ____ { @OnOpen public void onOpen() { } @OnOpen public void onOpen2() { } } }
TooManyOnOpen
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/util/ClassUtils.java
{ "start": 25358, "end": 25879 }
class ____ * @return the corresponding resource path, pointing to the class */ public static String convertClassNameToResourcePath(String className) { Assert.notNull(className, "Class name must not be null"); return className.replace(PACKAGE_SEPARATOR, PATH_SEPARATOR); } /** * Return a path suitable for use with {@code ClassLoader.getResource} * (also suitable for use with {@code Class.getResource} by prepending a * slash ('/') to the return value). Built by taking the package of the specified *
name
java
apache__camel
components/camel-jms/src/test/java/org/apache/camel/component/jms/integration/activemq/ActiveMQTempReplyToIssueIT.java
{ "start": 1806, "end": 4359 }
class ____ extends AbstractJMSTest { @Order(2) @RegisterExtension public static CamelContextExtension camelContextExtension = new DefaultCamelContextExtension(); protected CamelContext context; protected ProducerTemplate template; protected ConsumerTemplate consumer; @Test public void testReplyToIssue() { String out = template.requestBody("activemq:queue:TempReplyToIssueTest", "World", String.class); // we should receive that fixed reply assertEquals("Hello Moon", out); } public String handleMessage( @Header("JMSReplyTo") final Destination jmsReplyTo, @Header("JMSCorrelationID") final String id, @Body String body, Exchange exchange) throws Exception { assertNotNull(jmsReplyTo); assertTrue(jmsReplyTo.toString().startsWith("ActiveMQTemporaryQueue"), "Should be a temp queue"); // we send the reply manually (notice we just use a bogus endpoint uri) ProducerTemplate producer = exchange.getContext().createProducerTemplate(); producer.send("activemq:queue:xxx", exchange1 -> { exchange1.getIn().setBody("Hello Moon"); // remember to set correlation id exchange1.getIn().setHeader("JMSCorrelationID", id); // this is the real destination we send the reply to exchange1.getIn().setHeader(JmsConstants.JMS_DESTINATION, jmsReplyTo); }); // stop it after use producer.stop(); // sleep a bit so Camel will send the reply a bit later Thread.sleep(1000); // this will later cause a problem as the temp queue has been deleted // and exceptions will be logged etc return "Hello " + body; } @Override protected String getComponentName() { return "activemq"; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("activemq:queue:TempReplyToIssueTest").bean(ActiveMQTempReplyToIssueIT.class, "handleMessage"); } }; } @Override public CamelContextExtension getCamelContextExtension() { return camelContextExtension; } @BeforeEach void setUpRequirements() { context = camelContextExtension.getContext(); template = camelContextExtension.getProducerTemplate(); consumer = camelContextExtension.getConsumerTemplate(); } }
ActiveMQTempReplyToIssueIT
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/struct/TestForwardReference.java
{ "start": 2012, "end": 2208 }
class ____ { public String id; public void setId(String id) { this.id = id; } } @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY) static
ForwardReferenceClass
java
apache__dubbo
dubbo-test/dubbo-test-check/src/main/java/org/apache/dubbo/test/check/exception/DubboTestException.java
{ "start": 907, "end": 1836 }
class ____ extends RuntimeException { /** * Constructs a new {@link DubboTestException} with the specified detail message. * * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method. */ public DubboTestException(String message) { super(message); } /** * Constructs a new {@link DubboTestException} with the specified detail message and cause. * * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} method. * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). * (A null value is permitted, and indicates that the cause is nonexistent or unknown.) */ public DubboTestException(String message, Throwable cause) { super(message, cause); } }
DubboTestException
java
netty__netty
handler/src/test/java/io/netty/handler/ssl/OpenSslPrivateKeyMethodTest.java
{ "start": 18015, "end": 21057 }
class ____ implements OpenSslAsyncPrivateKeyMethod { private final OpenSslPrivateKeyMethod keyMethod; private final boolean newThread; OpenSslPrivateKeyMethodAdapter(OpenSslPrivateKeyMethod keyMethod, boolean newThread) { this.keyMethod = keyMethod; this.newThread = newThread; } @Override public Future<byte[]> sign(final SSLEngine engine, final int signatureAlgorithm, final byte[] input) { final Promise<byte[]> promise = ImmediateEventExecutor.INSTANCE.newPromise(); try { if (newThread) { // Let's run these in an extra thread to ensure that this would also work if the promise is // notified later. new DelegateThread(new Runnable() { @Override public void run() { try { // Let's sleep for some time to ensure we would notify in an async fashion Thread.sleep(ThreadLocalRandom.current().nextLong(100, 500)); promise.setSuccess(keyMethod.sign(engine, signatureAlgorithm, input)); } catch (Throwable cause) { promise.setFailure(cause); } } }).start(); } else { promise.setSuccess(keyMethod.sign(engine, signatureAlgorithm, input)); } } catch (Throwable cause) { promise.setFailure(cause); } return promise; } @Override public Future<byte[]> decrypt(final SSLEngine engine, final byte[] input) { final Promise<byte[]> promise = ImmediateEventExecutor.INSTANCE.newPromise(); try { if (newThread) { // Let's run these in an extra thread to ensure that this would also work if the promise is // notified later. new DelegateThread(new Runnable() { @Override public void run() { try { // Let's sleep for some time to ensure we would notify in an async fashion Thread.sleep(ThreadLocalRandom.current().nextLong(100, 500)); promise.setSuccess(keyMethod.decrypt(engine, input)); } catch (Throwable cause) { promise.setFailure(cause); } } }).start(); } else { promise.setSuccess(keyMethod.decrypt(engine, input)); } } catch (Throwable cause) { promise.setFailure(cause); } return promise; } } }
OpenSslPrivateKeyMethodAdapter
java
micronaut-projects__micronaut-core
test-suite-logback/src/test/java/io/micronaut/logback/config/CustomConfigurator.java
{ "start": 648, "end": 2867 }
class ____ extends ContextAwareBase implements Configurator { public static final Level ROOT_LOGGER_LEVEL = Level.INFO; @Override public ExecutionStatus configure(LoggerContext lc) { addInfo("Setting up default configuration."); ConsoleAppender<ILoggingEvent> ca = startConsoleAppender(lc); configureRootRootLogger(lc, ca); final String pkg = "io.micronaut.logback"; Logger appPkgLogger = lc.getLogger(pkg); appPkgLogger.setLevel(Level.TRACE); appPkgLogger.setAdditive(false); appPkgLogger.addAppender(ca); Logger controllersLogger = lc.getLogger(pkg + ".controllers"); controllersLogger.setLevel(Level.INFO); controllersLogger.setAdditive(false); controllersLogger.addAppender(ca); Logger configuredLogger = lc.getLogger("i.should.exist"); configuredLogger.setLevel(Level.TRACE); configuredLogger.setAdditive(false); configuredLogger.addAppender(ca); Logger mnLogger = lc.getLogger("io.micronaut.runtime.Micronaut"); mnLogger.setLevel(Level.INFO); mnLogger.setAdditive(false); mnLogger.addAppender(ca); return ExecutionStatus.NEUTRAL; } private void configureRootRootLogger(LoggerContext lc, ConsoleAppender<ILoggingEvent> ca) { Logger rootLogger = lc.getLogger(Logger.ROOT_LOGGER_NAME); rootLogger.setLevel(ROOT_LOGGER_LEVEL); rootLogger.addAppender(ca); } private ConsoleAppender<ILoggingEvent> startConsoleAppender(LoggerContext lc) { ConsoleAppender<ILoggingEvent> ca = new ConsoleAppender<>(); ca.setContext(lc); ca.setName("stdout"); LayoutWrappingEncoder<ILoggingEvent> encoder = new LayoutWrappingEncoder<>(); encoder.setContext(lc); // same as // PatternLayout layout = new PatternLayout(); // layout.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - // %msg%n"); TTLLLayout layout = new TTLLLayout(); layout.setContext(lc); layout.start(); encoder.setLayout(layout); ca.setEncoder(encoder); ca.start(); return ca; } }
CustomConfigurator
java
quarkusio__quarkus
extensions/qute/deployment/src/main/java/io/quarkus/qute/deployment/MessageBundleProcessor.java
{ "start": 64319, "end": 69532 }
enum ____ not contain '_$': " + constant); } if (constant.contains("$") || constant.contains("_")) { // If any of the constants contains "_" or "$" then "_$" is used return "_$"; } } return "_"; } private String toEnumConstantKey(String methodName, String separator, String enumConstant) { return methodName + separator + enumConstant; } private void generateEnumConstantMessageMethod(ClassCreator bundleCreator, String bundleName, String locale, ClassInfo bundleInterface, ClassInfo defaultBundleInterface, String enumConstantKey, Map<String, MessageMethod> keyMap, String messageTemplate, BuildProducer<MessageBundleMethodBuildItem> messageTemplateMethods) { String templateId = null; if (messageTemplate.contains("}")) { if (defaultBundleInterface != null) { if (locale == null) { AnnotationInstance localizedAnnotation = bundleInterface .declaredAnnotation(Names.LOCALIZED); locale = localizedAnnotation.value().asString(); } templateId = bundleName + "_" + locale + "_" + enumConstantKey; } else { templateId = bundleName + "_" + enumConstantKey; } } MessageBundleMethodBuildItem messageBundleMethod = new MessageBundleMethodBuildItem(bundleName, enumConstantKey, templateId, null, messageTemplate, defaultBundleInterface == null, true); messageTemplateMethods.produce(messageBundleMethod); String effectiveTemplateId = templateId; String effectiveLocale = locale; bundleCreator.method(enumConstantKey, mc -> { mc.returning(String.class); mc.body(bc -> { if (!messageBundleMethod.isValidatable()) { // No expression/tag - no need to use qute bc.return_(Const.of(messageTemplate)); } else { // Obtain the template, e.g. msg_myEnum$CONSTANT_1 LocalVar template = bc.localVar("template", bc.invokeStatic( io.quarkus.qute.deployment.Descriptors.BUNDLES_GET_TEMPLATE, Const.of(effectiveTemplateId))); // Create a template instance LocalVar templateInstance = bc.localVar("templateInstance", bc.invokeInterface(io.quarkus.qute.deployment.Descriptors.TEMPLATE_INSTANCE, template)); if (effectiveLocale != null) { bc.invokeInterface( MethodDesc.of(TemplateInstance.class, "setLocale", TemplateInstance.class, String.class), templateInstance, Const.of(effectiveLocale)); } // Render the template bc.return_(bc.invokeInterface( io.quarkus.qute.deployment.Descriptors.TEMPLATE_INSTANCE_RENDER, templateInstance)); } }); keyMap.put(enumConstantKey, new EnumConstantMessageMethod(mc.desc())); }); } /** * @return {@link Message#value()} if value was provided */ private String getMessageAnnotationValue(AnnotationInstance messageAnnotation, boolean useDefault) { var messageValue = messageAnnotation.value(); if (messageValue == null || messageValue.asString().equals(Message.DEFAULT_VALUE)) { // no value was provided in annotation if (useDefault) { var defaultMessageValue = messageAnnotation.value("defaultValue"); if (defaultMessageValue == null || defaultMessageValue.asString().equals(Message.DEFAULT_VALUE)) { return null; } return defaultMessageValue.asString(); } else { return null; } } return messageValue.asString(); } static String getParameterName(MethodInfo method, int position) { String name = method.parameterName(position); AnnotationInstance paramAnnotation = Annotations .find(Annotations.getParameterAnnotations(method.annotations()).stream() .filter(a -> a.target().asMethodParameter().position() == position).collect(Collectors.toList()), Names.MESSAGE_PARAM); if (paramAnnotation != null) { AnnotationValue paramAnnotationValue = paramAnnotation.value(); if (paramAnnotationValue != null && !paramAnnotationValue.asString().equals(Message.ELEMENT_NAME)) { name = paramAnnotationValue.asString(); } } if (name == null) { throw new MessageBundleException("Unable to determine the name of the parameter at position " + position + " in method " + method.declaringClass().name() + "#" + method.name() + "() - compile the
may
java
apache__kafka
server-common/src/main/java/org/apache/kafka/server/network/EndpointReadyFutures.java
{ "start": 5330, "end": 5590 }
class ____ { final String name; final CompletionStage<?> future; EndpointCompletionStage(String name, CompletionStage<?> future) { this.name = name; this.future = future; } }
EndpointCompletionStage
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/indices/SystemIndexMappingUpdateService.java
{ "start": 2214, "end": 2569 }
class ____ that all system indices have up-to-date mappings, provided * those indices can be automatically managed. Only some system indices are managed * internally to Elasticsearch - others are created and managed externally, e.g. * Kibana indices. * * Other metadata updates are handled by {@link SystemIndexMetadataUpgradeService}. */ public
ensures
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/orphan/manytomany/Group.java
{ "start": 182, "end": 923 }
class ____ implements Serializable { private String org; private String name; private String description; private Integer groupType; public Group(String name, String org) { this.org = org; this.name = name; } public Group() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getOrg() { return org; } public void setOrg(String org) { this.org = org; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Integer getGroupType() { return groupType; } public void setGroupType(Integer groupType) { this.groupType = groupType; } }
Group
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/sorted/set/SortNaturalTest.java
{ "start": 937, "end": 1804 }
class ____ { @Test @JiraKey(value = "HHH-8827") public void testSortNatural(SessionFactoryScope scope) { scope.inTransaction( session -> { Owner owner = new Owner(); Cat cat1 = new Cat(); Cat cat2 = new Cat(); cat1.owner = owner; cat1.name = "B"; cat2.owner = owner; cat2.name = "A"; owner.cats.add( cat1 ); owner.cats.add( cat2 ); session.persist( owner ); session.getTransaction().commit(); session.clear(); session.beginTransaction(); owner = session.get( Owner.class, owner.id ); assertThat( owner.cats ).isNotNull(); assertThat( owner.cats.size() ).isEqualTo( 2 ); assertThat( owner.cats.first().name ).isEqualTo( "A" ); assertThat( owner.cats.last().name ).isEqualTo( "B" ); } ); } @Entity(name = "Owner") @Table(name = "Owner") static
SortNaturalTest
java
quarkusio__quarkus
extensions/mongodb-client/runtime/src/main/java/io/quarkus/mongodb/reactive/ReactiveMongoCollection.java
{ "start": 9573, "end": 10274 }
class ____ decode each document into * @param <D> the target document type of the iterable. * @return the stream with the selected documents, can be empty if none matches. */ <D> Multi<D> find(Bson filter, Class<D> clazz); /** * Finds all documents in the collection. * * @param clientSession the client session with which to associate this operation * @return the stream with the selected documents, can be empty if none matches. */ Multi<T> find(ClientSession clientSession); /** * Finds all documents in the collection. * * @param clientSession the client session with which to associate this operation * @param clazz the
to
java
spring-projects__spring-security
rsocket/src/main/java/org/springframework/security/rsocket/util/matcher/PayloadExchangeAuthorizationContext.java
{ "start": 855, "end": 1445 }
class ____ { private final PayloadExchange exchange; private final Map<String, Object> variables; public PayloadExchangeAuthorizationContext(PayloadExchange exchange) { this(exchange, Collections.emptyMap()); } public PayloadExchangeAuthorizationContext(PayloadExchange exchange, Map<String, Object> variables) { this.exchange = exchange; this.variables = variables; } public PayloadExchange getExchange() { return this.exchange; } public Map<String, Object> getVariables() { return Collections.unmodifiableMap(this.variables); } }
PayloadExchangeAuthorizationContext
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/javadoc/JavadocTag.java
{ "start": 3415, "end": 3734 }
enum ____ { BLOCK, INLINE } static JavadocTag blockTag(String name) { return of(name, TagType.BLOCK); } static JavadocTag inlineTag(String name) { return of(name, TagType.INLINE); } private static JavadocTag of(String name, TagType type) { return new JavadocTag(name, type); } }
TagType
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/IteratorAssert.java
{ "start": 950, "end": 1311 }
class ____<ELEMENT> extends AbstractIteratorAssert<IteratorAssert<ELEMENT>, ELEMENT> { public static <ELEMENT> IteratorAssert<ELEMENT> assertThatIterator(Iterator<? extends ELEMENT> actual) { return new IteratorAssert<>(actual); } public IteratorAssert(Iterator<? extends ELEMENT> actual) { super(actual, IteratorAssert.class); } }
IteratorAssert
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/security/action/user/AuthenticateRequest.java
{ "start": 624, "end": 1619 }
class ____ extends LegacyActionRequest { public static final AuthenticateRequest INSTANCE = new AuthenticateRequest(); public AuthenticateRequest(StreamInput in) throws IOException { super(in); if (in.getTransportVersion().before(TransportVersions.V_8_5_0)) { // Older versions included the username as a field in.readString(); } } private AuthenticateRequest() {} @Override public ActionRequestValidationException validate() { // we cannot apply our validation rules here as an authenticate request could be for an LDAP user that doesn't fit our restrictions return null; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); if (out.getTransportVersion().before(TransportVersions.V_8_5_0)) { throw new IllegalStateException("cannot send authenticate request to a node of earlier version"); } } }
AuthenticateRequest
java
grpc__grpc-java
okhttp/third_party/okhttp/main/java/io/grpc/okhttp/internal/framed/Huffman.java
{ "start": 1082, "end": 7511 }
class ____ { // Appendix C: Huffman Codes // http://tools.ietf.org/html/draft-ietf-httpbis-header-compression-12#appendix-B private static final int[] CODES = { 0x1ff8, 0x7fffd8, 0xfffffe2, 0xfffffe3, 0xfffffe4, 0xfffffe5, 0xfffffe6, 0xfffffe7, 0xfffffe8, 0xffffea, 0x3ffffffc, 0xfffffe9, 0xfffffea, 0x3ffffffd, 0xfffffeb, 0xfffffec, 0xfffffed, 0xfffffee, 0xfffffef, 0xffffff0, 0xffffff1, 0xffffff2, 0x3ffffffe, 0xffffff3, 0xffffff4, 0xffffff5, 0xffffff6, 0xffffff7, 0xffffff8, 0xffffff9, 0xffffffa, 0xffffffb, 0x14, 0x3f8, 0x3f9, 0xffa, 0x1ff9, 0x15, 0xf8, 0x7fa, 0x3fa, 0x3fb, 0xf9, 0x7fb, 0xfa, 0x16, 0x17, 0x18, 0x0, 0x1, 0x2, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x5c, 0xfb, 0x7ffc, 0x20, 0xffb, 0x3fc, 0x1ffa, 0x21, 0x5d, 0x5e, 0x5f, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 0x70, 0x71, 0x72, 0xfc, 0x73, 0xfd, 0x1ffb, 0x7fff0, 0x1ffc, 0x3ffc, 0x22, 0x7ffd, 0x3, 0x23, 0x4, 0x24, 0x5, 0x25, 0x26, 0x27, 0x6, 0x74, 0x75, 0x28, 0x29, 0x2a, 0x7, 0x2b, 0x76, 0x2c, 0x8, 0x9, 0x2d, 0x77, 0x78, 0x79, 0x7a, 0x7b, 0x7ffe, 0x7fc, 0x3ffd, 0x1ffd, 0xffffffc, 0xfffe6, 0x3fffd2, 0xfffe7, 0xfffe8, 0x3fffd3, 0x3fffd4, 0x3fffd5, 0x7fffd9, 0x3fffd6, 0x7fffda, 0x7fffdb, 0x7fffdc, 0x7fffdd, 0x7fffde, 0xffffeb, 0x7fffdf, 0xffffec, 0xffffed, 0x3fffd7, 0x7fffe0, 0xffffee, 0x7fffe1, 0x7fffe2, 0x7fffe3, 0x7fffe4, 0x1fffdc, 0x3fffd8, 0x7fffe5, 0x3fffd9, 0x7fffe6, 0x7fffe7, 0xffffef, 0x3fffda, 0x1fffdd, 0xfffe9, 0x3fffdb, 0x3fffdc, 0x7fffe8, 0x7fffe9, 0x1fffde, 0x7fffea, 0x3fffdd, 0x3fffde, 0xfffff0, 0x1fffdf, 0x3fffdf, 0x7fffeb, 0x7fffec, 0x1fffe0, 0x1fffe1, 0x3fffe0, 0x1fffe2, 0x7fffed, 0x3fffe1, 0x7fffee, 0x7fffef, 0xfffea, 0x3fffe2, 0x3fffe3, 0x3fffe4, 0x7ffff0, 0x3fffe5, 0x3fffe6, 0x7ffff1, 0x3ffffe0, 0x3ffffe1, 0xfffeb, 0x7fff1, 0x3fffe7, 0x7ffff2, 0x3fffe8, 0x1ffffec, 0x3ffffe2, 0x3ffffe3, 0x3ffffe4, 0x7ffffde, 0x7ffffdf, 0x3ffffe5, 0xfffff1, 0x1ffffed, 0x7fff2, 0x1fffe3, 0x3ffffe6, 0x7ffffe0, 0x7ffffe1, 0x3ffffe7, 0x7ffffe2, 0xfffff2, 0x1fffe4, 0x1fffe5, 0x3ffffe8, 0x3ffffe9, 0xffffffd, 0x7ffffe3, 0x7ffffe4, 0x7ffffe5, 0xfffec, 0xfffff3, 0xfffed, 0x1fffe6, 0x3fffe9, 0x1fffe7, 0x1fffe8, 0x7ffff3, 0x3fffea, 0x3fffeb, 0x1ffffee, 0x1ffffef, 0xfffff4, 0xfffff5, 0x3ffffea, 0x7ffff4, 0x3ffffeb, 0x7ffffe6, 0x3ffffec, 0x3ffffed, 0x7ffffe7, 0x7ffffe8, 0x7ffffe9, 0x7ffffea, 0x7ffffeb, 0xffffffe, 0x7ffffec, 0x7ffffed, 0x7ffffee, 0x7ffffef, 0x7fffff0, 0x3ffffee }; private static final byte[] CODE_LENGTHS = { 13, 23, 28, 28, 28, 28, 28, 28, 28, 24, 30, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 30, 28, 28, 28, 28, 28, 28, 28, 28, 28, 6, 10, 10, 12, 13, 6, 8, 11, 10, 10, 8, 11, 8, 6, 6, 6, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 8, 15, 6, 12, 10, 13, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 13, 19, 13, 14, 6, 15, 5, 6, 5, 6, 5, 6, 6, 6, 5, 7, 7, 6, 6, 6, 5, 6, 7, 6, 5, 5, 6, 7, 7, 7, 7, 7, 15, 11, 14, 13, 28, 20, 22, 20, 20, 22, 22, 22, 23, 22, 23, 23, 23, 23, 23, 24, 23, 24, 24, 22, 23, 24, 23, 23, 23, 23, 21, 22, 23, 22, 23, 23, 24, 22, 21, 20, 22, 22, 23, 23, 21, 23, 22, 22, 24, 21, 22, 23, 23, 21, 21, 22, 21, 23, 22, 23, 23, 20, 22, 22, 22, 23, 22, 22, 23, 26, 26, 20, 19, 22, 23, 22, 25, 26, 26, 26, 27, 27, 26, 24, 25, 19, 21, 26, 27, 27, 26, 27, 24, 21, 21, 26, 26, 28, 27, 27, 27, 20, 24, 20, 21, 22, 21, 21, 23, 22, 22, 25, 25, 24, 24, 26, 23, 26, 27, 26, 26, 27, 27, 27, 27, 27, 28, 27, 27, 27, 27, 27, 26 }; private static final Huffman INSTANCE = new Huffman(); public static Huffman get() { return INSTANCE; } private final Node root = new Node(); private Huffman() { buildTree(); } void encode(byte[] data, OutputStream out) throws IOException { long current = 0; int n = 0; for (int i = 0; i < data.length; i++) { int b = data[i] & 0xFF; int code = CODES[b]; int nbits = CODE_LENGTHS[b]; current <<= nbits; current |= code; n += nbits; while (n >= 8) { n -= 8; out.write(((int) (current >> n))); } } if (n > 0) { current <<= (8 - n); current |= (0xFF >>> n); out.write((int) current); } } int encodedLength(byte[] bytes) { long len = 0; for (int i = 0; i < bytes.length; i++) { int b = bytes[i] & 0xFF; len += CODE_LENGTHS[b]; } return (int) ((len + 7) >> 3); } byte[] decode(byte[] buf) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); Node node = root; int current = 0; int nbits = 0; for (int i = 0; i < buf.length; i++) { int b = buf[i] & 0xFF; current = (current << 8) | b; nbits += 8; while (nbits >= 8) { int c = (current >>> (nbits - 8)) & 0xFF; node = node.children[c]; if (node.children == null) { // terminal node baos.write(node.symbol); nbits -= node.terminalBits; node = root; } else { // non-terminal node nbits -= 8; } } } while (nbits > 0) { int c = (current << (8 - nbits)) & 0xFF; node = node.children[c]; if (node.children != null || node.terminalBits > nbits) { break; } baos.write(node.symbol); nbits -= node.terminalBits; node = root; } return baos.toByteArray(); } private void buildTree() { for (int i = 0; i < CODE_LENGTHS.length; i++) { addCode(i, CODES[i], CODE_LENGTHS[i]); } } @SuppressWarnings("NarrowingCompoundAssignment") private void addCode(int sym, int code, byte len) { Node terminal = new Node(sym, len); Node current = root; while (len > 8) { len -= 8; int i = ((code >>> len) & 0xFF); if (current.children == null) { throw new IllegalStateException("invalid dictionary: prefix not unique"); } if (current.children[i] == null) { current.children[i] = new Node(); } current = current.children[i]; } int shift = 8 - len; int start = (code << shift) & 0xFF; int end = 1 << shift; for (int i = start; i < start + end; i++) { current.children[i] = terminal; } } private static final
Huffman
java
elastic__elasticsearch
x-pack/plugin/ml/src/test/java/org/elasticsearch/xpack/ml/inference/nlp/tokenizers/BasicTokenFilterTests.java
{ "start": 1024, "end": 6905 }
class ____ extends BaseTokenStreamTestCase { public void testNeverSplit_GivenNoLowerCase() throws IOException { Analyzer analyzer = basicAnalyzerFromSettings(false, false, List.of("[UNK]")); assertAnalyzesToNoCharFilter(analyzer, "1 (return) [ Patois ", new String[] { "1", "(", "return", ")", "[", "Patois" }); assertAnalyzesToNoCharFilter(analyzer, "Hello [UNK].", new String[] { "Hello", "[UNK]", "." }); assertAnalyzesToNoCharFilter(analyzer, "Hello-[UNK]", new String[] { "Hello", "-", "[UNK]" }); assertAnalyzesToNoCharFilter( analyzer, " \tHeLLo!how \n Are yoU? [UNK]", new String[] { "HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]" } ); assertAnalyzesToNoCharFilter(analyzer, "Hello [UNK]?", new String[] { "Hello", "[UNK]", "?" }); assertAnalyzesToNoCharFilter(analyzer, "Hello [UNK]!!", new String[] { "Hello", "[UNK]", "!", "!" }); assertAnalyzesToNoCharFilter(analyzer, "Hello~[UNK][UNK]", new String[] { "Hello", "~", "[UNK]", "[UNK]" }); assertAnalyzesToNoCharFilter(analyzer, "Hello-[unk]", new String[] { "Hello", "-", "[", "unk", "]" }); } public void testNeverSplit_GivenLowerCase() throws IOException { Analyzer analyzer = basicAnalyzerFromSettings(false, false, List.of("[UNK]")); assertAnalyzesToNoCharFilter( analyzer, " \tHeLLo!how \n Are yoU? [UNK]", new String[] { "HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]" } ); assertAnalyzesToNoCharFilter(analyzer, "Hello [UNK].", new String[] { "Hello", "[UNK]", "." }); assertAnalyzesToNoCharFilter(analyzer, "Hello [UNK]?", new String[] { "Hello", "[UNK]", "?" }); assertAnalyzesToNoCharFilter(analyzer, "Hello [UNK]!!", new String[] { "Hello", "[UNK]", "!", "!" }); assertAnalyzesToNoCharFilter(analyzer, "Hello-[UNK]", new String[] { "Hello", "-", "[UNK]" }); assertAnalyzesToNoCharFilter(analyzer, "Hello~[UNK][UNK]", new String[] { "Hello", "~", "[UNK]", "[UNK]" }); assertAnalyzesToNoCharFilter(analyzer, "Hello-[unk]", new String[] { "Hello", "-", "[", "unk", "]" }); } public void testSplitCJK() throws Exception { Analyzer analyzer = basicAnalyzerFromSettings(true, false, List.of("[UNK]")); assertAnalyzesToNoCharFilter(analyzer, "hello ah\u535A\u63A8zz", new String[] { "hello", "ah", "\u535A", "\u63A8", "zz" }); assertAnalyzesToNoCharFilter(analyzer, "hello world", new String[] { "hello", "world" }); } public void testStripAccents() throws Exception { Analyzer analyzer = basicAnalyzerFromSettings(true, true, List.of("[UNK]")); assertAnalyzesToNoCharFilter(analyzer, "HäLLo how are you", new String[] { "HaLLo", "how", "are", "you" }); assertAnalyzesToNoCharFilter(analyzer, "ÎÎÎÏνÎÎÎαοÏ", new String[] { "IIIII½IIII±I", "¿", "I" }); } private static void assertAnalyzesToNoCharFilter(Analyzer a, String input, String[] output) throws IOException { assertTokenStreamContents(a.tokenStream("dummy", input), output, null, null, null, null, null, input.length()); checkResetException(a, input); // We don't allow the random char filter because our offsets aren't corrected appropriately due to "never_split" // If we could figure out a way to pass "never_split" through whichever passed char_filter there was, then it would work checkAnalysisConsistency(random(), a, false, input); } public void testIsPunctuation() { assertTrue(BasicTokenFilter.isPunctuationMark('-')); assertTrue(BasicTokenFilter.isPunctuationMark('$')); assertTrue(BasicTokenFilter.isPunctuationMark('`')); assertTrue(BasicTokenFilter.isPunctuationMark('.')); assertFalse(BasicTokenFilter.isPunctuationMark(' ')); assertFalse(BasicTokenFilter.isPunctuationMark('A')); assertTrue(BasicTokenFilter.isPunctuationMark('[')); } public static Analyzer basicAnalyzerFromSettings(boolean isTokenizeCjkChars, boolean isStripAccents, List<String> neverSplit) { return new Analyzer() { @Override protected TokenStreamComponents createComponents(String fieldName) { Tokenizer t = new WhitespaceTokenizer(); try { return new TokenStreamComponents(t, BasicTokenFilter.build(isTokenizeCjkChars, isStripAccents, neverSplit, t)); } catch (IOException ex) { throw new UncheckedIOException(ex); } } @Override protected Reader initReader(String fieldName, Reader reader) { return new ControlCharFilter(reader); } }; } public static List<DelimitedToken> basicTokenize(Analyzer analyzer, String input) throws IOException { try (TokenStream test = analyzer.tokenStream("test", input)) { test.reset(); CharTermAttribute term = test.addAttribute(CharTermAttribute.class); OffsetAttribute offsetAttribute = test.addAttribute(OffsetAttribute.class); List<DelimitedToken> tokens = new ArrayList<>(); while (test.incrementToken()) { tokens.add(new DelimitedToken(term.toString(), offsetAttribute.startOffset(), offsetAttribute.endOffset())); } test.end(); return tokens; } } public static List<DelimitedToken> basicTokenize( boolean isTokenizeCjkChars, boolean isStripAccents, List<String> neverSplit, String input ) throws IOException { try (Analyzer analyzer = basicAnalyzerFromSettings(isTokenizeCjkChars, isStripAccents, neverSplit)) { return basicTokenize(analyzer, input); } } }
BasicTokenFilterTests
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy-common/spi/src/main/java/io/quarkus/resteasy/common/spi/ResteasyDotNames.java
{ "start": 5167, "end": 5530 }
class ____ implements Predicate<FieldInfo> { @Override public boolean test(FieldInfo fieldInfo) { return fieldInfo.hasAnnotation(JSON_IGNORE) || fieldInfo.hasAnnotation(JSONB_TRANSIENT) || fieldInfo.hasAnnotation(XML_TRANSIENT); } } private static
IgnoreFieldForReflectionPredicate
java
google__dagger
javatests/dagger/internal/codegen/MembersInjectionTest.java
{ "start": 1454, "end": 1693 }
class ____ { private static final Source NON_TYPE_USE_NULLABLE = CompilerTests.javaSource( "test.Nullable", // force one-string-per-line format "package test;", "", "public @
MembersInjectionTest
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/namingstrategy/CamelCaseToUnderscoresNamingStrategyTest.java
{ "start": 943, "end": 2459 }
class ____ { private ServiceRegistry serviceRegistry; @BeforeAll public void setUp() { serviceRegistry = ServiceRegistryBuilder.buildServiceRegistry( Environment.getProperties() ); } @AfterAll public void tearDown() { if ( serviceRegistry != null ) { ServiceRegistryBuilder.destroy( serviceRegistry ); } } @Test public void testWithWordWithDigitNamingStrategy() { Metadata metadata = new MetadataSources( serviceRegistry ) .addAnnotatedClass( B.class ) .getMetadataBuilder() .applyPhysicalNamingStrategy( new PhysicalNamingStrategySnakeCaseImpl() ) .build(); PersistentClass entityBinding = metadata.getEntityBinding( B.class.getName() ); assertThat( entityBinding.getProperty( "wordWithDigitD1" ).getSelectables().get( 0 ).getText() ) .isEqualTo( "word_with_digit_d1" ); assertThat( entityBinding.getProperty( "AbcdEfghI21" ).getSelectables().get( 0 ).getText() ) .isEqualTo( "abcd_efgh_i21" ); assertThat( entityBinding.getProperty( "hello1" ).getSelectables().get( 0 ).getText() ) .isEqualTo( "hello1" ); assertThat( entityBinding.getProperty( "hello1D2" ).getSelectables().get( 0 ).getText() ) .isEqualTo( "hello1_d2" ); assertThat( entityBinding.getProperty( "hello3d4" ).getSelectables().get( 0 ).getText() ) .isEqualTo( "hello3d4" ); assertThat( entityBinding.getProperty( "quoted" ).getSelectables().get( 0 ).getText() ) .isEqualTo( "Quoted-ColumnName" ); } @Entity @Table(name = "ABCD")
CamelCaseToUnderscoresNamingStrategyTest
java
apache__camel
components/camel-jcr/src/main/java/org/apache/camel/component/jcr/JcrProducer.java
{ "start": 1475, "end": 7785 }
class ____ extends DefaultProducer { public JcrProducer(JcrEndpoint jcrEndpoint) { super(jcrEndpoint); } @Override public void process(Exchange exchange) throws Exception { TypeConverter converter = exchange.getContext().getTypeConverter(); Session session = openSession(); Message message = exchange.getIn(); String operation = determineOperation(message); try { if (JcrConstants.JCR_INSERT.equals(operation)) { Node base = findOrCreateNode(session.getRootNode(), getJcrEndpoint().getBase(), ""); Node node = findOrCreateNode(base, getNodeName(message), getNodeType(message)); Map<String, Object> headers = filterComponentHeaders(message.getHeaders()); for (String key : headers.keySet()) { Object header = message.getHeader(key); if (header != null && Object[].class.isAssignableFrom(header.getClass())) { Value[] value = converter.convertTo(Value[].class, exchange, header); node.setProperty(key, value); } else { Value value = converter.convertTo(Value.class, exchange, header); node.setProperty(key, value); } } node.addMixin("mix:referenceable"); exchange.getOut().setBody(node.getIdentifier()); session.save(); } else if (JcrConstants.JCR_GET_BY_ID.equals(operation)) { Node node = session.getNodeByIdentifier(exchange.getIn() .getMandatoryBody(String.class)); PropertyIterator properties = node.getProperties(); while (properties.hasNext()) { Property property = properties.nextProperty(); Class<?> aClass = classForJCRType(property); Object value; if (property.isMultiple()) { value = converter.convertTo(aClass, exchange, property.getValues()); } else { value = converter.convertTo(aClass, exchange, property.getValue()); } message.setHeader(property.getName(), value); } } else { throw new RuntimeCamelException("Unsupported operation: " + operation); } } finally { if (session != null && session.isLive()) { session.logout(); } } } private Map<String, Object> filterComponentHeaders(Map<String, Object> properties) { Map<String, Object> result = new HashMap<>(properties.size()); for (Map.Entry<String, Object> entry : properties.entrySet()) { String key = entry.getKey(); if (!key.equals(JcrConstants.JCR_NODE_NAME) && !key.equals(JcrConstants.JCR_OPERATION) && !key.equals(JcrConstants.JCR_NODE_TYPE)) { result.put(entry.getKey(), entry.getValue()); } } return result; } private Class<?> classForJCRType(Property property) throws RepositoryException { switch (property.getType()) { case PropertyType.STRING: return String.class; case PropertyType.BINARY: return InputStream.class; case PropertyType.BOOLEAN: return Boolean.class; case PropertyType.LONG: return Long.class; case PropertyType.DOUBLE: return Double.class; case PropertyType.DECIMAL: return BigDecimal.class; case PropertyType.DATE: return Calendar.class; case PropertyType.NAME: return String.class; case PropertyType.PATH: return String.class; case PropertyType.REFERENCE: return String.class; case PropertyType.WEAKREFERENCE: return String.class; case PropertyType.URI: return String.class; case PropertyType.UNDEFINED: return String.class; default: throw new IllegalArgumentException("unknown type: " + property.getType()); } } private String determineOperation(Message message) { String operation = message.getHeader(JcrConstants.JCR_OPERATION, String.class); return operation != null ? operation : JcrConstants.JCR_INSERT; } private String getNodeName(Message message) { String nodeName = message.getHeader(JcrConstants.JCR_NODE_NAME, String.class); return nodeName != null ? nodeName : message.getExchange().getExchangeId(); } private String getNodeType(Message message) { String nodeType = message.getHeader(JcrConstants.JCR_NODE_TYPE, String.class); return nodeType != null ? nodeType : ""; } private Node findOrCreateNode(Node parent, String path, String nodeType) throws RepositoryException { Node result = parent; for (String component : path.split("/")) { component = Text.escapeIllegalJcrChars(component); if (component.length() > 0) { if (result.hasNode(component)) { result = result.getNode(component); } else { if (ObjectHelper.isNotEmpty(nodeType)) { result = result.addNode(component, nodeType); } else { result = result.addNode(component); } } } } return result; } protected Session openSession() throws RepositoryException { if (ObjectHelper.isEmpty(getJcrEndpoint().getWorkspaceName())) { return getJcrEndpoint().getRepository().login(getJcrEndpoint().getCredentials()); } else { return getJcrEndpoint().getRepository().login(getJcrEndpoint().getCredentials(), getJcrEndpoint().getWorkspaceName()); } } private JcrEndpoint getJcrEndpoint() { return (JcrEndpoint) getEndpoint(); } }
JcrProducer
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/model/RoutesConfigurationMultipleRouteBuilderTest.java
{ "start": 1028, "end": 2361 }
class ____ extends ContextTestSupport { @Override public boolean isUseRouteBuilder() { return false; } @Test public void testRoutesConfiguration() throws Exception { context.addRoutesConfigurations(new RouteConfigurationBuilder() { @Override public void configuration() { // global configuration for all routes routeConfiguration().onException(Exception.class).handled(true).to("mock:error"); } }); context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start") .throwException(new IllegalArgumentException("Foo")); } }); context.addRoutes(new RouteBuilder() { @Override public void configure() { from("direct:start2") .throwException(new IllegalArgumentException("Foo2")); } }); context.start(); getMockEndpoint("mock:error").expectedBodiesReceived("Hello World", "Bye World"); template.sendBody("direct:start", "Hello World"); template.sendBody("direct:start2", "Bye World"); assertMockEndpointsSatisfied(); } }
RoutesConfigurationMultipleRouteBuilderTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/MetricAggregatorSupplier.java
{ "start": 786, "end": 1041 }
interface ____ { Aggregator build( String name, ValuesSourceConfig valuesSourceConfig, AggregationContext context, Aggregator parent, Map<String, Object> metadata ) throws IOException; }
MetricAggregatorSupplier
java
apache__camel
components/camel-ognl/src/test/java/org/apache/camel/language/ognl/MyClassResolver.java
{ "start": 948, "end": 1381 }
class ____ extends DefaultClassResolver { public MyClassResolver(CamelContext camelContext) { super(camelContext); } @Override public Class<?> resolveClass(String name) { if (name.equals("org.apache.camel.language.ognl.Animal1")) { name = "org.apache.camel.language.ognl.Animal"; } return loadClass(name, DefaultClassResolver.class.getClassLoader()); } }
MyClassResolver
java
google__guava
android/guava-testlib/src/com/google/common/testing/FreshValueGenerator.java
{ "start": 12557, "end": 12906 }
interface ____ {} /** * Annotates a method to generate the "empty" instance of a collection. This method should accept * no parameter. The value it generates should be unequal to the values generated by methods * annotated with {@link Generates}. */ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) private @
Generates
java
spring-projects__spring-boot
configuration-metadata/spring-boot-configuration-metadata/src/main/java/org/springframework/boot/configurationmetadata/ConfigurationMetadataHint.java
{ "start": 820, "end": 1785 }
class ____ { private static final String KEY_SUFFIX = ".keys"; private static final String VALUE_SUFFIX = ".values"; private String id; private final List<ValueHint> valueHints = new ArrayList<>(); private final List<ValueProvider> valueProviders = new ArrayList<>(); boolean isMapKeyHints() { return (this.id != null && this.id.endsWith(KEY_SUFFIX)); } boolean isMapValueHints() { return (this.id != null && this.id.endsWith(VALUE_SUFFIX)); } String resolveId() { if (isMapKeyHints()) { return this.id.substring(0, this.id.length() - KEY_SUFFIX.length()); } if (isMapValueHints()) { return this.id.substring(0, this.id.length() - VALUE_SUFFIX.length()); } return this.id; } String getId() { return this.id; } void setId(String id) { this.id = id; } List<ValueHint> getValueHints() { return this.valueHints; } List<ValueProvider> getValueProviders() { return this.valueProviders; } }
ConfigurationMetadataHint
java
google__dagger
javatests/dagger/functional/producers/cancellation/CancellationComponent.java
{ "start": 1695, "end": 2000 }
class ____ { final ProducerTester tester; Dependency(ProducerTester tester) { this.tester = checkNotNull(tester); } @SuppressWarnings("unused") // Dagger uses it ListenableFuture<String> getDependencyFuture() { return tester.start("dependencyFuture"); } } }
Dependency
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/event/service/spi/DuplicationStrategy.java
{ "start": 480, "end": 1030 }
enum ____ { ERROR, KEEP_ORIGINAL, REPLACE_ORIGINAL } /** * Are the two listener instances considered a duplication? * * @param listener The listener we are currently trying to register * @param original An already registered listener * * @return {@literal true} if the two instances are considered a duplication; {@literal false} otherwise */ boolean areMatch(Object listener, Object original); /** * How should a duplication be handled? * * @return The strategy for handling duplication */ Action getAction(); }
Action
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/jmx/export/assembler/MetadataMBeanInfoAssembler.java
{ "start": 2453, "end": 4501 }
class ____ extends AbstractReflectiveMBeanInfoAssembler implements AutodetectCapableMBeanInfoAssembler, InitializingBean { private @Nullable JmxAttributeSource attributeSource; /** * Create a new {@code MetadataMBeanInfoAssembler} which needs to be * configured through the {@link #setAttributeSource} method. */ public MetadataMBeanInfoAssembler() { } /** * Create a new {@code MetadataMBeanInfoAssembler} for the given * {@code JmxAttributeSource}. * @param attributeSource the JmxAttributeSource to use */ public MetadataMBeanInfoAssembler(JmxAttributeSource attributeSource) { Assert.notNull(attributeSource, "JmxAttributeSource must not be null"); this.attributeSource = attributeSource; } /** * Set the {@code JmxAttributeSource} implementation to use for * reading the metadata from the bean class. * @see org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource */ public void setAttributeSource(JmxAttributeSource attributeSource) { Assert.notNull(attributeSource, "JmxAttributeSource must not be null"); this.attributeSource = attributeSource; } @Override public void afterPropertiesSet() { if (this.attributeSource == null) { throw new IllegalArgumentException("Property 'attributeSource' is required"); } } private JmxAttributeSource obtainAttributeSource() { Assert.state(this.attributeSource != null, "No JmxAttributeSource set"); return this.attributeSource; } /** * Throws an IllegalArgumentException if it encounters a JDK dynamic proxy. * Metadata can only be read from target classes and CGLIB proxies! */ @Override protected void checkManagedBean(Object managedBean) throws IllegalArgumentException { if (AopUtils.isJdkDynamicProxy(managedBean)) { throw new IllegalArgumentException( "MetadataMBeanInfoAssembler does not support JDK dynamic proxies - " + "export the target beans directly or use CGLIB proxies instead"); } } /** * Used for auto-detection of beans. Checks to see if the bean's
MetadataMBeanInfoAssembler
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/internal/tools/query/QueryBuilder.java
{ "start": 14507, "end": 15019 }
class ____ extends JoinParameter { private final String entityName; public CrossJoinParameter(String entityName, String alias, boolean select) { super( alias, select ); this.entityName = entityName; } @Override public void appendJoin(boolean firstFromElement, StringBuilder builder, Map<String, Object> queryParamValues) { if ( !firstFromElement ) { builder.append( ", " ); } builder.append( entityName ).append( ' ' ).append( getAlias() ); } } private static
CrossJoinParameter
java
quarkusio__quarkus
extensions/reactive-routes/deployment/src/test/java/io/quarkus/vertx/web/validation/SyncValidationTest.java
{ "start": 5417, "end": 6720 }
class ____ { @Valid @Route(methods = HttpMethod.GET, path = "/valid") public Greeting getValidGreeting() { return new Greeting("luke", "hello"); } @Route(methods = HttpMethod.GET, path = "/invalid") @Valid public Greeting getInvalidValidGreeting() { return new Greeting("neo", "hello"); } @Route(methods = HttpMethod.GET, path = "/invalid2") public @Valid Greeting getDoubleInValidGreeting() { return new Greeting("neo", "hi"); } @Route public Greeting invalidParam(@NotNull @Param String name) { return new Greeting("neo", "hi"); } @Route(methods = HttpMethod.GET, path = "/query") public Greeting getGreetingWithName(@Pattern(regexp = "ne.*") @NotNull @Param("name") String name) { return new Greeting(name, "hi"); } @Route public String invalidParamHtml(@NotNull @Param String name) { return "hi"; } @Route(methods = HttpMethod.POST, path = "/echo") public @Valid Greeting echo(@Valid @Body JsonObject greeting) { return new Greeting(greeting.getString("name"), greeting.getString("message")); } } public static
MyRoutes
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/common/BackoffPolicy.java
{ "start": 9213, "end": 9917 }
class ____ implements Iterator<TimeValue> { private final Iterator<TimeValue> delegate; private final Runnable onBackoff; WrappedBackoffIterator(Iterator<TimeValue> delegate, Runnable onBackoff) { this.delegate = delegate; this.onBackoff = onBackoff; } @Override public boolean hasNext() { return delegate.hasNext(); } @Override public TimeValue next() { if (false == delegate.hasNext()) { throw new NoSuchElementException(); } onBackoff.run(); return delegate.next(); } } private static final
WrappedBackoffIterator
java
netty__netty
resolver-dns/src/test/java/io/netty/resolver/dns/PreferredAddressTypeComparatorTest.java
{ "start": 1000, "end": 3054 }
class ____ { @Test public void testIpv4() throws UnknownHostException { InetAddress ipv4Address1 = InetAddress.getByName("10.0.0.1"); InetAddress ipv4Address2 = InetAddress.getByName("10.0.0.2"); InetAddress ipv4Address3 = InetAddress.getByName("10.0.0.3"); InetAddress ipv6Address1 = InetAddress.getByName("::1"); InetAddress ipv6Address2 = InetAddress.getByName("::2"); InetAddress ipv6Address3 = InetAddress.getByName("::3"); PreferredAddressTypeComparator ipv4 = PreferredAddressTypeComparator.comparator(SocketProtocolFamily.INET); List<InetAddress> addressList = new ArrayList<InetAddress>(); Collections.addAll(addressList, ipv4Address1, ipv4Address2, ipv6Address1, ipv6Address2, ipv4Address3, ipv6Address3); Collections.sort(addressList, ipv4); assertEquals(Arrays.asList(ipv4Address1, ipv4Address2, ipv4Address3, ipv6Address1, ipv6Address2, ipv6Address3), addressList); } @Test public void testIpv6() throws UnknownHostException { InetAddress ipv4Address1 = InetAddress.getByName("10.0.0.1"); InetAddress ipv4Address2 = InetAddress.getByName("10.0.0.2"); InetAddress ipv4Address3 = InetAddress.getByName("10.0.0.3"); InetAddress ipv6Address1 = InetAddress.getByName("::1"); InetAddress ipv6Address2 = InetAddress.getByName("::2"); InetAddress ipv6Address3 = InetAddress.getByName("::3"); PreferredAddressTypeComparator ipv4 = PreferredAddressTypeComparator.comparator(SocketProtocolFamily.INET6); List<InetAddress> addressList = new ArrayList<InetAddress>(); Collections.addAll(addressList, ipv4Address1, ipv4Address2, ipv6Address1, ipv6Address2, ipv4Address3, ipv6Address3); Collections.sort(addressList, ipv4); assertEquals(Arrays.asList(ipv6Address1, ipv6Address2, ipv6Address3, ipv4Address1, ipv4Address2, ipv4Address3), addressList); } }
PreferredAddressTypeComparatorTest
java
apache__maven
impl/maven-impl/src/main/java/org/apache/maven/impl/DefaultVersionParser.java
{ "start": 1372, "end": 2224 }
class ____ implements VersionParser { private final ModelVersionParser modelVersionParser; @Inject public DefaultVersionParser(ModelVersionParser modelVersionParser) { this.modelVersionParser = requireNonNull(modelVersionParser, "modelVersionParser"); } @Override public Version parseVersion(String version) { return modelVersionParser.parseVersion(version); } @Override public VersionRange parseVersionRange(String range) { return modelVersionParser.parseVersionRange(range); } @Override public VersionConstraint parseVersionConstraint(String constraint) { return modelVersionParser.parseVersionConstraint(constraint); } @Override public boolean isSnapshot(String version) { return modelVersionParser.isSnapshot(version); } }
DefaultVersionParser
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/submitted/auto_type_from_non_ambiguous_constructor/Mapper1.java
{ "start": 931, "end": 1732 }
interface ____ { String SELECT_SQL = "select a.id, a.name, a.type from account a where a.id = #{id}"; String SELECT_WITH_DOB_SQL = "select id, name, type, date '2025-01-05' dob from account where id = #{id}"; @ConstructorArgs({ @Arg(column = "id"), @Arg(column = "name"), @Arg(column = "type") }) @Select(SELECT_SQL) Account getAccountJavaTypesMissing(long id); @ConstructorArgs({ @Arg(column = "id"), @Arg(column = "name", javaType = String.class), @Arg(column = "type") }) @Select(SELECT_SQL) Account3 getAccountPartialTypesProvided(long id); @ConstructorArgs({ @Arg(column = "name", name = "accountName"), @Arg(column = "dob", name = "accountDob"), @Arg(column = "id", name = "accountId") }) @Select(SELECT_WITH_DOB_SQL) Account4 getAccountWrongOrder(long id); }
Mapper1
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/jobmaster/slotpool/AbstractServiceConnectionManager.java
{ "start": 1104, "end": 2103 }
class ____<S> implements ServiceConnectionManager<S> { protected final Object lock = new Object(); @Nullable @GuardedBy("lock") protected S service; @GuardedBy("lock") private boolean closed = false; @Override public final void connect(S service) { synchronized (lock) { checkNotClosed(); this.service = service; } } @Override public final void disconnect() { synchronized (lock) { checkNotClosed(); this.service = null; } } @Override public final void close() { synchronized (lock) { closed = true; service = null; } } protected final void checkNotClosed() { if (closed) { throw new IllegalStateException("This connection manager has already been closed."); } } protected final boolean isConnected() { return service != null; } }
AbstractServiceConnectionManager
java
spring-projects__spring-framework
spring-beans/src/main/java/org/springframework/beans/factory/support/PropertiesBeanDefinitionReader.java
{ "start": 5729, "end": 5879 }
class ____, this default value gets used. * <p>Can be used, for example, for view definition files, to define a parent * with a default view
attribute
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/server/namenode/TestFSNamesystemMBean.java
{ "start": 2608, "end": 10074 }
class ____. ObjectName mxbeanNamefsn = new ObjectName( "Hadoop:service=NameNode,name=FSNamesystem"); // Metrics that belong to "FSNamesystemState". // These are metrics that FSNamesystem registers directly with MBeanServer. ObjectName mxbeanNameFsns = new ObjectName( "Hadoop:service=NameNode,name=FSNamesystemState"); // Metrics that belong to "NameNodeInfo". // These are metrics that FSNamesystem registers directly with MBeanServer. ObjectName mxbeanNameNni = new ObjectName( "Hadoop:service=NameNode,name=NameNodeInfo"); final Set<ObjectName> mbeans = new HashSet<ObjectName>(); mbeans.add(mxbeanNamefsn); mbeans.add(mxbeanNameFsns); mbeans.add(mxbeanNameNni); for(ObjectName mbean : mbeans) { MBeanInfo attributes = mbs.getMBeanInfo(mbean); for (MBeanAttributeInfo attributeInfo : attributes.getAttributes()) { mbs.getAttribute(mbean, attributeInfo.getName()); } } succeeded = true; } catch (Exception e) { } } } @Test public void test() throws Exception { Configuration conf = new Configuration(); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).build(); cluster.waitActive(); FSNamesystem fsn = cluster.getNameNode().namesystem; MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName mxbeanName = new ObjectName( "Hadoop:service=NameNode,name=FSNamesystemState"); String snapshotStats = (String) (mbs.getAttribute(mxbeanName, "SnapshotStats")); @SuppressWarnings("unchecked") Map<String, Object> stat = (Map<String, Object>) JSON .parse(snapshotStats); assertTrue(stat.containsKey("SnapshottableDirectories") && (Long) stat.get("SnapshottableDirectories") == fsn .getNumSnapshottableDirs()); assertTrue(stat.containsKey("Snapshots") && (Long) stat.get("Snapshots") == fsn.getNumSnapshots()); Object pendingDeletionBlocks = mbs.getAttribute(mxbeanName, "PendingDeletionBlocks"); assertNotNull(pendingDeletionBlocks); assertTrue(pendingDeletionBlocks instanceof Long); Object encryptionZones = mbs.getAttribute(mxbeanName, "NumEncryptionZones"); assertNotNull(encryptionZones); assertTrue(encryptionZones instanceof Integer); } finally { if (cluster != null) { cluster.shutdown(); } } } // The test makes sure JMX request can be processed even if namesystem's // writeLock is owned by another thread. @Test public void testWithFSNamesystemWriteLock() throws Exception { Configuration conf = new Configuration(); MiniDFSCluster cluster = null; FSNamesystem fsn = null; int jmxCachePeriod = 1; new ConfigBuilder().add("namenode.period", jmxCachePeriod) .save(TestMetricsConfig.getTestFilename("hadoop-metrics2-namenode")); try { cluster = new MiniDFSCluster.Builder(conf).build(); cluster.waitActive(); fsn = cluster.getNameNode().namesystem; fsn.writeLock(RwLockMode.GLOBAL); Thread.sleep(jmxCachePeriod * 1000); MBeanClient client = new MBeanClient(); client.start(); client.join(20000); assertTrue(client.succeeded, "JMX calls are blocked when FSNamesystem's writerlock" + "is owned by another thread"); client.interrupt(); } finally { if (fsn != null && fsn.hasWriteLock(RwLockMode.GLOBAL)) { fsn.writeUnlock(RwLockMode.GLOBAL, "testWithFSNamesystemWriteLock"); } if (cluster != null) { cluster.shutdown(); } } } // The test makes sure JMX request can be processed even if FSEditLog // is synchronized. @Test public void testWithFSEditLogLock() throws Exception { Configuration conf = new Configuration(); int jmxCachePeriod = 1; new ConfigBuilder().add("namenode.period", jmxCachePeriod) .save(TestMetricsConfig.getTestFilename("hadoop-metrics2-namenode")); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).build(); cluster.waitActive(); synchronized (cluster.getNameNode().getFSImage().getEditLog()) { Thread.sleep(jmxCachePeriod * 1000); MBeanClient client = new MBeanClient(); client.start(); client.join(20000); assertTrue(client.succeeded, "JMX calls are blocked when FSEditLog" + " is synchronized by another thread"); client.interrupt(); } } finally { if (cluster != null) { cluster.shutdown(); } } } @Test @Timeout(value = 120) public void testFsEditLogMetrics() throws Exception { final Configuration conf = new Configuration(); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build(); cluster.waitActive(); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName mxbeanNameFs = new ObjectName("Hadoop:service=NameNode,name=FSNamesystemState"); FileSystem fs = cluster.getFileSystem(); final int NUM_OPS = 10; for (int i = 0; i < NUM_OPS; i++) { final Path path = new Path(String.format("/user%d", i)); fs.mkdirs(path); } long syncCount = (long) mbs.getAttribute(mxbeanNameFs, "TotalSyncCount"); String syncTimes = (String) mbs.getAttribute(mxbeanNameFs, "TotalSyncTimes"); assertTrue(syncCount > 0); assertNotNull(syncTimes); } finally { if (cluster != null) { cluster.shutdown(); } } } /** * Test metrics associated with reconstructionQueuesInitProgress. */ @Test public void testReconstructionQueuesInitProgressMetrics() throws Exception { Configuration conf = new Configuration(); try (MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).build()) { cluster.waitActive(); final FSNamesystem fsNamesystem = cluster.getNamesystem(); final DistributedFileSystem fs = cluster.getFileSystem(); // Validate init reconstructionQueuesInitProgress value. assertEquals(0.0, fsNamesystem.getReconstructionQueuesInitProgress(), 0); MBeanServer mbs = ManagementFactory.getPlatformMBeanServer(); ObjectName mxbeanName = new ObjectName("Hadoop:service=NameNode,name=FSNamesystemState"); float reconstructionQueuesInitProgress = (float) mbs.getAttribute(mxbeanName, "ReconstructionQueuesInitProgress"); assertEquals(0.0, reconstructionQueuesInitProgress, 0); // Create file. Path file = new Path("/test"); long fileLength = 1024 * 1024 * 3; DFSTestUtil.createFile(fs, file, fileLength, (short) 1, 0L); DFSTestUtil.waitReplication(fs, file, (short) 1); // Restart nameNode to run processMisReplicatedBlocks. cluster.restartNameNode(true); // Validate reconstructionQueuesInitProgress value. GenericTestUtils.waitFor( () -> cluster.getNamesystem().getReconstructionQueuesInitProgress() == 1.0, 100, 5 * 1000); reconstructionQueuesInitProgress = (float) mbs.getAttribute(mxbeanName, "ReconstructionQueuesInitProgress"); assertEquals(1.0, reconstructionQueuesInitProgress, 0); } } }
FSNamesystem
java
apache__dubbo
dubbo-plugin/dubbo-filter-cache/src/main/java/org/apache/dubbo/cache/support/lfu/LfuCache.java
{ "start": 1161, "end": 1842 }
class ____ {@link LfuCacheFactory} to store method's returns value * to server from store without making method call. * <pre> * e.g. 1) &lt;dubbo:service cache="lfu" cache.size="5000" cache.evictionFactor="0.3"/&gt; * 2) &lt;dubbo:consumer cache="lfu" /&gt; * </pre> * <pre> * LfuCache uses url's <b>cache.size</b> value for its max store size, url's <b>cache.evictionFactor</b> value for its eviction factor, * default store size value will be 1000, default eviction factor will be 0.3 * </pre> * * @see Cache * @see LfuCacheFactory * @see org.apache.dubbo.cache.support.AbstractCacheFactory * @see org.apache.dubbo.cache.filter.CacheFilter */ public
using
java
google__dagger
dagger-compiler/main/java/dagger/internal/codegen/writing/LazyMapKeyProxyGenerator.java
{ "start": 3098, "end": 4081 }
class ____, and dagger will apply // identifierrnamestring rule to it to make sure it is correctly obfuscated. XPropertySpec lazyClassKeyField = XPropertySpecs.builder(LAZY_CLASS_KEY_NAME_FIELD, XTypeName.STRING) // TODO(b/217435141): Leave the field as non-final. We will apply // @IdentifierNameString on the field, which doesn't work well with static final // fields. .addModifiers(STATIC, PUBLIC) .initializer("%S", lazyClassMapKeyClassName.getReflectionName()) .build(); // In proguard, we need to keep the classes referenced by @LazyClassKey, we do that by // generating a field referencing the type, and then applying @KeepFieldType to the // field. Here, we generate the field in the proxy class. For classes that are // accessible from the dagger component, we generate fields in LazyClassKeyProvider. // Note: the generated field should not be initialized to avoid
name