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
netty__netty
resolver-dns/src/main/java/io/netty/resolver/dns/DnsResolveContext.java
{ "start": 56284, "end": 64122 }
class ____ { private final String questionName; // We not expect the linked-list to be very long so a double-linked-list is overkill. private AuthoritativeNameServer head; private int nameServerCount; AuthoritativeNameServerList(String questionName) { this.questionName = questionName.toLowerCase(Locale.US); } void add(DnsRecord r) { if (r.type() != DnsRecordType.NS || !(r instanceof DnsRawRecord)) { return; } // Only include servers that serve the correct domain. if (questionName.length() < r.name().length()) { return; } String recordName = r.name().toLowerCase(Locale.US); int dots = 0; for (int a = recordName.length() - 1, b = questionName.length() - 1; a >= 0; a--, b--) { char c = recordName.charAt(a); if (questionName.charAt(b) != c) { return; } if (c == '.') { dots++; } } if (head != null && head.dots > dots) { // We already have a closer match so ignore this one, no need to parse the domainName etc. return; } final ByteBuf recordContent = ((ByteBufHolder) r).content(); final String domainName = decodeDomainName(recordContent); if (domainName == null) { // Could not be parsed, ignore. return; } // We are only interested in preserving the nameservers which are the closest to our qName, so ensure // we drop servers that have a smaller dots count. if (head == null || head.dots < dots) { nameServerCount = 1; head = new AuthoritativeNameServer(dots, r.timeToLive(), recordName, domainName); } else if (head.dots == dots) { AuthoritativeNameServer serverName = head; while (serverName.next != null) { serverName = serverName.next; } serverName.next = new AuthoritativeNameServer(dots, r.timeToLive(), recordName, domainName); nameServerCount++; } } void handleWithAdditional( DnsNameResolver parent, DnsRecord r, AuthoritativeDnsServerCache authoritativeCache) { // Just walk the linked-list and mark the entry as handled when matched. AuthoritativeNameServer serverName = head; String nsName = r.name(); InetAddress resolved = decodeAddress(r, nsName, parent.isDecodeIdn()); if (resolved == null) { // Could not parse the address, just ignore. return; } while (serverName != null) { if (serverName.nsName.equalsIgnoreCase(nsName)) { if (serverName.address != null) { // We received multiple ADDITIONAL records for the same name. // Search for the last we insert before and then append a new one. while (serverName.next != null && serverName.next.isCopy) { serverName = serverName.next; } AuthoritativeNameServer server = new AuthoritativeNameServer(serverName); server.next = serverName.next; serverName.next = server; serverName = server; nameServerCount++; } // We should replace the TTL if needed with the one of the ADDITIONAL record so we use // the smallest for caching. serverName.update(parent.newRedirectServerAddress(resolved), r.timeToLive()); // Cache the server now. cache(serverName, authoritativeCache, parent.executor()); return; } serverName = serverName.next; } } // Now handle all AuthoritativeNameServer for which we had no ADDITIONAL record void handleWithoutAdditionals( DnsNameResolver parent, DnsCache cache, AuthoritativeDnsServerCache authoritativeCache) { AuthoritativeNameServer serverName = head; while (serverName != null) { if (serverName.address == null) { // These will be resolved on the fly if needed. cacheUnresolved(serverName, authoritativeCache, parent.executor()); // Try to resolve via cache as we had no ADDITIONAL entry for the server. List<? extends DnsCacheEntry> entries = cache.get(serverName.nsName, null); if (entries != null && !entries.isEmpty()) { InetAddress address = entries.get(0).address(); // If address is null we have a resolution failure cached so just use an unresolved address. if (address != null) { serverName.update(parent.newRedirectServerAddress(address)); for (int i = 1; i < entries.size(); i++) { address = entries.get(i).address(); assert address != null : "Cache returned a cached failure, should never return anything else"; AuthoritativeNameServer server = new AuthoritativeNameServer(serverName); server.next = serverName.next; serverName.next = server; serverName = server; serverName.update(parent.newRedirectServerAddress(address)); nameServerCount++; } } } } serverName = serverName.next; } } private static void cacheUnresolved( AuthoritativeNameServer server, AuthoritativeDnsServerCache authoritativeCache, EventLoop loop) { // We still want to cached the unresolved address server.address = InetSocketAddress.createUnresolved( server.nsName, DefaultDnsServerAddressStreamProvider.DNS_PORT); // Cache the server now. cache(server, authoritativeCache, loop); } private static void cache(AuthoritativeNameServer server, AuthoritativeDnsServerCache cache, EventLoop loop) { // Cache NS record if not for a root server as we should never cache for root servers. if (!server.isRootServer()) { cache.cache(server.domainName, server.address, server.ttl, loop); } } /** * Returns {@code true} if empty, {@code false} otherwise. */ boolean isEmpty() { return nameServerCount == 0; } /** * Creates a new {@link List} which holds the {@link InetSocketAddress}es. */ List<InetSocketAddress> addressList() { List<InetSocketAddress> addressList = new ArrayList<InetSocketAddress>(nameServerCount); AuthoritativeNameServer server = head; while (server != null) { if (server.address != null) { addressList.add(server.address); } server = server.next; } return addressList; } } private static final
AuthoritativeNameServerList
java
quarkusio__quarkus
independent-projects/bootstrap/maven-resolver/src/main/java/io/quarkus/bootstrap/resolver/maven/OrderedDependencyVisitor.java
{ "start": 362, "end": 4271 }
class ____ { private final Deque<DependencyList> stack = new ArrayDeque<>(); private DependencyList currentList; private int currentIndex = -1; private int currentDistance; private int totalOnCurrentDistance = 1; private int totalOnNextDistance; /** * The root of the dependency tree * * @param root the root of the dependency tree */ OrderedDependencyVisitor(DependencyNode root) { currentList = new DependencyList(0, List.of(root)); } /** * Current dependency. * * @return current dependency */ DependencyNode getCurrent() { ensureNonNegativeIndex(); return currentList.deps.get(currentIndex); } /** * Returns the current distance (depth) from the root to the level on which the current node is. * * @return current depth */ int getCurrentDistance() { ensureNonNegativeIndex(); return currentDistance; } private void ensureNonNegativeIndex() { if (currentIndex < 0) { throw new RuntimeException("The visitor has not been positioned on the first dependency node yet"); } } /** * Whether there are still not visited dependencies. * * @return true if there are still not visited dependencies, otherwise - false */ boolean hasNext() { return !stack.isEmpty() || currentIndex + 1 < currentList.deps.size() || !currentList.deps.get(currentIndex).getChildren().isEmpty(); } /** * Returns the next dependency. * * @return the next dependency */ DependencyNode next() { if (!hasNext()) { throw new NoSuchElementException(); } if (currentIndex >= 0) { var children = currentList.deps.get(currentIndex).getChildren(); if (!children.isEmpty()) { stack.addLast(new DependencyList(getSubtreeIndexForChildren(), children)); totalOnNextDistance += children.size(); } if (--totalOnCurrentDistance == 0) { ++currentDistance; totalOnCurrentDistance = totalOnNextDistance; totalOnNextDistance = 0; } } if (++currentIndex == currentList.deps.size()) { currentList = stack.removeFirst(); currentIndex = 0; } return currentList.deps.get(currentIndex); } private int getSubtreeIndexForChildren() { return currentDistance < 2 ? currentIndex + 1 : currentList.subtreeIndex; } /** * A dependency subtree index the current dependency belongs to. * * <p> * A dependency subtree index is an index of a direct dependency of the root of the dependency tree * from which the dependency subtree originates. All the dependencies from a subtree that originates * from a direct dependency of the root of the dependency tree will share the same subtree index. * * <p> * A dependency subtree index starts from {@code 1}. An exception is the root of the dependency tree, * which will have the subtree index of {@code 0}. * * @return dependency subtree index the current dependency belongs to */ int getSubtreeIndex() { return currentDistance == 0 ? 0 : (currentDistance < 2 ? currentIndex + 1 : currentList.subtreeIndex); } /** * Replaces the current dependency in the tree with the argument. * * @param newNode dependency node that should replace the current one in the tree */ void replaceCurrent(DependencyNode newNode) { currentList.deps.set(currentIndex, newNode); } /** * A list of dependencies that are children of a {@link DependencyNode} * that are associated with a dependency subtree index. */ private static
OrderedDependencyVisitor
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/cdi/bcextensions/ChangeFieldThroughClassTest.java
{ "start": 1838, "end": 1917 }
interface ____ { String hello(); } @Singleton static
MyService
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/query/sqm/tree/expression/SqmToDuration.java
{ "start": 681, "end": 2860 }
class ____<T> extends AbstractSqmExpression<T> { private final SqmExpression<?> magnitude; private final SqmDurationUnit<?> unit; public SqmToDuration( SqmExpression<?> magnitude, SqmDurationUnit<?> unit, ReturnableType<T> type, NodeBuilder nodeBuilder) { super( nodeBuilder.resolveExpressible( type ), nodeBuilder ); this.magnitude = magnitude; this.unit = unit; } @Override public SqmToDuration<T> copy(SqmCopyContext context) { final SqmToDuration<T> existing = context.getCopy( this ); if ( existing != null ) { return existing; } final SqmToDuration<T> expression = context.registerCopy( this, new SqmToDuration<>( magnitude.copy( context ), unit.copy( context ), (ReturnableType<T>) getNodeType(), nodeBuilder() ) ); copyTo( expression, context ); return expression; } public SqmExpression<?> getMagnitude() { return magnitude; } public SqmDurationUnit<?> getUnit() { return unit; } @Override public @NonNull SqmBindableType<T> getNodeType() { return castNonNull( super.getNodeType() ); } @Override public <R> R accept(SemanticQueryWalker<R> walker) { return walker.visitToDuration( this ); } @Override public String asLoggableText() { return magnitude.asLoggableText() + " " + unit.getUnit(); } @Override public void appendHqlString(StringBuilder hql, SqmRenderContext context) { magnitude.appendHqlString( hql, context ); hql.append( ' ' ); hql.append( unit.getUnit() ); } @Override public boolean equals(@Nullable Object object) { return object instanceof SqmToDuration<?> that && magnitude.equals( that.magnitude ) && unit.equals( that.unit ); } @Override public int hashCode() { int result = magnitude.hashCode(); result = 31 * result + unit.hashCode(); return result; } @Override public boolean isCompatible(Object object) { return object instanceof SqmToDuration<?> that && magnitude.isCompatible( that.magnitude ) && unit.isCompatible( that.unit ); } @Override public int cacheHashCode() { int result = magnitude.cacheHashCode(); result = 31 * result + unit.cacheHashCode(); return result; } }
SqmToDuration
java
elastic__elasticsearch
x-pack/plugin/security/src/main/java/org/elasticsearch/xpack/security/rest/action/rolemapping/RestGetRoleMappingsAction.java
{ "start": 1369, "end": 2972 }
class ____ extends NativeRoleMappingBaseRestHandler { public RestGetRoleMappingsAction(Settings settings, XPackLicenseState licenseState) { super(settings, licenseState); } @Override public List<Route> routes() { return List.of(new Route(GET, "/_security/role_mapping/"), new Route(GET, "/_security/role_mapping/{name}")); } @Override public String getName() { return "security_get_role_mappings_action"; } @Override public RestChannelConsumer innerPrepareRequest(RestRequest request, NodeClient client) throws IOException { final String[] names = request.paramAsStringArrayOrEmptyIfAll("name"); return channel -> new GetRoleMappingsRequestBuilder(client).names(names).execute(new RestBuilderListener<>(channel) { @Override public RestResponse buildResponse(GetRoleMappingsResponse response, XContentBuilder builder) throws Exception { builder.startObject(); for (ExpressionRoleMapping mapping : response.mappings()) { builder.field(mapping.getName(), mapping); } builder.endObject(); // if the request specified mapping names, but nothing was found then return a 404 result if (names.length != 0 && response.mappings().length == 0) { return new RestResponse(RestStatus.NOT_FOUND, builder); } else { return new RestResponse(RestStatus.OK, builder); } } }); } }
RestGetRoleMappingsAction
java
assertj__assertj-core
assertj-core/src/main/java/org/assertj/core/api/AbstractIterableAssert.java
{ "start": 121500, "end": 126234 }
class ____ extends SubType1 { * String inSubType2 = "type2"; * } * * List&lt;BaseClass&gt; list1 = List.of(new SubType1(), new SubType2()); * List&lt;BaseClass&gt; list2 = List.of(new SubType1(), new SubType2()); * * // Without ignoringNonExistentComparedFields(), this would fail with an IllegalArgumentException * // indicating that 'inSubType2' field doesn't exist in SubType1. * assertThat(list1).usingRecursiveFieldByFieldElementComparatorOnFields("common", "inSubType1", "inSubType2") * .ignoringNonExistentComparedFields() * .containsAll(list2); </code></pre> * * @return {@code this} assertion object. */ @CheckReturnValue public SELF ignoringNonExistentComparedFields() { RecursiveComparisonConfiguration recursiveComparisonConfiguration = RecursiveComparisonConfiguration.builder() .withIgnoreNonExistentComparedFields(true) .build(); return usingRecursiveFieldByFieldElementComparator(recursiveComparisonConfiguration); } /** * Enable hexadecimal representation of Iterable elements instead of standard representation in error messages. * <p> * It can be useful to better understand what the error was with a more meaningful error message. * <p> * Example * <pre><code class='java'> final List&lt;Byte&gt; bytes = newArrayList((byte) 0x10, (byte) 0x20);</code></pre> * * With standard error message: * <pre><code class='java'> assertThat(bytes).contains((byte) 0x30); * * Expecting: * &lt;[16, 32]&gt; * to contain: * &lt;[48]&gt; * but could not find: * &lt;[48]&gt;</code></pre> * * With Hexadecimal error message: * <pre><code class='java'> assertThat(bytes).inHexadecimal().contains((byte) 0x30); * * Expecting: * &lt;[0x10, 0x20]&gt; * to contain: * &lt;[0x30]&gt; * but could not find: * &lt;[0x30]&gt;</code></pre> * * @return {@code this} assertion object. */ @Override @CheckReturnValue public SELF inHexadecimal() { return super.inHexadecimal(); } /** * Enable binary representation of Iterable elements instead of standard representation in error messages. * <p> * Example: * <pre><code class='java'> final List&lt;Byte&gt; bytes = newArrayList((byte) 0x10, (byte) 0x20);</code></pre> * * With standard error message: * <pre><code class='java'> assertThat(bytes).contains((byte) 0x30); * * Expecting: * &lt;[16, 32]&gt; * to contain: * &lt;[48]&gt; * but could not find: * &lt;[48]&gt;</code></pre> * * With binary error message: * <pre><code class='java'> assertThat(bytes).inBinary().contains((byte) 0x30); * * Expecting: * &lt;[0b00010000, 0b00100000]&gt; * to contain: * &lt;[0b00110000]&gt; * but could not find: * &lt;[0b00110000]&gt;</code></pre> * * @return {@code this} assertion object. */ @Override @CheckReturnValue public SELF inBinary() { return super.inBinary(); } /** * Filters the iterable under test keeping only elements having a property or field equal to {@code expectedValue}, the * property/field is specified by {@code propertyOrFieldName} parameter. * <p> * The filter first tries to get the value from a property (named {@code propertyOrFieldName}), if no such property * exists it tries to read the value from a field. Reading private fields is supported by default, this can be * globally disabled by calling {@link Assertions#setAllowExtractingPrivateFields(boolean) * Assertions.setAllowExtractingPrivateFields(false)}. * <p> * When reading <b>nested</b> property/field, if an intermediate value is null the whole nested property/field is * considered to be null, thus reading "address.street.name" value will return null if "street" value is null. * <p> * * As an example, let's check all employees 800 years old (yes, special employees): * <pre><code class='java'> Employee yoda = new Employee(1L, new Name("Yoda"), 800); * Employee obiwan = new Employee(2L, new Name("Obiwan"), 800); * Employee luke = new Employee(3L, new Name("Luke", "Skywalker"), 26); * Employee noname = new Employee(4L, null, 50); * * List&lt;Employee&gt; employees = newArrayList(yoda, luke, obiwan, noname); * * assertThat(employees).filteredOn("age", 800) * .containsOnly(yoda, obiwan);</code></pre> * * Nested properties/fields are supported: * <pre><code class='java'> // Name is bean
SubType2
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/vectors/XFeatureField.java
{ "start": 1131, "end": 1707 }
class ____ { static final int MAX_FREQ = Float.floatToIntBits(Float.MAX_VALUE) >>> 15; static float decodeFeatureValue(float freq) { if (freq > MAX_FREQ) { // This is never used in practice but callers of the SimScorer API might // occasionally call it on eg. Float.MAX_VALUE to compute the max score // so we need to be consistent. return Float.MAX_VALUE; } int tf = (int) freq; // lossless int featureBits = tf << 15; return Float.intBitsToFloat(featureBits); } }
XFeatureField
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/NodeLabelsPage.java
{ "start": 1349, "end": 2066 }
class ____ extends RouterView { @Override protected void preHead(Hamlet.HTML<__> html) { commonPreHead(html); String type = $(NODE_SC); String nodeLabel = $(NODE_LABEL); String title = "Node labels of the cluster"; if (nodeLabel != null && !nodeLabel.isEmpty()) { title = generateWebTitle(title, nodeLabel); } else if (type != null && !type.isEmpty()) { title = generateWebTitle(title, type); } setTitle(title); set(DATATABLES_ID, "nodelabels"); setTableStyles(html, "nodelabels", ".healthStatus {width:10em}", ".healthReport {width:10em}"); } @Override protected Class<? extends SubView> content() { return NodeLabelsBlock.class; } }
NodeLabelsPage
java
spring-projects__spring-framework
spring-core/src/main/java/org/springframework/asm/Opcodes.java
{ "start": 2391, "end": 3250 }
interface ____ { // ASM API versions. int ASM4 = 4 << 16 | 0 << 8; int ASM5 = 5 << 16 | 0 << 8; int ASM6 = 6 << 16 | 0 << 8; int ASM7 = 7 << 16 | 0 << 8; int ASM8 = 8 << 16 | 0 << 8; int ASM9 = 9 << 16 | 0 << 8; /** * <i>Experimental, use at your own risk. This field will be renamed when it becomes stable, this * will break existing code using it. Only code compiled with --enable-preview can use this.</i> * <p>SPRING PATCH: no preview mode check for ASM 10 experimental, enabling it by default. */ int ASM10_EXPERIMENTAL = 1 << 24 | 10 << 16 | 0 << 8; /* * Internal flags used to redirect calls to deprecated methods. For instance, if a visitOldStuff * method in API_OLD is deprecated and replaced with visitNewStuff in API_NEW, then the * redirection should be done as follows: * * <pre> * public
Opcodes
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/api/assumptions/BDDAssumptionsTest.java
{ "start": 4790, "end": 5169 }
class ____ { private final Byte actual = (byte) 1; @Test void should_run_test_when_assumption_passes() { thenCode(() -> given(actual).isOne()).doesNotThrowAnyException(); } @Test void should_ignore_test_when_assumption_fails() { expectAssumptionNotMetException(() -> given(actual).isZero()); } } @Nested
BDDAssumptions_given_Byte_Test
java
micronaut-projects__micronaut-core
core/src/main/java/io/micronaut/core/util/ArgumentUtils.java
{ "start": 5880, "end": 5957 }
interface ____ check a condition. */ @FunctionalInterface public
the
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/compositefk/OneToManyEmbeddedIdFKNotNullableTest.java
{ "start": 2742, "end": 3036 }
class ____ { private String name; public NestedEmbeddable() { } public NestedEmbeddable(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } } @Embeddable public static
NestedEmbeddable
java
spring-projects__spring-framework
spring-web/src/test/java/org/springframework/web/filter/DelegatingFilterProxyTests.java
{ "start": 1663, "end": 15453 }
class ____ { @Test void testDelegatingFilterProxy() throws ServletException, IOException { ServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.registerSingleton("targetFilter", MockFilter.class); wac.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter"); MockFilterConfig proxyConfig = new MockFilterConfig(sc); proxyConfig.addInitParameter("targetBeanName", "targetFilter"); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(); filterProxy.init(proxyConfig); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyAndCustomContextAttribute() throws ServletException, IOException { ServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.registerSingleton("targetFilter", MockFilter.class); wac.refresh(); sc.setAttribute("CUSTOM_ATTR", wac); MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter"); MockFilterConfig proxyConfig = new MockFilterConfig(sc); proxyConfig.addInitParameter("targetBeanName", "targetFilter"); proxyConfig.addInitParameter("contextAttribute", "CUSTOM_ATTR"); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(); filterProxy.init(proxyConfig); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyWithFilterDelegateInstance() throws ServletException, IOException { MockFilter targetFilter = new MockFilter(); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(targetFilter); filterProxy.init(new MockFilterConfig(new MockServletContext())); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyWithTargetBeanName() throws ServletException, IOException { MockServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.registerSingleton("targetFilter", MockFilter.class); wac.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter"); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy("targetFilter"); filterProxy.init(new MockFilterConfig(sc)); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyWithTargetBeanNameAndNotYetRefreshedApplicationContext() throws ServletException, IOException { MockServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.registerSingleton("targetFilter", MockFilter.class); // wac.refresh(); // note that the context is not set as the ROOT attribute in the ServletContext! DelegatingFilterProxy filterProxy = new DelegatingFilterProxy("targetFilter", wac); filterProxy.init(new MockFilterConfig(sc)); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter"); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyWithTargetBeanNameAndNoApplicationContext() throws ServletException { MockServletContext sc = new MockServletContext(); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy("targetFilter", null); filterProxy.init(new MockFilterConfig(sc)); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); assertThatIllegalStateException().isThrownBy(() -> filterProxy.doFilter(request, response, null)); } @Test void testDelegatingFilterProxyWithFilterName() throws ServletException, IOException { ServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.registerSingleton("targetFilter", MockFilter.class); wac.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter"); MockFilterConfig proxyConfig = new MockFilterConfig(sc, "targetFilter"); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(); filterProxy.init(proxyConfig); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyWithLazyContextStartup() throws ServletException, IOException { ServletContext sc = new MockServletContext(); MockFilterConfig proxyConfig = new MockFilterConfig(sc); proxyConfig.addInitParameter("targetBeanName", "targetFilter"); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(); filterProxy.init(proxyConfig); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.registerSingleton("targetFilter", MockFilter.class); wac.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter"); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyWithTargetFilterLifecycle() throws ServletException, IOException { ServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.registerSingleton("targetFilter", MockFilter.class); wac.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter"); MockFilterConfig proxyConfig = new MockFilterConfig(sc); proxyConfig.addInitParameter("targetBeanName", "targetFilter"); proxyConfig.addInitParameter("targetFilterLifecycle", "true"); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(); filterProxy.init(proxyConfig); assertThat(targetFilter.filterConfig).isEqualTo(proxyConfig); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isEqualTo(proxyConfig); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyWithFrameworkServletContext() throws ServletException, IOException { ServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.registerSingleton("targetFilter", MockFilter.class); wac.refresh(); sc.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac); MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter"); MockFilterConfig proxyConfig = new MockFilterConfig(sc); proxyConfig.addInitParameter("targetBeanName", "targetFilter"); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(); filterProxy.init(proxyConfig); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyInjectedPreferred() throws ServletException, IOException { ServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.refresh(); sc.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac); StaticWebApplicationContext injectedWac = new StaticWebApplicationContext(); injectedWac.setServletContext(sc); String beanName = "targetFilter"; injectedWac.registerSingleton(beanName, MockFilter.class); injectedWac.refresh(); MockFilter targetFilter = (MockFilter) injectedWac.getBean(beanName); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(beanName, injectedWac); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyNotInjectedWacServletAttrPreferred() throws ServletException, IOException { ServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac); sc.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac); StaticWebApplicationContext wacToUse = new StaticWebApplicationContext(); wacToUse.setServletContext(sc); String beanName = "targetFilter"; String attrName = "customAttrName"; wacToUse.registerSingleton(beanName, MockFilter.class); wacToUse.refresh(); sc.setAttribute(attrName, wacToUse); MockFilter targetFilter = (MockFilter) wacToUse.getBean(beanName); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(beanName); filterProxy.setContextAttribute(attrName); filterProxy.setServletContext(sc); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } @Test void testDelegatingFilterProxyNotInjectedWithRootPreferred() throws ServletException, IOException { ServletContext sc = new MockServletContext(); StaticWebApplicationContext wac = new StaticWebApplicationContext(); wac.setServletContext(sc); wac.refresh(); sc.setAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher", wac); sc.setAttribute("another", wac); StaticWebApplicationContext wacToUse = new StaticWebApplicationContext(); wacToUse.setServletContext(sc); String beanName = "targetFilter"; wacToUse.registerSingleton(beanName, MockFilter.class); wacToUse.refresh(); sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wacToUse); MockFilter targetFilter = (MockFilter) wacToUse.getBean(beanName); DelegatingFilterProxy filterProxy = new DelegatingFilterProxy(beanName); filterProxy.setServletContext(sc); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); filterProxy.doFilter(request, response, null); assertThat(targetFilter.filterConfig).isNull(); assertThat(request.getAttribute("called")).isEqualTo(Boolean.TRUE); filterProxy.destroy(); assertThat(targetFilter.filterConfig).isNull(); } public static
DelegatingFilterProxyTests
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/GooglePubsubEndpointBuilderFactory.java
{ "start": 18721, "end": 20949 }
interface ____ extends EndpointProducerBuilder { default AdvancedGooglePubsubEndpointProducerBuilder advanced() { return (AdvancedGooglePubsubEndpointProducerBuilder) this; } /** * Use Credentials when interacting with PubSub service (no * authentication is required when using emulator). * * The option is a: <code>boolean</code> type. * * Default: true * Group: security * * @param authenticate the value to set * @return the dsl builder */ default GooglePubsubEndpointProducerBuilder authenticate(boolean authenticate) { doSetProperty("authenticate", authenticate); return this; } /** * Use Credentials when interacting with PubSub service (no * authentication is required when using emulator). * * The option will be converted to a <code>boolean</code> type. * * Default: true * Group: security * * @param authenticate the value to set * @return the dsl builder */ default GooglePubsubEndpointProducerBuilder authenticate(String authenticate) { doSetProperty("authenticate", authenticate); return this; } /** * The Service account key that can be used as credentials for the * PubSub publisher/subscriber. It can be loaded by default from * classpath, but you can prefix with classpath:, file:, or http: to * load the resource from different systems. * * The option is a: <code>java.lang.String</code> type. * * Group: security * * @param serviceAccountKey the value to set * @return the dsl builder */ default GooglePubsubEndpointProducerBuilder serviceAccountKey(String serviceAccountKey) { doSetProperty("serviceAccountKey", serviceAccountKey); return this; } } /** * Advanced builder for endpoint producers for the Google Pubsub component. */ public
GooglePubsubEndpointProducerBuilder
java
elastic__elasticsearch
x-pack/plugin/security/qa/multi-cluster/src/javaRestTest/java/org/elasticsearch/xpack/remotecluster/RemoteClusterSecurityRCS2ResolveClusterIT.java
{ "start": 1597, "end": 23758 }
class ____ extends AbstractRemoteClusterSecurityTestCase { private static final AtomicReference<Map<String, Object>> API_KEY_MAP_REF = new AtomicReference<>(); private static final AtomicReference<Map<String, Object>> REST_API_KEY_MAP_REF = new AtomicReference<>(); private static final AtomicBoolean SSL_ENABLED_REF = new AtomicBoolean(); private static final AtomicBoolean NODE1_RCS_SERVER_ENABLED = new AtomicBoolean(); private static final AtomicBoolean NODE2_RCS_SERVER_ENABLED = new AtomicBoolean(); private static final AtomicInteger INVALID_SECRET_LENGTH = new AtomicInteger(); static { fulfillingCluster = ElasticsearchCluster.local() .name("fulfilling-cluster") .nodes(3) .apply(commonClusterConfig) .setting("remote_cluster.port", "0") .setting("xpack.security.remote_cluster_server.ssl.enabled", () -> String.valueOf(SSL_ENABLED_REF.get())) .setting("xpack.security.remote_cluster_server.ssl.key", "remote-cluster.key") .setting("xpack.security.remote_cluster_server.ssl.certificate", "remote-cluster.crt") .setting("xpack.security.authc.token.enabled", "true") .keystore("xpack.security.remote_cluster_server.ssl.secure_key_passphrase", "remote-cluster-password") .node(0, spec -> spec.setting("remote_cluster_server.enabled", "true")) .node(1, spec -> spec.setting("remote_cluster_server.enabled", () -> String.valueOf(NODE1_RCS_SERVER_ENABLED.get()))) .node(2, spec -> spec.setting("remote_cluster_server.enabled", () -> String.valueOf(NODE2_RCS_SERVER_ENABLED.get()))) .build(); queryCluster = ElasticsearchCluster.local() .name("query-cluster") .apply(commonClusterConfig) .setting("xpack.security.remote_cluster_client.ssl.enabled", () -> String.valueOf(SSL_ENABLED_REF.get())) .setting("xpack.security.remote_cluster_client.ssl.certificate_authorities", "remote-cluster-ca.crt") .setting("xpack.security.authc.token.enabled", "true") .keystore("cluster.remote.my_remote_cluster.credentials", () -> { if (API_KEY_MAP_REF.get() == null) { final Map<String, Object> apiKeyMap = createCrossClusterAccessApiKey(""" { "search": [ { "names": ["index*"] } ] }"""); API_KEY_MAP_REF.set(apiKeyMap); } return (String) API_KEY_MAP_REF.get().get("encoded"); }) // Define a bogus API key for another remote cluster .keystore("cluster.remote.invalid_remote.credentials", randomEncodedApiKey()) // Define remote with a REST API key to observe expected failure .keystore("cluster.remote.wrong_api_key_type.credentials", () -> { if (REST_API_KEY_MAP_REF.get() == null) { initFulfillingClusterClient(); final var createApiKeyRequest = new Request("POST", "/_security/api_key"); createApiKeyRequest.setJsonEntity(""" { "name": "rest_api_key" }"""); try { final Response createApiKeyResponse = performRequestWithAdminUser(fulfillingClusterClient, createApiKeyRequest); assertOK(createApiKeyResponse); REST_API_KEY_MAP_REF.set(responseAsMap(createApiKeyResponse)); } catch (IOException e) { throw new UncheckedIOException(e); } } return (String) REST_API_KEY_MAP_REF.get().get("encoded"); }) // Define a remote with invalid API key secret length .keystore( "cluster.remote.invalid_secret_length.credentials", () -> Base64.getEncoder() .encodeToString( (UUIDs.base64UUID() + ":" + randomAlphaOfLength(INVALID_SECRET_LENGTH.get())).getBytes(StandardCharsets.UTF_8) ) ) .rolesFile(Resource.fromClasspath("roles.yml")) .user(REMOTE_METRIC_USER, PASS.toString(), "read_remote_shared_metrics", false) .build(); } @ClassRule // Use a RuleChain to ensure that fulfilling cluster is started before query cluster // `SSL_ENABLED_REF` is used to control the SSL-enabled setting on the test clusters // We set it here, since randomization methods are not available in the static initialize context above public static TestRule clusterRule = RuleChain.outerRule(new RunnableTestRuleAdapter(() -> { SSL_ENABLED_REF.set(usually()); NODE1_RCS_SERVER_ENABLED.set(randomBoolean()); NODE2_RCS_SERVER_ENABLED.set(randomBoolean()); INVALID_SECRET_LENGTH.set(randomValueOtherThan(22, () -> randomIntBetween(0, 99))); })).around(fulfillingCluster).around(queryCluster); @SuppressWarnings("unchecked") public void testResolveCluster() throws Exception { configureRemoteCluster(); { // Query cluster -> add role for test user - do not give any privileges for remote_indices final var putRoleRequest = new Request("PUT", "/_security/role/" + REMOTE_SEARCH_ROLE); putRoleRequest.setJsonEntity(""" { "indices": [ { "names": ["local_index"], "privileges": ["read"] } ] }"""); assertOK(adminClient().performRequest(putRoleRequest)); // Query cluster -> create user and assign role final var putUserRequest = new Request("PUT", "/_security/user/" + REMOTE_SEARCH_USER); putUserRequest.setJsonEntity(""" { "password": "x-pack-test-password", "roles" : ["remote_search"] }"""); assertOK(adminClient().performRequest(putUserRequest)); // Query cluster -> create test index final var indexDocRequest = new Request("POST", "/local_index/_doc?refresh=true"); indexDocRequest.setJsonEntity("{\"local_foo\": \"local_bar\"}"); assertOK(client().performRequest(indexDocRequest)); // Fulfilling cluster -> create test indices final Request bulkRequest = new Request("POST", "/_bulk?refresh=true"); bulkRequest.setJsonEntity(Strings.format(""" { "index": { "_index": "index1" } } { "foo": "bar" } { "index": { "_index": "secretindex" } } { "bar": "foo" } """)); assertOK(performRequestAgainstFulfillingCluster(bulkRequest)); } { // TEST CASE 1: Query cluster -> try to resolve local and remote star patterns (no access to remote cluster) final Request starResolveRequest = new Request("GET", "_resolve/cluster/*,my_remote_cluster:*"); Response response = performRequestWithRemoteSearchUser(starResolveRequest); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertLocalMatching(responseMap); Map<String, ?> remoteClusterResponse = (Map<String, ?>) responseMap.get("my_remote_cluster"); // with security exceptions, the remote should be marked as connected=false, since you can't tell whether a security // exception comes from the local cluster (intercepted) or the remote assertThat((Boolean) remoteClusterResponse.get("connected"), equalTo(false)); assertThat((String) remoteClusterResponse.get("error"), containsString("is unauthorized for user")); assertThat( (String) remoteClusterResponse.get("error"), containsString("no remote indices privileges apply for the target cluster") ); // TEST CASE 1-b: Query with no index expression but still with no access to remote cluster Response response2 = performRequestWithRemoteSearchUser(new Request("GET", "_resolve/cluster")); assertOK(response2); Map<String, Object> responseMap2 = responseAsMap(response2); Map<String, ?> remoteClusterResponse2 = (Map<String, ?>) responseMap2.get("my_remote_cluster"); assertThat((Boolean) remoteClusterResponse2.get("connected"), equalTo(false)); assertThat((String) remoteClusterResponse.get("error"), containsString("is unauthorized for user")); assertThat( (String) remoteClusterResponse.get("error"), containsString("no remote indices privileges apply for the target cluster") ); // TEST CASE 2: Query cluster -> add remote privs to the user role and try resolve again var updateRoleRequest = new Request("PUT", "/_security/role/" + REMOTE_SEARCH_ROLE); updateRoleRequest.setJsonEntity(""" { "indices": [ { "names": ["local_index"], "privileges": ["read"] } ], "remote_indices": [ { "names": ["index*"], "privileges": ["read", "read_cross_cluster"], "clusters": ["my_remote_cluster"] } ] }"""); assertOK(adminClient().performRequest(updateRoleRequest)); // Query cluster -> resolve local and remote with proper access response = performRequestWithRemoteSearchUser(starResolveRequest); assertOK(response); responseMap = responseAsMap(response); assertLocalMatching(responseMap); assertRemoteMatching(responseMap); } { // TEST CASE 3: Query cluster -> resolve index1 for local index without any local privilege final Request localOnly1 = new Request("GET", "_resolve/cluster/index1"); ResponseException exc = expectThrows(ResponseException.class, () -> performRequestWithRemoteSearchUser(localOnly1)); assertThat(exc.getResponse().getStatusLine().getStatusCode(), is(403)); assertThat( exc.getMessage(), containsString( "action [indices:admin/resolve/cluster] is unauthorized for user " + "[remote_search_user] with effective roles [remote_search] on indices [index1]" ) ); } { // TEST CASE 4: Query cluster -> resolve local for local index without any local privilege using wildcard final Request localOnlyWildcard1 = new Request("GET", "_resolve/cluster/index1*"); Response response = performRequestWithRemoteSearchUser(localOnlyWildcard1); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertMatching((Map<String, Object>) responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), false); } { // TEST CASE 5: Query cluster -> resolve remote and local without permission where using wildcard 'index1*' final Request localNoPermsRemoteWithPerms = new Request("GET", "_resolve/cluster/index1*,my_remote_cluster:index1"); Response response = performRequestWithRemoteSearchUser(localNoPermsRemoteWithPerms); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertMatching((Map<String, Object>) responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), false); assertRemoteMatching(responseMap); } { // TEST CASE 6a: Query cluster -> resolve remote only for existing and privileged index final Request remoteOnly1 = new Request("GET", "_resolve/cluster/my_remote_cluster:index1"); Response response = performRequestWithRemoteSearchUser(remoteOnly1); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertThat(responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), nullValue()); assertRemoteMatching(responseMap); } { // TEST CASE 6b: Resolution against a wildcarded index that does not exist (but no explicit permissions for "dummy") final Request remoteOnly1 = new Request("GET", "_resolve/cluster/my_remote_cluster:dummy*"); Response response = performRequestWithRemoteSearchUser(remoteOnly1); Map<String, Object> responseMap = responseAsMap(response); assertOK(response); assertThat(responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), nullValue()); Map<String, Object> remoteMap = (Map<String, Object>) responseMap.get("my_remote_cluster"); assertThat((Boolean) remoteMap.get("connected"), equalTo(true)); assertThat((Boolean) remoteMap.get("matching_indices"), equalTo(false)); assertThat(remoteMap.get("version"), notNullValue()); } { // TEST CASE 7: Query cluster -> resolve remote only for existing but non-privileged index final Request remoteOnly2 = new Request("GET", "_resolve/cluster/my_remote_cluster:secretindex"); Response response = performRequestWithRemoteSearchUser(remoteOnly2); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertThat(responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), nullValue()); Map<String, ?> remoteClusterResponse = (Map<String, ?>) responseMap.get("my_remote_cluster"); assertThat((Boolean) remoteClusterResponse.get("connected"), equalTo(false)); assertThat((String) remoteClusterResponse.get("error"), containsString("is unauthorized for user")); assertThat((String) remoteClusterResponse.get("error"), containsString("on indices [secretindex]")); } { // TEST CASE 7b: same as above except put a wildcard on secretindex*, which causes the error message to go away final Request remoteOnly1 = new Request("GET", "_resolve/cluster/my_remote_cluster:secretindex*"); Response response = performRequestWithRemoteSearchUser(remoteOnly1); Map<String, Object> responseMap = responseAsMap(response); assertOK(response); assertThat(responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), nullValue()); Map<String, Object> remoteMap = (Map<String, Object>) responseMap.get("my_remote_cluster"); assertThat((Boolean) remoteMap.get("connected"), equalTo(true)); assertThat((Boolean) remoteMap.get("matching_indices"), equalTo(false)); assertThat(remoteMap.get("version"), notNullValue()); } { // TEST CASE 8: Query cluster -> resolve remote only for non-existing and non-privileged index final Request remoteOnly3 = new Request("GET", "_resolve/cluster/my_remote_cluster:doesnotexist"); Response response = performRequestWithRemoteSearchUser(remoteOnly3); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertThat(responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), nullValue()); Map<String, ?> remoteClusterResponse = (Map<String, ?>) responseMap.get("my_remote_cluster"); assertThat((Boolean) remoteClusterResponse.get("connected"), equalTo(false)); assertThat((String) remoteClusterResponse.get("error"), containsString("is unauthorized for user")); assertThat((String) remoteClusterResponse.get("error"), containsString("on indices [doesnotexist]")); } { // TEST CASE 9: Query cluster -> resolve remote only for non-existing but privileged (by index pattern) index final Request remoteOnly4 = new Request("GET", "_resolve/cluster/my_remote_cluster:index99"); Response response = performRequestWithRemoteSearchUser(remoteOnly4); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertThat(responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), nullValue()); Map<String, ?> remoteClusterResponse = (Map<String, ?>) responseMap.get("my_remote_cluster"); // with IndexNotFoundExceptions, we know that error came from the remote cluster, so we can mark the remote as connected=true assertThat((Boolean) remoteClusterResponse.get("connected"), equalTo(true)); assertThat((Boolean) remoteClusterResponse.get("skip_unavailable"), equalTo(false)); assertThat((String) remoteClusterResponse.get("error"), containsString("no such index [index99]")); } { // TEST CASE 10: Query cluster -> resolve remote only for some existing/privileged, // non-existing/privileged, existing/non-privileged final Request remoteOnly5 = new Request( "GET", "_resolve/cluster/my_remote_cluster:index1,my_remote_cluster:secretindex,my_remote_cluster:index99" ); Response response = performRequestWithRemoteSearchUser(remoteOnly5); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertThat(responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), nullValue()); Map<String, ?> remoteClusterResponse = (Map<String, ?>) responseMap.get("my_remote_cluster"); assertThat((Boolean) remoteClusterResponse.get("connected"), equalTo(false)); assertThat((String) remoteClusterResponse.get("error"), containsString("is unauthorized for user")); assertThat((String) remoteClusterResponse.get("error"), containsString("on indices [secretindex]")); } { // TEST CASE 11: Query resolve/cluster with no index expression Response response = performRequestWithRemoteSearchUser(new Request("GET", "_resolve/cluster")); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertThat(responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), nullValue()); Map<String, ?> remoteClusterResponse = (Map<String, ?>) responseMap.get("my_remote_cluster"); assertThat((Boolean) remoteClusterResponse.get("connected"), equalTo(true)); assertNull(remoteClusterResponse.get("error")); assertNotNull(remoteClusterResponse.get("version")); } { // TEST CASE 12: Query resolve/cluster with no index expression, but include index options - should return error Request getRequest = new Request("GET", "_resolve/cluster"); Tuple<String, String> indexOptionTuple = randomFrom( new Tuple<>("ignore_throttled", "false"), new Tuple<>("expand_wildcards", "none"), new Tuple<>("allow_no_indices", "true"), new Tuple<>("ignore_unavailable", "true") ); getRequest.addParameter(indexOptionTuple.v1(), indexOptionTuple.v2()); ResponseException exc = expectThrows(ResponseException.class, () -> performRequestWithRemoteSearchUser(getRequest)); assertThat(exc.getResponse().getStatusLine().getStatusCode(), is(400)); assertThat( exc.getMessage(), containsString("No index options are allowed on _resolve/cluster when no index expression is specified") ); assertThat(exc.getMessage(), containsString(indexOptionTuple.v1())); } { // TEST CASE 13: Resolution against wildcarded remote cluster expression that matches no remotes should result in an // empty response and not fall back to the local cluster. final Request remoteOnly1 = new Request("GET", "_resolve/cluster/no_such_remote*:*"); Response response = performRequestWithRemoteSearchUser(remoteOnly1); assertOK(response); Map<String, Object> responseMap = responseAsMap(response); assertThat(responseMap.isEmpty(), is(true)); } } private Response performRequestWithRemoteSearchUser(final Request request) throws IOException { request.setOptions( RequestOptions.DEFAULT.toBuilder().addHeader("Authorization", headerFromRandomAuthMethod(REMOTE_SEARCH_USER, PASS)) ); return client().performRequest(request); } @SuppressWarnings("unchecked") private void assertLocalMatching(Map<String, Object> responseMap) { assertMatching((Map<String, Object>) responseMap.get(LOCAL_CLUSTER_NAME_REPRESENTATION), true); } @SuppressWarnings("unchecked") private void assertRemoteMatching(Map<String, Object> responseMap) { assertMatching((Map<String, Object>) responseMap.get("my_remote_cluster"), true); } private void assertMatching(Map<String, Object> perClusterResponse, boolean matching) { assertThat((Boolean) perClusterResponse.get("connected"), equalTo(true)); assertThat((Boolean) perClusterResponse.get("matching_indices"), equalTo(matching)); assertThat(perClusterResponse.get("version"), notNullValue()); } @SuppressWarnings("unchecked") private void assertRemoteNotMatching(Map<String, Object> responseMap) { assertMatching((Map<String, Object>) responseMap.get("my_remote_cluster"), false); } }
RemoteClusterSecurityRCS2ResolveClusterIT
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/requests/OffsetDeleteResponse.java
{ "start": 1975, "end": 6219 }
class ____ { OffsetDeleteResponseData data = new OffsetDeleteResponseData(); private OffsetDeleteResponseTopic getOrCreateTopic( String topicName ) { OffsetDeleteResponseTopic topic = data.topics().find(topicName); if (topic == null) { topic = new OffsetDeleteResponseTopic().setName(topicName); data.topics().add(topic); } return topic; } public Builder addPartition( String topicName, int partitionIndex, Errors error ) { final OffsetDeleteResponseTopic topicResponse = getOrCreateTopic(topicName); topicResponse.partitions().add(new OffsetDeleteResponsePartition() .setPartitionIndex(partitionIndex) .setErrorCode(error.code())); return this; } public <P> Builder addPartitions( String topicName, List<P> partitions, Function<P, Integer> partitionIndex, Errors error ) { final OffsetDeleteResponseTopic topicResponse = getOrCreateTopic(topicName); partitions.forEach(partition -> topicResponse.partitions().add(new OffsetDeleteResponsePartition() .setPartitionIndex(partitionIndex.apply(partition)) .setErrorCode(error.code())) ); return this; } public Builder merge( OffsetDeleteResponseData newData ) { if (newData.errorCode() != Errors.NONE.code()) { // If the top-level error exists, we can discard it and use the new data. data = newData; } else if (data.topics().isEmpty()) { // If the current data is empty, we can discard it and use the new data. data = newData; } else { // Otherwise, we have to merge them together. newData.topics().forEach(newTopic -> { OffsetDeleteResponseTopic existingTopic = data.topics().find(newTopic.name()); if (existingTopic == null) { // If no topic exists, we can directly copy the new topic data. data.topics().add(newTopic.duplicate()); } else { // Otherwise, we add the partitions to the existing one. Note we // expect non-overlapping partitions here as we don't verify // if the partition is already in the list before adding it. newTopic.partitions().forEach(partition -> existingTopic.partitions().add(partition.duplicate()) ); } }); } return this; } public OffsetDeleteResponse build() { return new OffsetDeleteResponse(data); } } private final OffsetDeleteResponseData data; public OffsetDeleteResponse(OffsetDeleteResponseData data) { super(ApiKeys.OFFSET_DELETE); this.data = data; } @Override public OffsetDeleteResponseData data() { return data; } @Override public Map<Errors, Integer> errorCounts() { Map<Errors, Integer> counts = new EnumMap<>(Errors.class); updateErrorCounts(counts, Errors.forCode(data.errorCode())); data.topics().forEach(topic -> topic.partitions().forEach(partition -> updateErrorCounts(counts, Errors.forCode(partition.errorCode())) ) ); return counts; } public static OffsetDeleteResponse parse(Readable readable, short version) { return new OffsetDeleteResponse(new OffsetDeleteResponseData(readable, version)); } @Override public int throttleTimeMs() { return data.throttleTimeMs(); } @Override public void maybeSetThrottleTimeMs(int throttleTimeMs) { data.setThrottleTimeMs(throttleTimeMs); } @Override public boolean shouldClientThrottle(short version) { return version >= 0; } }
Builder
java
spring-projects__spring-boot
loader/spring-boot-loader/src/main/java/org/springframework/boot/loader/net/protocol/jar/Handler.java
{ "start": 1191, "end": 6106 }
class ____ be public, // must be named Handler and must be in a package ending '.jar' private static final String PROTOCOL = "jar"; private static final String SEPARATOR = "!/"; static final Handler INSTANCE = new Handler(); @Override protected URLConnection openConnection(URL url) throws IOException { return JarUrlConnection.open(url); } @Override protected void parseURL(URL url, String spec, int start, int limit) { if (spec.regionMatches(true, start, "jar:", 0, 4)) { throw new IllegalStateException("Nested JAR URLs are not supported"); } int anchorIndex = spec.indexOf('#', limit); String path = extractPath(url, spec, start, limit, anchorIndex); String ref = (anchorIndex != -1) ? spec.substring(anchorIndex + 1) : null; setURL(url, PROTOCOL, "", -1, null, null, path, null, ref); } private String extractPath(URL url, String spec, int start, int limit, int anchorIndex) { if (anchorIndex == start) { return extractAnchorOnlyPath(url); } if (spec.length() >= 4 && spec.regionMatches(true, 0, "jar:", 0, 4)) { return extractAbsolutePath(spec, start, limit); } return extractRelativePath(url, spec, start, limit); } private String extractAnchorOnlyPath(URL url) { return url.getPath(); } private String extractAbsolutePath(String spec, int start, int limit) { int indexOfSeparator = indexOfSeparator(spec, start, limit); if (indexOfSeparator == -1) { throw new IllegalStateException("no !/ in spec"); } String innerUrl = spec.substring(start, indexOfSeparator); assertInnerUrlIsNotMalformed(spec, innerUrl); return spec.substring(start, limit); } private String extractRelativePath(URL url, String spec, int start, int limit) { String contextPath = extractContextPath(url, spec, start); String path = contextPath + spec.substring(start, limit); return Canonicalizer.canonicalizeAfter(path, indexOfSeparator(path) + 1); } private String extractContextPath(URL url, String spec, int start) { String contextPath = url.getPath(); if (spec.regionMatches(false, start, "/", 0, 1)) { int indexOfContextPathSeparator = indexOfSeparator(contextPath); if (indexOfContextPathSeparator == -1) { throw new IllegalStateException("malformed context url:%s: no !/".formatted(url)); } return contextPath.substring(0, indexOfContextPathSeparator + 1); } int lastSlash = contextPath.lastIndexOf('/'); if (lastSlash == -1) { throw new IllegalStateException("malformed context url:%s".formatted(url)); } return contextPath.substring(0, lastSlash + 1); } private void assertInnerUrlIsNotMalformed(String spec, String innerUrl) { if (innerUrl.startsWith("nested:")) { org.springframework.boot.loader.net.protocol.nested.Handler.assertUrlIsNotMalformed(innerUrl); return; } try { new URL(innerUrl); } catch (MalformedURLException ex) { throw new IllegalStateException("invalid url: %s (%s)".formatted(spec, ex)); } } @Override protected int hashCode(URL url) { String protocol = url.getProtocol(); int hash = (protocol != null) ? protocol.hashCode() : 0; String file = url.getFile(); int indexOfSeparator = file.indexOf(SEPARATOR); if (indexOfSeparator == -1) { return hash + file.hashCode(); } String fileWithoutEntry = file.substring(0, indexOfSeparator); try { hash += new URL(fileWithoutEntry).hashCode(); } catch (MalformedURLException ex) { hash += fileWithoutEntry.hashCode(); } String entry = file.substring(indexOfSeparator + 2); return hash + entry.hashCode(); } @Override protected boolean sameFile(URL url1, URL url2) { if (!url1.getProtocol().equals(PROTOCOL) || !url2.getProtocol().equals(PROTOCOL)) { return false; } String file1 = url1.getFile(); String file2 = url2.getFile(); int indexOfSeparator1 = file1.indexOf(SEPARATOR); int indexOfSeparator2 = file2.indexOf(SEPARATOR); if (indexOfSeparator1 == -1 || indexOfSeparator2 == -1) { return super.sameFile(url1, url2); } String entry1 = file1.substring(indexOfSeparator1 + 2); String entry2 = file2.substring(indexOfSeparator2 + 2); if (!entry1.equals(entry2)) { return false; } try { URL innerUrl1 = new URL(file1.substring(0, indexOfSeparator1)); URL innerUrl2 = new URL(file2.substring(0, indexOfSeparator2)); if (!super.sameFile(innerUrl1, innerUrl2)) { return false; } } catch (MalformedURLException unused) { return super.sameFile(url1, url2); } return true; } static int indexOfSeparator(String spec) { return indexOfSeparator(spec, 0, spec.length()); } static int indexOfSeparator(String spec, int start, int limit) { for (int i = limit - 1; i >= start; i--) { if (spec.charAt(i) == '!' && (i + 1) < limit && spec.charAt(i + 1) == '/') { return i; } } return -1; } /** * Clear any internal caches. */ public static void clearCache() { JarUrlConnection.clearCache(); } }
must
java
apache__camel
components/camel-stax/src/main/java/org/apache/camel/component/stax/StAXJAXBIteratorExpression.java
{ "start": 3444, "end": 5956 }
class ____ has JAXB annotations to bind POJO. * @param isNamespaceAware sets the namespace awareness of the xml reader */ public StAXJAXBIteratorExpression(String handledName, boolean isNamespaceAware) { ObjectHelper.notNull(handledName, "handledName"); this.handled = null; this.handledName = handledName; this.isNamespaceAware = isNamespaceAware; } private static JAXBContext jaxbContext(Class<?> handled) throws JAXBException { try { return JAX_CONTEXTS.computeIfAbsent(handled, k -> { try { return JAXBContext.newInstance(handled); } catch (JAXBException e) { throw new RuntimeCamelException(e); } }); } catch (RuntimeCamelException e) { throw (JAXBException) e.getCause(); } } @Override @SuppressWarnings("unchecked") public Object evaluate(Exchange exchange) { try { InputStream inputStream = null; XMLEventReader reader = exchange.getContext().getTypeConverter().tryConvertTo(XMLEventReader.class, exchange, exchange.getIn().getBody()); if (reader == null) { inputStream = exchange.getIn().getMandatoryBody(InputStream.class); XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance(); xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, isNamespaceAware); xmlInputFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, ""); xmlInputFactory.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, ""); reader = xmlInputFactory.createXMLEventReader(inputStream); } Class<T> clazz = handled; if (clazz == null && handledName != null) { clazz = (Class<T>) exchange.getContext().getClassResolver().resolveMandatoryClass(handledName); } return createIterator(reader, clazz, inputStream); } catch (InvalidPayloadException | JAXBException | ClassNotFoundException | XMLStreamException e) { exchange.setException(e); return null; } } private Iterator<T> createIterator(XMLEventReader reader, Class<T> clazz, InputStream inputStream) throws JAXBException { return new StAXJAXBIterator<>(clazz, reader, inputStream); } /** * Iterator to walk the XML reader */ static
which
java
quarkusio__quarkus
integration-tests/compose-devservices/src/test/java/io/quarkus/it/compose/devservices/rabbitmq/RabbitmqTest.java
{ "start": 398, "end": 1099 }
class ____ { @Test public void test() { given() .when() .body("hello") .post("/amqp/send") .then() .statusCode(204); given() .when() .body("world") .post("/amqp/send") .then() .statusCode(204); await().untilAsserted(() -> given() .accept(ContentType.JSON) .when().get("/amqp/received") .then() .statusCode(200) .body(Matchers.containsString("hello"), Matchers.containsString("world"))); } }
RabbitmqTest
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/UnusedNestedClass.java
{ "start": 3102, "end": 4145 }
class ____ extends TreePathScanner<Void, Void> { private final Map<ClassSymbol, TreePath> classes = new HashMap<>(); private final VisitorState state; private PrivateNestedClassScanner(VisitorState state) { this.state = state; } @Override public Void visitClass(ClassTree classTree, Void unused) { if (ignoreUnusedClass(classTree, state)) { return null; } ClassSymbol symbol = getSymbol(classTree); boolean isAnonymous = classTree.getSimpleName().length() == 0; if (!isAnonymous && (canBeRemoved(symbol) || symbol.owner instanceof MethodSymbol)) { classes.put(symbol, getCurrentPath()); } return super.visitClass(classTree, null); } private boolean ignoreUnusedClass(ClassTree classTree, VisitorState state) { return isSuppressed(classTree, state) || wellKnownKeep.shouldKeep(classTree) || toLowerCase(classTree.getSimpleName().toString()).startsWith("unused"); } } private static final
PrivateNestedClassScanner
java
google__error-prone
core/src/test/java/com/google/errorprone/matchers/EnclosingTest.java
{ "start": 1901, "end": 3652 }
class ____<T extends Tree> implements Matcher<T> { @Override public boolean matches(T t, VisitorState state) { if (state.getPath().getParentPath() == null) { return false; } Tree parent = state.getPath().getParentPath().getLeaf(); return (parent instanceof ForLoopTree forLoopTree && (interestingPartOfLoop(forLoopTree) == t)); } abstract Object interestingPartOfLoop(ForLoopTree loop); } private static final Matcher<Tree> IS_LOOP_CONDITION = new IsInterestingLoopSubNode<Tree>() { @Override Object interestingPartOfLoop(ForLoopTree loop) { return loop.getCondition(); } }; private static final Matcher<BlockTree> IS_LOOP_STATEMENT = new IsInterestingLoopSubNode<BlockTree>() { @Override Object interestingPartOfLoop(ForLoopTree loop) { return loop.getStatement(); } }; private static final Matcher<Tree> ENCLOSED_IN_LOOP_CONDITION = enclosingNode(IS_LOOP_CONDITION); private static final Matcher<Tree> CHILD_OF_LOOP_CONDITION = parentNode(IS_LOOP_CONDITION); private static final Matcher<Tree> USED_UNDER_LOOP_STATEMENT = enclosingBlock(IS_LOOP_STATEMENT); private static final Matcher<Tree> USED_UNDER_LOOP_STATEMENT_ACCORDING_TO_BLOCK_OR_CASE = new Enclosing.BlockOrCase<>(IS_LOOP_STATEMENT, Matchers.<CaseTree>nothing()); final List<ScannerTest> tests = new ArrayList<>(); @After public void tearDown() { for (ScannerTest test : tests) { test.assertDone(); } } /** Tests that a node is not enclosed by itself. */ @Test public void usedDirectlyInLoopCondition() { writeFile( "A.java", """ public
IsInterestingLoopSubNode
java
apache__camel
components/camel-rocketmq/src/test/java/org/apache/camel/component/rocketmq/RocketMQRouteIT.java
{ "start": 1492, "end": 3693 }
class ____ extends RocketMQTestSupport { public static final String EXPECTED_MESSAGE = "hello, RocketMQ."; private static final String START_ENDPOINT_URI = "rocketmq:START_TOPIC?producerGroup=p1&consumerGroup=c1&sendTag=startTag"; private static final String RESULT_ENDPOINT_URI = "mock:result"; private static final int MESSAGE_COUNT = 5; private CountDownLatch latch = new CountDownLatch(MESSAGE_COUNT); @BeforeAll static void beforeAll() throws Exception { rocketMQService.createTopic("START_TOPIC"); } @Override protected CamelContext createCamelContext() throws Exception { CamelContext camelContext = super.createCamelContext(); RocketMQComponent rocketMQComponent = new RocketMQComponent(); rocketMQComponent.setNamesrvAddr(rocketMQService.nameserverAddress()); camelContext.addComponent("rocketmq", rocketMQComponent); return camelContext; } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from(START_ENDPOINT_URI) .process(e -> latch.countDown()) .to(RESULT_ENDPOINT_URI); } }; } @Test public void testSimpleRoute() throws Exception { MockEndpoint resultEndpoint = getMockEndpoint(RESULT_ENDPOINT_URI); resultEndpoint.expectedBodiesReceived(EXPECTED_MESSAGE); // It is very slow, so we are lenient and OK if we receive just 1 message resultEndpoint.message(0).header(RocketMQConstants.TOPIC).isEqualTo("START_TOPIC"); resultEndpoint.message(0).header(RocketMQConstants.TAG).isEqualTo("startTag"); for (int i = 0; i < MESSAGE_COUNT; i++) { template.sendBody(START_ENDPOINT_URI, EXPECTED_MESSAGE); } Assertions.assertTrue(latch.await(5, TimeUnit.SECONDS), "Should have received a message"); resultEndpoint.assertIsSatisfied(); } @AfterAll public static void afterAll() throws IOException, InterruptedException { rocketMQService.deleteTopic("START_TOPIC"); } }
RocketMQRouteIT
java
netty__netty
codec-socks/src/test/java/io/netty/handler/codec/socks/SocksCommonTestUtils.java
{ "start": 868, "end": 1210 }
class ____ constructed. */ private SocksCommonTestUtils() { //NOOP } @SuppressWarnings("deprecation") public static void writeMessageIntoEmbedder(EmbeddedChannel embedder, SocksMessage msg) { ByteBuf buf = Unpooled.buffer(); msg.encodeAsByteBuf(buf); embedder.writeInbound(buf); } }
being
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/VolumeChoosingPolicy.java
{ "start": 1099, "end": 1841 }
interface ____<V extends FsVolumeSpi> { /** * Choose a volume to place a replica, * given a list of volumes and the replica size sought for storage. * * The caller should synchronize access to the list of volumes. * * @param volumes - a list of available volumes. * @param replicaSize - the size of the replica for which a volume is sought. * @param storageId - the storage id of the Volume nominated by the namenode. * This can usually be ignored by the VolumeChoosingPolicy. * @return the chosen volume. * @throws IOException when disks are unavailable or are full. */ V chooseVolume(List<V> volumes, long replicaSize, String storageId) throws IOException; }
VolumeChoosingPolicy
java
mapstruct__mapstruct
processor/src/test/java/org/mapstruct/ap/test/selection/generics/WildCardExtendsMBWrapper.java
{ "start": 258, "end": 546 }
class ____<T> { private T wrapped; public WildCardExtendsMBWrapper(T wrapped) { this.wrapped = wrapped; } public T getWrapped() { return wrapped; } public void setWrapped(T wrapped) { this.wrapped = wrapped; } }
WildCardExtendsMBWrapper
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/util/PrimitiveArrayBuilder.java
{ "start": 4393, "end": 5268 }
class ____<T> { /** * Data stored in this node. */ final T _data; /** * Number entries in the (untyped) array. Offset is assumed to be 0. */ final int _dataLength; Node<T> _next; public Node(T data, int dataLen) { _data = data; _dataLength = dataLen; } public T getData() { return _data; } public int copyData(T dst, int ptr) { System.arraycopy(_data, 0, dst, ptr, _dataLength); ptr += _dataLength; return ptr; } public Node<T> next() { return _next; } public void linkNext(Node<T> next) { if (_next != null) { // sanity check throw new IllegalStateException(); } _next = next; } } }
Node
java
mybatis__mybatis-3
src/main/java/org/apache/ibatis/plugin/Invocation.java
{ "start": 1090, "end": 1980 }
class ____ { private static final List<Class<?>> targetClasses = Arrays.asList(Executor.class, ParameterHandler.class, ResultSetHandler.class, StatementHandler.class); private final Object target; private final Method method; private final Object[] args; public Invocation(Object target, Method method, Object[] args) { if (!targetClasses.contains(method.getDeclaringClass())) { throw new IllegalArgumentException("Method '" + method + "' is not supported as a plugin target."); } this.target = target; this.method = method; this.args = args; } public Object getTarget() { return target; } public Method getMethod() { return method; } public Object[] getArgs() { return args; } public Object proceed() throws InvocationTargetException, IllegalAccessException { return method.invoke(target, args); } }
Invocation
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/impl/streams/TestStreamFactories.java
{ "start": 11236, "end": 11527 }
class ____ extends CustomFactory { public FactoryFailsToInstantiate() { throw new UncheckedIOException("failed to instantiate", new IOException()); } } /** * Callbacks from {@link ObjectInputStreamFactory} instances. */ private static final
FactoryFailsToInstantiate
java
redisson__redisson
redisson/src/main/java/org/redisson/client/protocol/decoder/AggregationCursorResultDecoder.java
{ "start": 913, "end": 1662 }
class ____ implements MultiDecoder<Object> { @Override public Object decode(List<Object> parts, State state) { if (parts.isEmpty()) { return new AggregationResult(0, Collections.emptyList(), -1); } List<Object> list = (List<Object>) parts.get(0); long total = (long) list.get(0); List<Map<String, Object>> docs = new ArrayList<>(); if (total > 0) { for (int i = 1; i < list.size(); i++) { Map<String, Object> attrs = (Map<String, Object>) list.get(i); docs.add(attrs); } } long cursorId = (long) parts.get(1); return new AggregationResult(total, docs, cursorId); } }
AggregationCursorResultDecoder
java
google__guava
android/guava-tests/test/com/google/common/util/concurrent/FuturesTest.java
{ "start": 19418, "end": 20127 }
class ____ implements AsyncFunction<Object, Object> { @SuppressWarnings("nullness:initialization.field.uninitialized") ListenableFuture<Object> output; @Override public ListenableFuture<Object> apply(Object input) { output.cancel(false); throw new SomeError(); } } Transformer transformer = new Transformer(); SettableFuture<Object> input = SettableFuture.create(); ListenableFuture<Object> output = transformAsync(input, transformer, directExecutor()); transformer.output = output; input.set("foo"); assertTrue(output.isCancelled()); } public void testTransformAsync_exceptionAfterCancellation() throws Exception {
Transformer
java
google__error-prone
core/src/test/java/com/google/errorprone/bugpatterns/CompareToZeroTest.java
{ "start": 2541, "end": 3019 }
class ____ { boolean test(Integer i) { // BUG: Diagnostic matches: KEY return i.compareTo(2) >= 1; } } """) .expectErrorMessage( "KEY", msg -> msg.contains("consistency") && !msg.contains("implementation")) .doTest(); } @Test public void positiveAddition() { compilationHelper .addSourceLines( "Test.java", """
Test
java
apache__flink
flink-formats/flink-parquet/src/main/java/org/apache/flink/formats/parquet/protobuf/PatchedProtoWriteSupport.java
{ "start": 10011, "end": 10854 }
enum ____ written for {}", enumNameNumberMapping.getKey()); } int idx = 0; for (Map.Entry<String, Integer> nameNumberPair : enumNameNumberMapping.getValue().entrySet()) { nameNumberPairs .append(nameNumberPair.getKey()) .append(METADATA_ENUM_KEY_VALUE_SEPARATOR) .append(nameNumberPair.getValue()); idx++; if (idx < enumNameNumberMapping.getValue().size()) { nameNumberPairs.append(METADATA_ENUM_ITEM_SEPARATOR); } } enumMetadata.put( METADATA_ENUM_PREFIX + enumNameNumberMapping.getKey(), nameNumberPairs.toString()); } return enumMetadata; }
is
java
google__auto
value/src/main/java/com/google/auto/value/processor/BuilderSpec.java
{ "start": 4772, "end": 5236 }
class ____ an" + " interface"); } else if (!builderTypeElement.getModifiers().contains(Modifier.STATIC)) { return Optional.of( "[AutoValueInnerBuilder] @AutoValue.Builder cannot be applied to a non-static class"); } else if (builderTypeElement.getKind().equals(ElementKind.CLASS) && !hasVisibleNoArgConstructor(builderTypeElement)) { return Optional.of( "[AutoValueBuilderConstructor] @AutoValue.Builder
or
java
google__guava
android/guava/src/com/google/common/collect/MinMaxPriorityQueue.java
{ "start": 4777, "end": 7107 }
class ____<E> extends AbstractQueue<E> { /** * Creates a new min-max priority queue with default settings: natural order, no maximum size, no * initial contents, and an initial expected size of 11. */ public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create() { return new Builder<Comparable<E>>(Ordering.natural()).create(); } /** * Creates a new min-max priority queue using natural order, no maximum size, and initially * containing the given elements. */ public static <E extends Comparable<E>> MinMaxPriorityQueue<E> create( Iterable<? extends E> initialContents) { return new Builder<E>(Ordering.natural()).create(initialContents); } /** * Creates and returns a new builder, configured to build {@code MinMaxPriorityQueue} instances * that use {@code comparator} to determine the least and greatest elements. */ /* * TODO(cpovirk): Change to Comparator<? super B> to permit Comparator<@Nullable ...> and * Comparator<SupertypeOfB>? What we have here matches the immutable collections, but those also * expose a public Builder constructor that accepts "? super." So maybe we should do *that* * instead. */ public static <B> Builder<B> orderedBy(Comparator<B> comparator) { return new Builder<>(comparator); } /** * Creates and returns a new builder, configured to build {@code MinMaxPriorityQueue} instances * sized appropriately to hold {@code expectedSize} elements. */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static Builder<Comparable> expectedSize(int expectedSize) { return new Builder<Comparable>(Ordering.natural()).expectedSize(expectedSize); } /** * Creates and returns a new builder, configured to build {@code MinMaxPriorityQueue} instances * that are limited to {@code maximumSize} elements. Each time a queue grows beyond this bound, it * immediately removes its greatest element (according to its comparator), which might be the * element that was just added. */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static Builder<Comparable> maximumSize(int maximumSize) { return new Builder<Comparable>(Ordering.natural()).maximumSize(maximumSize); } /** * The builder
MinMaxPriorityQueue
java
google__guava
android/guava/src/com/google/common/base/CharMatcher.java
{ "start": 48732, "end": 49509 }
class ____ extends CharMatcher { final CharMatcher first; final CharMatcher second; And(CharMatcher a, CharMatcher b) { first = checkNotNull(a); second = checkNotNull(b); } @Override public boolean matches(char c) { return first.matches(c) && second.matches(c); } @GwtIncompatible // used only from other GwtIncompatible code @Override void setBits(BitSet table) { BitSet tmp1 = new BitSet(); first.setBits(tmp1); BitSet tmp2 = new BitSet(); second.setBits(tmp2); tmp1.and(tmp2); table.or(tmp1); } @Override public String toString() { return first + ".and(" + second + ")"; } } /** Implementation of {@link #or(CharMatcher)}. */ private static final
And
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/antora/CheckJavadocMacros.java
{ "start": 11793, "end": 12662 }
class ____ extends ClassVisitor { private final MethodAnchor methodAnchor; private boolean matched = false; private MethodMatcher(MethodAnchor methodAnchor) { super(SpringAsmInfo.ASM_VERSION); this.methodAnchor = methodAnchor; } @Override public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { if (!this.matched && name.equals(this.methodAnchor.name)) { Type type = Type.getType(descriptor); if (type.getArgumentCount() == this.methodAnchor.arguments.size()) { List<String> argumentTypeNames = Arrays.asList(type.getArgumentTypes()) .stream() .map(Type::getClassName) .toList(); if (argumentTypeNames.equals(this.methodAnchor.arguments)) { this.matched = true; } } } return null; } } private static final
MethodMatcher
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/view/UrlBasedViewResolver.java
{ "start": 1668, "end": 2409 }
class ____ all views generated by this resolver can be specified * via the "viewClass" property. * * <p>View names can either be resource URLs themselves, or get augmented by a * specified prefix and/or suffix. Exporting an attribute that holds the * RequestContext to all views is explicitly supported. * * <p>Example: prefix="templates/", suffix=".ftl", viewname="test" &rarr; * "templates/test.ftl" * * <p>As a special feature, redirect URLs can be specified via the "redirect:" * prefix. For example: "redirect:myAction" will trigger a redirect to the given * URL, rather than resolution as standard view name. This is typically used * for redirecting to a controller URL after finishing a form workflow. * * <p>Note: This
for
java
spring-projects__spring-framework
spring-webflux/src/main/java/org/springframework/web/reactive/result/condition/NameValueExpression.java
{ "start": 972, "end": 1079 }
interface ____<T> { String getName(); @Nullable T getValue(); boolean isNegated(); }
NameValueExpression
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/namenode/top/TopConf.java
{ "start": 1177, "end": 1270 }
class ____ a common place for NNTop configuration. */ @InterfaceAudience.Private public final
is
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/heap/HeapKeyValueStateIterator.java
{ "start": 9182, "end": 12821 }
class ____ implements SingleStateIterator { private final Iterator<? extends StateEntry<?, ?, ?>> entriesIterator; private final RegisteredKeyValueStateBackendMetaInfo<?, ?> stateSnapshot; private StateTableIterator( Iterator<? extends StateEntry<?, ?, ?>> entriesIterator, RegisteredKeyValueStateBackendMetaInfo<?, ?> stateSnapshot) { this.entriesIterator = entriesIterator; this.stateSnapshot = stateSnapshot; } @Override public boolean hasNext() { return entriesIterator.hasNext(); } @Override public boolean writeOutNext() throws IOException { StateEntry<?, ?, ?> currentEntry = entriesIterator.next(); valueOut.clear(); compositeKeyBuilder.setKeyAndKeyGroup(currentEntry.getKey(), keyGroup()); compositeKeyBuilder.setNamespace( currentEntry.getNamespace(), castToType(stateSnapshot.getNamespaceSerializer())); TypeSerializer<?> stateSerializer = stateSnapshot.getStateSerializer(); switch (stateSnapshot.getStateType()) { case AGGREGATING: case REDUCING: case FOLDING: case VALUE: return writeOutValue(currentEntry, stateSerializer); case LIST: return writeOutList(currentEntry, stateSerializer); case MAP: return writeOutMap(currentEntry, stateSerializer); default: throw new IllegalStateException(""); } } private boolean writeOutValue( StateEntry<?, ?, ?> currentEntry, TypeSerializer<?> stateSerializer) throws IOException { currentKey = compositeKeyBuilder.build(); castToType(stateSerializer).serialize(currentEntry.getState(), valueOut); currentValue = valueOut.getCopyOfBuffer(); return true; } @SuppressWarnings("unchecked") private boolean writeOutList( StateEntry<?, ?, ?> currentEntry, TypeSerializer<?> stateSerializer) throws IOException { List<Object> state = (List<Object>) currentEntry.getState(); if (state.isEmpty()) { return false; } ListSerializer<Object> listSerializer = (ListSerializer<Object>) stateSerializer; currentKey = compositeKeyBuilder.build(); currentValue = listDelimitedSerializer.serializeList( state, listSerializer.getElementSerializer()); return true; } @SuppressWarnings("unchecked") private boolean writeOutMap( StateEntry<?, ?, ?> currentEntry, TypeSerializer<?> stateSerializer) throws IOException { Map<Object, Object> state = (Map<Object, Object>) currentEntry.getState(); if (state.isEmpty()) { return false; } MapSerializer<Object, Object> mapSerializer = (MapSerializer<Object, Object>) stateSerializer; currentStateIterator = new MapStateIterator( state, mapSerializer.getKeySerializer(), mapSerializer.getValueSerializer(), this); return currentStateIterator.writeOutNext(); } } private final
StateTableIterator
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/bootstrap/ConsoleLoader.java
{ "start": 1077, "end": 3145 }
class ____ { private static final String CONSOLE_LOADER_CLASS = "org.elasticsearch.io.ansi.AnsiConsoleLoader"; public static Console loadConsole(Environment env) { final ClassLoader classLoader = buildClassLoader(env); final Supplier<Console> supplier = buildConsoleLoader(classLoader); return supplier.get(); } public record Console(PrintStream printStream, Supplier<Integer> width, Boolean ansiEnabled, @Nullable Charset charset) {} @SuppressWarnings("unchecked") static Supplier<Console> buildConsoleLoader(ClassLoader classLoader) { try { final Class<? extends Supplier<Console>> cls = (Class<? extends Supplier<Console>>) classLoader.loadClass(CONSOLE_LOADER_CLASS); final Constructor<? extends Supplier<Console>> constructor = cls.getConstructor(); final Supplier<Console> supplier = constructor.newInstance(); return supplier; } catch (ReflectiveOperationException e) { throw new RuntimeException("Failed to load ANSI console", e); } } private static ClassLoader buildClassLoader(Environment env) { final Path libDir = env.libDir().resolve("tools").resolve("ansi-console"); try (var libDirFilesStream = Files.list(libDir)) { final URL[] urls = libDirFilesStream.filter(each -> each.getFileName().toString().endsWith(".jar")) .map(ConsoleLoader::pathToURL) .toArray(URL[]::new); return URLClassLoader.newInstance(urls, ConsoleLoader.class.getClassLoader()); } catch (IOException e) { throw new RuntimeException("Failed to list jars in [" + libDir + "]: " + e.getMessage(), e); } } private static URL pathToURL(Path path) { try { return path.toUri().toURL(); } catch (MalformedURLException e) { // Shouldn't happen, but have to handle the exception throw new RuntimeException("Failed to convert path [" + path + "] to URL", e); } } }
ConsoleLoader
java
assertj__assertj-core
assertj-core/src/test/java/org/assertj/core/internal/iterables/SinglyIterableFactory.java
{ "start": 714, "end": 863 }
class ____ { static Iterable<String> createSinglyIterable(final List<String> values) { // can't use Iterable<> for anonymous
SinglyIterableFactory
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/builder/xml/XPathFunctionsTest.java
{ "start": 1075, "end": 3482 }
class ____ extends ContextTestSupport { @Test public void testChoiceWithHeaderAndPropertiesSelectCamel() throws Exception { MockEndpoint mock = getMockEndpoint("mock:camel"); mock.expectedBodiesReceived("<name>King</name>"); mock.expectedHeaderReceived("type", "Camel"); template.sendBodyAndHeader("direct:in", "<name>King</name>", "type", "Camel"); mock.assertIsSatisfied(); } @Test public void testChoiceWithNoHeaderAndPropertiesSelectDonkey() throws Exception { MockEndpoint mock = getMockEndpoint("mock:donkey"); mock.expectedBodiesReceived("<name>Donkey Kong</name>"); template.sendBody("direct:in", "<name>Donkey Kong</name>"); mock.assertIsSatisfied(); } @Test public void testChoiceWithNoHeaderAndPropertiesSelectOther() throws Exception { MockEndpoint mock = getMockEndpoint("mock:other"); mock.expectedBodiesReceived("<name>Other</name>"); template.sendBody("direct:in", "<name>Other</name>"); mock.assertIsSatisfied(); } @Override protected RouteBuilder createRouteBuilder() { return new RouteBuilder() { public void configure() { // START SNIPPET: ex // setup properties component context.getPropertiesComponent().setLocation("classpath:org/apache/camel/builder/xml/myprop.properties"); // myprop.properties contains the following properties // foo=Camel // bar=Kong from("direct:in").choice() // $type is a variable for the header with key type // here we use the properties function to lookup foo from // the properties files // which at runtime will be evaluated to 'Camel' .when().xpath("$type = function:properties('foo')").to("mock:camel") // here we use the simple language to evaluate the // expression // which at runtime will be evaluated to 'Donkey Kong' .when().xpath("//name = function:simple('Donkey {{bar}}')").to("mock:donkey").otherwise() .to("mock:other").end(); // END SNIPPET: ex } }; } }
XPathFunctionsTest
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/java/org/elasticsearch/xpack/esql/ExceptionUtils.java
{ "start": 434, "end": 2076 }
class ____ { /** * Create a {@link VerificationException} from an {@link ArithmeticException} thrown because of an invalid math expression. * * @param source the invalid part of the query causing the exception * @param e the exception that was thrown * @return an exception with a user-readable error message with http code 400 */ public static VerificationException math(Source source, ArithmeticException e) { return new VerificationException("arithmetic exception in expression [{}]: [{}]", source.text(), e.getMessage()); } /** * We generally prefer to avoid assertions in production code, as they can kill the entire node if they fail, instead of just failing * a given test. So instead, we throw an {@link IllegalStateException}. Like proper asserts, this will only be executed if assertions * are enabled. */ public static void assertIllegalState(Boolean condition, String message) { if (Assertions.ENABLED && condition == false) { throw new IllegalStateException(message); } } /** * We generally prefer to avoid assertions in production code, as they can kill the entire node if they fail, instead of just failing * a given test. So instead, we throw an {@link IllegalStateException}. Like proper asserts, this will only be executed if assertions * are enabled. */ public static void assertIllegalState(Supplier<Boolean> condition, String message) { if (Assertions.ENABLED && condition.get() == false) { throw new IllegalStateException(message); } } }
ExceptionUtils
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-nodemanager/src/test/java/org/apache/hadoop/yarn/server/nodemanager/webapp/TestNMWebServicesApps.java
{ "start": 3897, "end": 4901 }
class ____ extends JerseyTestBase { private static Context nmContext; private static ResourceView resourceView; private static ApplicationACLsManager aclsManager; private static LocalDirsHandlerService dirsHandler; private static WebApp nmWebApp; private static Configuration conf = new Configuration(); private static final File testRootDir = new File("target", TestNMWebServicesApps.class.getSimpleName()); private static File testLogDir = new File("target", TestNMWebServicesApps.class.getSimpleName() + "LogDir"); @Override protected javax.ws.rs.core.Application configure() { ResourceConfig config = new ResourceConfig(); config.register(new JerseyBinder()); config.register(NMWebServices.class); config.register(GenericExceptionHandler.class); config.register(new JettisonFeature()).register(JAXBContextResolver.class); forceSet(TestProperties.CONTAINER_PORT, JERSEY_RANDOM_PORT); return config; } private static
TestNMWebServicesApps
java
apache__flink
flink-core/src/main/java/org/apache/flink/core/io/VersionedIOReadableWritable.java
{ "start": 1101, "end": 1404 }
class ____ {@link IOReadableWritable} which allows to differentiate * between serialization versions. Concrete subclasses should typically override the {@link * #write(DataOutputView)} and {@link #read(DataInputView)}, thereby calling super to ensure version * checking. */ @Internal public abstract
for
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/launcher/core/LauncherConfigurationParametersTests.java
{ "start": 10257, "end": 10462 }
class ____ { // `public` is needed for simple "Class#getField(String)" to work public String thing = "body."; @Test void some() { assertEquals("Someone else!", "Some" + thing); } } }
Something
java
spring-projects__spring-security
web/src/main/java/org/springframework/security/web/debug/DebugFilter.java
{ "start": 5158, "end": 5806 }
class ____ extends HttpServletRequestWrapper { private static final Logger logger = new Logger(); DebugRequestWrapper(HttpServletRequest request) { super(request); } @Override public HttpSession getSession() { boolean sessionExists = super.getSession(false) != null; HttpSession session = super.getSession(); if (!sessionExists) { DebugRequestWrapper.logger.info("New HTTP session created: " + session.getId(), true); } return session; } @Override public HttpSession getSession(boolean create) { if (!create) { return super.getSession(create); } return getSession(); } } }
DebugRequestWrapper
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/unused/RemoveUnusedComponentsTest.java
{ "start": 202, "end": 520 }
class ____ { protected void assertPresent(Class<?> beanClass) { assertTrue(Arc.container().instance(beanClass).isAvailable()); } protected void assertNotPresent(Class<?> beanClass) { assertEquals(0, Arc.container().beanManager().getBeans(beanClass).size()); } }
RemoveUnusedComponentsTest
java
grpc__grpc-java
okhttp/src/main/java/io/grpc/okhttp/OkHttpClientTransport.java
{ "start": 10526, "end": 48647 }
class ____<T> extends LinkedHashMap<String, T> { @Override protected boolean removeEldestEntry(Map.Entry<String, T> eldest) { return size() > 100; } } @GuardedBy("lock") private final Map<String, Status> authorityVerificationResults = new LruCache<>(); @GuardedBy("lock") private final InUseStateAggregator<OkHttpClientStream> inUseState = new InUseStateAggregator<OkHttpClientStream>() { @Override protected void handleInUse() { listener.transportInUse(true); } @Override protected void handleNotInUse() { listener.transportInUse(false); } }; @GuardedBy("lock") private InternalChannelz.Security securityInfo; @VisibleForTesting @Nullable final HttpConnectProxiedSocketAddress proxiedAddr; @VisibleForTesting int proxySocketTimeout = 30000; // The following fields should only be used for test. Runnable connectingCallback; SettableFuture<Void> connectedFuture; public OkHttpClientTransport( OkHttpTransportFactory transportFactory, InetSocketAddress address, String authority, @Nullable String userAgent, Attributes eagAttrs, @Nullable HttpConnectProxiedSocketAddress proxiedAddr, Runnable tooManyPingsRunnable, ChannelCredentials channelCredentials) { this( transportFactory, address, authority, userAgent, eagAttrs, GrpcUtil.STOPWATCH_SUPPLIER, new Http2(), proxiedAddr, tooManyPingsRunnable, channelCredentials); } private OkHttpClientTransport( OkHttpTransportFactory transportFactory, InetSocketAddress address, String authority, @Nullable String userAgent, Attributes eagAttrs, Supplier<Stopwatch> stopwatchFactory, Variant variant, @Nullable HttpConnectProxiedSocketAddress proxiedAddr, Runnable tooManyPingsRunnable, ChannelCredentials channelCredentials) { this.address = Preconditions.checkNotNull(address, "address"); this.defaultAuthority = authority; this.maxMessageSize = transportFactory.maxMessageSize; this.initialWindowSize = transportFactory.flowControlWindow; this.executor = Preconditions.checkNotNull(transportFactory.executor, "executor"); serializingExecutor = new SerializingExecutor(transportFactory.executor); this.scheduler = Preconditions.checkNotNull( transportFactory.scheduledExecutorService, "scheduledExecutorService"); // Client initiated streams are odd, server initiated ones are even. Server should not need to // use it. We start clients at 3 to avoid conflicting with HTTP negotiation. nextStreamId = 3; this.socketFactory = transportFactory.socketFactory == null ? SocketFactory.getDefault() : transportFactory.socketFactory; this.sslSocketFactory = transportFactory.sslSocketFactory; this.hostnameVerifier = transportFactory.hostnameVerifier != null ? transportFactory.hostnameVerifier : OkHostnameVerifier.INSTANCE; this.connectionSpec = Preconditions.checkNotNull( transportFactory.connectionSpec, "connectionSpec"); this.stopwatchFactory = Preconditions.checkNotNull(stopwatchFactory, "stopwatchFactory"); this.variant = Preconditions.checkNotNull(variant, "variant"); this.userAgent = GrpcUtil.getGrpcUserAgent("okhttp", userAgent); this.proxiedAddr = proxiedAddr; this.tooManyPingsRunnable = Preconditions.checkNotNull(tooManyPingsRunnable, "tooManyPingsRunnable"); this.maxInboundMetadataSize = transportFactory.maxInboundMetadataSize; this.transportTracer = transportFactory.transportTracerFactory.create(); this.logId = InternalLogId.allocate(getClass(), address.toString()); this.attributes = Attributes.newBuilder() .set(GrpcAttributes.ATTR_CLIENT_EAG_ATTRS, eagAttrs).build(); this.useGetForSafeMethods = transportFactory.useGetForSafeMethods; initTransportTracer(); TrustManager tempX509TrustManager; if (channelCredentials instanceof TlsChannelCredentials && x509ExtendedTrustManagerClass != null) { try { tempX509TrustManager = getTrustManager( (TlsChannelCredentials) channelCredentials); } catch (GeneralSecurityException e) { tempX509TrustManager = null; log.log(Level.WARNING, "Obtaining X509ExtendedTrustManager for the transport failed." + "Per-rpc authority overrides will be disallowed.", e); } } else { tempX509TrustManager = null; } x509TrustManager = tempX509TrustManager; } /** * Create a transport connected to a fake peer for test. */ @SuppressWarnings("AddressSelection") // An IP address always returns one address @VisibleForTesting OkHttpClientTransport( OkHttpTransportFactory transportFactory, String userAgent, Supplier<Stopwatch> stopwatchFactory, Variant variant, @Nullable Runnable connectingCallback, SettableFuture<Void> connectedFuture, Runnable tooManyPingsRunnable) { this( transportFactory, new InetSocketAddress("127.0.0.1", 80), "notarealauthority:80", userAgent, Attributes.EMPTY, stopwatchFactory, variant, null, tooManyPingsRunnable, null); this.connectingCallback = connectingCallback; this.connectedFuture = Preconditions.checkNotNull(connectedFuture, "connectedFuture"); } // sslSocketFactory is set to null when use plaintext. boolean isUsingPlaintext() { return sslSocketFactory == null; } private void initTransportTracer() { synchronized (lock) { // to make @GuardedBy linter happy transportTracer.setFlowControlWindowReader(new TransportTracer.FlowControlReader() { @Override public TransportTracer.FlowControlWindows read() { synchronized (lock) { long local = outboundFlow == null ? -1 : outboundFlow.windowUpdate(null, 0); // connectionUnacknowledgedBytesRead is only readable by ClientFrameHandler, so we // provide a lower bound. long remote = (long) (initialWindowSize * DEFAULT_WINDOW_UPDATE_RATIO); return new TransportTracer.FlowControlWindows(local, remote); } } }); } } /** * Enable keepalive with custom delay and timeout. */ void enableKeepAlive(boolean enable, long keepAliveTimeNanos, long keepAliveTimeoutNanos, boolean keepAliveWithoutCalls) { enableKeepAlive = enable; this.keepAliveTimeNanos = keepAliveTimeNanos; this.keepAliveTimeoutNanos = keepAliveTimeoutNanos; this.keepAliveWithoutCalls = keepAliveWithoutCalls; } @Override public void ping(final PingCallback callback, Executor executor) { long data = 0; Http2Ping p; boolean writePing; synchronized (lock) { checkState(frameWriter != null); if (stopped) { Http2Ping.notifyFailed(callback, executor, getPingFailure()); return; } if (ping != null) { // we only allow one outstanding ping at a time, so just add the callback to // any outstanding operation p = ping; writePing = false; } else { // set outstanding operation and then write the ping after releasing lock data = random.nextLong(); Stopwatch stopwatch = stopwatchFactory.get(); stopwatch.start(); p = ping = new Http2Ping(data, stopwatch); writePing = true; transportTracer.reportKeepAliveSent(); } if (writePing) { frameWriter.ping(false, (int) (data >>> 32), (int) data); } } // If transport concurrently failed/stopped since we released the lock above, this could // immediately invoke callback (which we shouldn't do while holding a lock) p.addCallback(callback, executor); } @Override public OkHttpClientStream newStream( MethodDescriptor<?, ?> method, Metadata headers, CallOptions callOptions, ClientStreamTracer[] tracers) { Preconditions.checkNotNull(method, "method"); Preconditions.checkNotNull(headers, "headers"); StatsTraceContext statsTraceContext = StatsTraceContext.newClientContext(tracers, getAttributes(), headers); // FIXME: it is likely wrong to pass the transportTracer here as it'll exit the lock's scope synchronized (lock) { // to make @GuardedBy linter happy return new OkHttpClientStream( method, headers, frameWriter, OkHttpClientTransport.this, outboundFlow, lock, maxMessageSize, initialWindowSize, defaultAuthority, userAgent, statsTraceContext, transportTracer, callOptions, useGetForSafeMethods); } } private TrustManager getTrustManager(TlsChannelCredentials tlsCreds) throws GeneralSecurityException { TrustManager[] tm; // Using the same way of creating TrustManager from OkHttpChannelBuilder.sslSocketFactoryFrom() if (tlsCreds.getTrustManagers() != null) { tm = tlsCreds.getTrustManagers().toArray(new TrustManager[0]); } else if (tlsCreds.getRootCertificates() != null) { tm = CertificateUtils.createTrustManager(tlsCreds.getRootCertificates()); } else { // else use system default TrustManagerFactory tmf = TrustManagerFactory.getInstance( TrustManagerFactory.getDefaultAlgorithm()); tmf.init((KeyStore) null); tm = tmf.getTrustManagers(); } for (TrustManager trustManager: tm) { if (trustManager instanceof X509TrustManager) { return trustManager; } } return null; } @GuardedBy("lock") void streamReadyToStart(OkHttpClientStream clientStream, String authority) { if (goAwayStatus != null) { clientStream.transportState().transportReportStatus( goAwayStatus, RpcProgress.MISCARRIED, true, new Metadata()); } else { if (socket instanceof SSLSocket && !authority.equals(defaultAuthority)) { Status authorityVerificationResult; if (authorityVerificationResults.containsKey(authority)) { authorityVerificationResult = authorityVerificationResults.get(authority); } else { authorityVerificationResult = verifyAuthority(authority); authorityVerificationResults.put(authority, authorityVerificationResult); } if (!authorityVerificationResult.isOk()) { if (enablePerRpcAuthorityCheck) { clientStream.transportState().transportReportStatus( authorityVerificationResult, RpcProgress.PROCESSED, true, new Metadata()); return; } } } if (streams.size() >= maxConcurrentStreams) { pendingStreams.add(clientStream); setInUse(clientStream); } else { startStream(clientStream); } } } private Status verifyAuthority(String authority) { Status authorityVerificationResult; if (hostnameVerifier.verify(authority, ((SSLSocket) socket).getSession())) { authorityVerificationResult = Status.OK; } else { authorityVerificationResult = Status.UNAVAILABLE.withDescription(String.format( "HostNameVerifier verification failed for authority '%s'", authority)); } if (!authorityVerificationResult.isOk() && !enablePerRpcAuthorityCheck) { log.log(Level.WARNING, String.format("HostNameVerifier verification failed for " + "authority '%s'. This will be an error in the future.", authority)); } if (authorityVerificationResult.isOk()) { // The status is trivially assigned in this case, but we are still making use of the // cache to keep track that a warning log had been logged for the authority when // enablePerRpcAuthorityCheck is false. When we permanently enable the feature, the // status won't need to be cached for case when x509TrustManager is null. if (x509TrustManager == null) { authorityVerificationResult = Status.UNAVAILABLE.withDescription( String.format("Could not verify authority '%s' for the rpc with no " + "X509TrustManager available", authority)); } else if (x509ExtendedTrustManagerClass.isInstance(x509TrustManager)) { try { Certificate[] peerCertificates = sslSession.getPeerCertificates(); X509Certificate[] x509PeerCertificates = new X509Certificate[peerCertificates.length]; for (int i = 0; i < peerCertificates.length; i++) { x509PeerCertificates[i] = (X509Certificate) peerCertificates[i]; } checkServerTrustedMethod.invoke(x509TrustManager, x509PeerCertificates, "RSA", new SslSocketWrapper((SSLSocket) socket, authority)); authorityVerificationResult = Status.OK; } catch (SSLPeerUnverifiedException | InvocationTargetException | IllegalAccessException e) { authorityVerificationResult = Status.UNAVAILABLE.withCause(e).withDescription( "Peer verification failed"); } if (authorityVerificationResult.getCause() != null) { log.log(Level.WARNING, authorityVerificationResult.getDescription() + ". This will be an error in the future.", authorityVerificationResult.getCause()); } else { log.log(Level.WARNING, authorityVerificationResult.getDescription() + ". This will be an error in the future."); } } } return authorityVerificationResult; } @SuppressWarnings("GuardedBy") @GuardedBy("lock") private void startStream(OkHttpClientStream stream) { checkState( stream.transportState().id() == OkHttpClientStream.ABSENT_ID, "StreamId already assigned"); streams.put(nextStreamId, stream); setInUse(stream); // TODO(b/145386688): This access should be guarded by 'stream.transportState().lock'; instead // found: 'this.lock' stream.transportState().start(nextStreamId); // For unary and server streaming, there will be a data frame soon, no need to flush the header. if ((stream.getType() != MethodType.UNARY && stream.getType() != MethodType.SERVER_STREAMING) || stream.useGet()) { frameWriter.flush(); } if (nextStreamId >= Integer.MAX_VALUE - 2) { // Make sure nextStreamId greater than all used id, so that mayHaveCreatedStream() performs // correctly. nextStreamId = Integer.MAX_VALUE; startGoAway(Integer.MAX_VALUE, ErrorCode.NO_ERROR, Status.UNAVAILABLE.withDescription("Stream ids exhausted")); } else { nextStreamId += 2; } } /** * Starts pending streams, returns true if at least one pending stream is started. */ @GuardedBy("lock") private boolean startPendingStreams() { boolean hasStreamStarted = false; while (!pendingStreams.isEmpty() && streams.size() < maxConcurrentStreams) { OkHttpClientStream stream = pendingStreams.poll(); startStream(stream); hasStreamStarted = true; } return hasStreamStarted; } /** * Removes given pending stream, used when a pending stream is cancelled. */ @GuardedBy("lock") void removePendingStream(OkHttpClientStream pendingStream) { pendingStreams.remove(pendingStream); maybeClearInUse(pendingStream); } @Override public Runnable start(Listener listener) { this.listener = Preconditions.checkNotNull(listener, "listener"); if (enableKeepAlive) { keepAliveManager = new KeepAliveManager( new ClientKeepAlivePinger(this), scheduler, keepAliveTimeNanos, keepAliveTimeoutNanos, keepAliveWithoutCalls); keepAliveManager.onTransportStarted(); } int maxQueuedControlFrames = 10000; final AsyncSink asyncSink = AsyncSink.sink(serializingExecutor, this, maxQueuedControlFrames); FrameWriter rawFrameWriter = asyncSink.limitControlFramesWriter( variant.newWriter(Okio.buffer(asyncSink), true)); synchronized (lock) { // Handle FrameWriter exceptions centrally, since there are many callers. Note that errors // coming from rawFrameWriter are generally broken invariants/bugs, as AsyncSink does not // propagate syscall errors through the FrameWriter. But we handle the AsyncSink failures with // the same TransportExceptionHandler instance so it is all mixed back together. frameWriter = new ExceptionHandlingFrameWriter(this, rawFrameWriter); outboundFlow = new OutboundFlowController(this, frameWriter); } final CountDownLatch latch = new CountDownLatch(1); final CountDownLatch latchForExtraThread = new CountDownLatch(1); // The transport needs up to two threads to function once started, // but only needs one during handshaking. Start another thread during handshaking // to make sure there's still a free thread available. If the number of threads is exhausted, // it is better to kill the transport than for all the transports to hang unable to send. CyclicBarrier barrier = new CyclicBarrier(2); // Connecting in the serializingExecutor, so that some stream operations like synStream // will be executed after connected. serializingExecutor.execute(new Runnable() { @Override public void run() { // Use closed source on failure so that the reader immediately shuts down. BufferedSource source = Okio.buffer(new Source() { @Override public long read(Buffer sink, long byteCount) { return -1; } @Override public Timeout timeout() { return Timeout.NONE; } @Override public void close() { } }); try { // This is a hack to make sure the connection preface and initial settings to be sent out // without blocking the start. By doing this essentially prevents potential deadlock when // network is not available during startup while another thread holding lock to send the // initial preface. try { latch.await(); barrier.await(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (TimeoutException | BrokenBarrierException e) { startGoAway(0, ErrorCode.INTERNAL_ERROR, Status.UNAVAILABLE .withDescription("Timed out waiting for second handshake thread. " + "The transport executor pool may have run out of threads")); return; } if (proxiedAddr == null) { sock = socketFactory.createSocket(address.getAddress(), address.getPort()); } else { if (proxiedAddr.getProxyAddress() instanceof InetSocketAddress) { sock = createHttpProxySocket( proxiedAddr.getTargetAddress(), (InetSocketAddress) proxiedAddr.getProxyAddress(), proxiedAddr.getUsername(), proxiedAddr.getPassword() ); } else { throw Status.INTERNAL.withDescription( "Unsupported SocketAddress implementation " + proxiedAddr.getProxyAddress().getClass()).asException(); } } if (sslSocketFactory != null) { SSLSocket sslSocket = OkHttpTlsUpgrader.upgrade( sslSocketFactory, hostnameVerifier, sock, getOverridenHost(), getOverridenPort(), connectionSpec); sslSession = sslSocket.getSession(); sock = sslSocket; } sock.setTcpNoDelay(true); source = Okio.buffer(Okio.source(sock)); asyncSink.becomeConnected(Okio.sink(sock), sock); // The return value of OkHttpTlsUpgrader.upgrade is an SSLSocket that has this info attributes = attributes.toBuilder() .set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, sock.getRemoteSocketAddress()) .set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, sock.getLocalSocketAddress()) .set(Grpc.TRANSPORT_ATTR_SSL_SESSION, sslSession) .set(GrpcAttributes.ATTR_SECURITY_LEVEL, sslSession == null ? SecurityLevel.NONE : SecurityLevel.PRIVACY_AND_INTEGRITY) .build(); } catch (StatusException e) { startGoAway(0, ErrorCode.INTERNAL_ERROR, e.getStatus()); return; } catch (Exception e) { onException(e); return; } finally { clientFrameHandler = new ClientFrameHandler(variant.newReader(source, true)); latchForExtraThread.countDown(); } synchronized (lock) { socket = Preconditions.checkNotNull(sock, "socket"); if (sslSession != null) { securityInfo = new InternalChannelz.Security(new InternalChannelz.Tls(sslSession)); } } } }); executor.execute(new Runnable() { @Override public void run() { try { barrier.await(1000, TimeUnit.MILLISECONDS); latchForExtraThread.await(); } catch (BrokenBarrierException | TimeoutException e) { // Something bad happened, maybe too few threads available! // This will be handled in the handshake thread. } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); // Schedule to send connection preface & settings before any other write. try { sendConnectionPrefaceAndSettings(); } finally { latch.countDown(); } serializingExecutor.execute(new Runnable() { @Override public void run() { if (connectingCallback != null) { connectingCallback.run(); } // ClientFrameHandler need to be started after connectionPreface / settings, otherwise it // may send goAway immediately. executor.execute(clientFrameHandler); synchronized (lock) { maxConcurrentStreams = Integer.MAX_VALUE; startPendingStreams(); } if (connectedFuture != null) { connectedFuture.set(null); } } }); return null; } /** * Should only be called once when the transport is first established. */ private void sendConnectionPrefaceAndSettings() { synchronized (lock) { frameWriter.connectionPreface(); Settings settings = new Settings(); OkHttpSettingsUtil.set(settings, OkHttpSettingsUtil.INITIAL_WINDOW_SIZE, initialWindowSize); frameWriter.settings(settings); if (initialWindowSize > DEFAULT_WINDOW_SIZE) { frameWriter.windowUpdate( Utils.CONNECTION_STREAM_ID, initialWindowSize - DEFAULT_WINDOW_SIZE); } } } private Socket createHttpProxySocket(InetSocketAddress address, InetSocketAddress proxyAddress, String proxyUsername, String proxyPassword) throws StatusException { Socket sock = null; try { // The proxy address may not be resolved if (proxyAddress.getAddress() != null) { sock = socketFactory.createSocket(proxyAddress.getAddress(), proxyAddress.getPort()); } else { sock = socketFactory.createSocket(proxyAddress.getHostName(), proxyAddress.getPort()); } sock.setTcpNoDelay(true); // A socket timeout is needed because lost network connectivity while reading from the proxy, // can cause reading from the socket to hang. sock.setSoTimeout(proxySocketTimeout); Source source = Okio.source(sock); BufferedSink sink = Okio.buffer(Okio.sink(sock)); // Prepare headers and request method line Request proxyRequest = createHttpProxyRequest(address, proxyUsername, proxyPassword); HttpUrl url = proxyRequest.httpUrl(); String requestLine = String.format(Locale.US, "CONNECT %s:%d HTTP/1.1", url.host(), url.port()); // Write request to socket sink.writeUtf8(requestLine).writeUtf8("\r\n"); for (int i = 0, size = proxyRequest.headers().size(); i < size; i++) { sink.writeUtf8(proxyRequest.headers().name(i)) .writeUtf8(": ") .writeUtf8(proxyRequest.headers().value(i)) .writeUtf8("\r\n"); } sink.writeUtf8("\r\n"); // Flush buffer (flushes socket and sends request) sink.flush(); // Read status line, check if 2xx was returned StatusLine statusLine = StatusLine.parse(readUtf8LineStrictUnbuffered(source)); // Drain rest of headers while (!readUtf8LineStrictUnbuffered(source).equals("")) {} if (statusLine.code < 200 || statusLine.code >= 300) { Buffer body = new Buffer(); try { sock.shutdownOutput(); source.read(body, 1024); } catch (IOException ex) { body.writeUtf8("Unable to read body: " + ex.toString()); } try { sock.close(); } catch (IOException ignored) { // ignored } String message = String.format( Locale.US, "Response returned from proxy was not successful (expected 2xx, got %d %s). " + "Response body:\n%s", statusLine.code, statusLine.message, body.readUtf8()); throw Status.UNAVAILABLE.withDescription(message).asException(); } // As the socket will be used for RPCs from here on, we want the socket timeout back to zero. sock.setSoTimeout(0); return sock; } catch (IOException e) { if (sock != null) { GrpcUtil.closeQuietly(sock); } throw Status.UNAVAILABLE.withDescription("Failed trying to connect with proxy").withCause(e) .asException(); } } private Request createHttpProxyRequest(InetSocketAddress address, String proxyUsername, String proxyPassword) { HttpUrl tunnelUrl = new HttpUrl.Builder() .scheme("https") .host(address.getHostName()) .port(address.getPort()) .build(); Request.Builder request = new Request.Builder() .url(tunnelUrl) .header("Host", tunnelUrl.host() + ":" + tunnelUrl.port()) .header("User-Agent", userAgent); // If we have proxy credentials, set them right away if (proxyUsername != null && proxyPassword != null) { request.header("Proxy-Authorization", Credentials.basic(proxyUsername, proxyPassword)); } return request.build(); } private static String readUtf8LineStrictUnbuffered(Source source) throws IOException { Buffer buffer = new Buffer(); while (true) { if (source.read(buffer, 1) == -1) { throw new EOFException("\\n not found: " + buffer.readByteString().hex()); } if (buffer.getByte(buffer.size() - 1) == '\n') { return buffer.readUtf8LineStrict(); } } } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("logId", logId.getId()) .add("address", address) .toString(); } @Override public InternalLogId getLogId() { return logId; } /** * Gets the overridden authority hostname. If the authority is overridden to be an invalid * authority, uri.getHost() will (rightly) return null, since the authority is no longer * an actual service. This method overrides the behavior for practical reasons. For example, * if an authority is in the form "invalid_authority" (note the "_"), rather than return null, * we return the input. This is because the return value, in conjunction with getOverridenPort, * are used by the SSL library to reconstruct the actual authority. It /already/ has a * connection to the port, independent of this function. * * <p>Note: if the defaultAuthority has a port number in it and is also bad, this code will do * the wrong thing. An example wrong behavior would be "invalid_host:443". Registry based * authorities do not have ports, so this is even more wrong than before. Sorry. */ @VisibleForTesting String getOverridenHost() { URI uri = GrpcUtil.authorityToUri(defaultAuthority); if (uri.getHost() != null) { return uri.getHost(); } return defaultAuthority; } @VisibleForTesting int getOverridenPort() { URI uri = GrpcUtil.authorityToUri(defaultAuthority); if (uri.getPort() != -1) { return uri.getPort(); } return address.getPort(); } @Override public void shutdown(Status reason) { synchronized (lock) { if (goAwayStatus != null) { return; } goAwayStatus = reason; listener.transportShutdown(goAwayStatus); stopIfNecessary(); } } @Override public void shutdownNow(Status reason) { shutdown(reason); synchronized (lock) { Iterator<Map.Entry<Integer, OkHttpClientStream>> it = streams.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, OkHttpClientStream> entry = it.next(); it.remove(); entry.getValue().transportState().transportReportStatus(reason, false, new Metadata()); maybeClearInUse(entry.getValue()); } for (OkHttpClientStream stream : pendingStreams) { // in cases such as the connection fails to ACK keep-alive, pending streams should have a // chance to retry and be routed to another connection. stream.transportState().transportReportStatus( reason, RpcProgress.MISCARRIED, true, new Metadata()); maybeClearInUse(stream); } pendingStreams.clear(); stopIfNecessary(); } } @Override public Attributes getAttributes() { return attributes; } /** * Gets all active streams as an array. */ @Override public OutboundFlowController.StreamState[] getActiveStreams() { synchronized (lock) { OutboundFlowController.StreamState[] flowStreams = new OutboundFlowController.StreamState[streams.size()]; int i = 0; for (OkHttpClientStream stream : streams.values()) { flowStreams[i++] = stream.transportState().getOutboundFlowState(); } return flowStreams; } } @VisibleForTesting ClientFrameHandler getHandler() { return clientFrameHandler; } @VisibleForTesting SocketFactory getSocketFactory() { return socketFactory; } @VisibleForTesting int getPendingStreamSize() { synchronized (lock) { return pendingStreams.size(); } } @VisibleForTesting void setNextStreamId(int nextStreamId) { synchronized (lock) { this.nextStreamId = nextStreamId; } } /** * Finish all active streams due to an IOException, then close the transport. */ @Override public void onException(Throwable failureCause) { Preconditions.checkNotNull(failureCause, "failureCause"); Status status = Status.UNAVAILABLE.withCause(failureCause); startGoAway(0, ErrorCode.INTERNAL_ERROR, status); } /** * Send GOAWAY to the server, then finish all active streams and close the transport. */ private void onError(ErrorCode errorCode, String moreDetail) { startGoAway(0, errorCode, toGrpcStatus(errorCode).augmentDescription(moreDetail)); } private void startGoAway(int lastKnownStreamId, ErrorCode errorCode, Status status) { synchronized (lock) { if (goAwayStatus == null) { goAwayStatus = status; listener.transportShutdown(status); } if (errorCode != null && !goAwaySent) { // Send GOAWAY with lastGoodStreamId of 0, since we don't expect any server-initiated // streams. The GOAWAY is part of graceful shutdown. goAwaySent = true; frameWriter.goAway(0, errorCode, new byte[0]); } Iterator<Map.Entry<Integer, OkHttpClientStream>> it = streams.entrySet().iterator(); while (it.hasNext()) { Map.Entry<Integer, OkHttpClientStream> entry = it.next(); if (entry.getKey() > lastKnownStreamId) { it.remove(); entry.getValue().transportState().transportReportStatus( status, RpcProgress.REFUSED, false, new Metadata()); maybeClearInUse(entry.getValue()); } } for (OkHttpClientStream stream : pendingStreams) { stream.transportState().transportReportStatus( status, RpcProgress.MISCARRIED, true, new Metadata()); maybeClearInUse(stream); } pendingStreams.clear(); stopIfNecessary(); } } /** * Called when a stream is closed. We do things like: * <ul> * <li>Removing the stream from the map. * <li>Optionally reporting the status. * <li>Starting pending streams if we can. * <li>Stopping the transport if this is the last live stream under a go-away status. * </ul> * * @param streamId the Id of the stream. * @param status the final status of this stream, null means no need to report. * @param stopDelivery interrupt queued messages in the deframer * @param errorCode reset the stream with this ErrorCode if not null. * @param trailers the trailers received if not null */ void finishStream( int streamId, @Nullable Status status, RpcProgress rpcProgress, boolean stopDelivery, @Nullable ErrorCode errorCode, @Nullable Metadata trailers) { synchronized (lock) { OkHttpClientStream stream = streams.remove(streamId); if (stream != null) { if (errorCode != null) { frameWriter.rstStream(streamId, ErrorCode.CANCEL); } if (status != null) { stream .transportState() .transportReportStatus( status, rpcProgress, stopDelivery, trailers != null ? trailers : new Metadata()); } if (!startPendingStreams()) { stopIfNecessary(); } maybeClearInUse(stream); } } } /** * When the transport is in goAway state, we should stop it once all active streams finish. */ @GuardedBy("lock") private void stopIfNecessary() { if (!(goAwayStatus != null && streams.isEmpty() && pendingStreams.isEmpty())) { return; } if (stopped) { return; } stopped = true; if (keepAliveManager != null) { keepAliveManager.onTransportTermination(); } if (ping != null) { ping.failed(getPingFailure()); ping = null; } if (!goAwaySent) { // Send GOAWAY with lastGoodStreamId of 0, since we don't expect any server-initiated // streams. The GOAWAY is part of graceful shutdown. goAwaySent = true; frameWriter.goAway(0, ErrorCode.NO_ERROR, new byte[0]); } // We will close the underlying socket in the writing thread to break out the reader // thread, which will close the frameReader and notify the listener. frameWriter.close(); } @GuardedBy("lock") private void maybeClearInUse(OkHttpClientStream stream) { if (hasStream) { if (pendingStreams.isEmpty() && streams.isEmpty()) { hasStream = false; if (keepAliveManager != null) { // We don't have any active streams. No need to do keepalives any more. // Again, we have to call this inside the lock to avoid the race between onTransportIdle // and onTransportActive. keepAliveManager.onTransportIdle(); } } } if (stream.shouldBeCountedForInUse()) { inUseState.updateObjectInUse(stream, false); } } @GuardedBy("lock") private void setInUse(OkHttpClientStream stream) { if (!hasStream) { hasStream = true; if (keepAliveManager != null) { // We have a new stream. We might need to do keepalives now. // Note that we have to do this inside the lock to avoid calling // KeepAliveManager.onTransportActive and KeepAliveManager.onTransportIdle in the wrong // order. keepAliveManager.onTransportActive(); } } if (stream.shouldBeCountedForInUse()) { inUseState.updateObjectInUse(stream, true); } } private Status getPingFailure() { synchronized (lock) { if (goAwayStatus != null) { return goAwayStatus; } else { return Status.UNAVAILABLE.withDescription("Connection closed"); } } } boolean mayHaveCreatedStream(int streamId) { synchronized (lock) { return streamId < nextStreamId && (streamId & 1) == 1; } } OkHttpClientStream getStream(int streamId) { synchronized (lock) { return streams.get(streamId); } } /** * Returns a Grpc status corresponding to the given ErrorCode. */ @VisibleForTesting static Status toGrpcStatus(ErrorCode code) { Status status = ERROR_CODE_TO_STATUS.get(code); return status != null ? status : Status.UNKNOWN.withDescription( "Unknown http2 error code: " + code.httpCode); } @Override public ListenableFuture<SocketStats> getStats() { SettableFuture<SocketStats> ret = SettableFuture.create(); synchronized (lock) { if (socket == null) { ret.set(new SocketStats( transportTracer.getStats(), /*local=*/ null, /*remote=*/ null, new InternalChannelz.SocketOptions.Builder().build(), /*security=*/ null)); } else { ret.set(new SocketStats( transportTracer.getStats(), socket.getLocalSocketAddress(), socket.getRemoteSocketAddress(), Utils.getSocketOptions(socket), securityInfo)); } return ret; } } /** * Runnable which reads frames and dispatches them to in flight calls. */
LruCache
java
apache__dubbo
dubbo-config/dubbo-config-api/src/test/java/org/apache/dubbo/config/bootstrap/builders/AbstractReferenceBuilderTest.java
{ "start": 1082, "end": 4749 }
class ____ { @Test void check() { ReferenceBuilder builder = new ReferenceBuilder(); builder.check(true); Assertions.assertTrue(builder.build().isCheck()); builder.check(false); Assertions.assertFalse(builder.build().isCheck()); } @Test void init() { ReferenceBuilder builder = new ReferenceBuilder(); builder.init(true); Assertions.assertTrue(builder.build().isInit()); builder.init(false); Assertions.assertFalse(builder.build().isInit()); } @Test void generic() { ReferenceBuilder builder = new ReferenceBuilder(); builder.generic(true); Assertions.assertTrue(builder.build().isGeneric()); builder.generic(false); Assertions.assertFalse(builder.build().isGeneric()); } @Test void generic1() { ReferenceBuilder builder = new ReferenceBuilder(); builder.generic(GENERIC_SERIALIZATION_BEAN); Assertions.assertEquals(GENERIC_SERIALIZATION_BEAN, builder.build().getGeneric()); } @Test void injvm() { ReferenceBuilder builder = new ReferenceBuilder(); builder.injvm(true); Assertions.assertTrue(builder.build().isInjvm()); builder.injvm(false); Assertions.assertFalse(builder.build().isInjvm()); } @Test void lazy() { ReferenceBuilder builder = new ReferenceBuilder(); builder.lazy(true); Assertions.assertTrue(builder.build().getLazy()); builder.lazy(false); Assertions.assertFalse(builder.build().getLazy()); } @Test void reconnect() { ReferenceBuilder builder = new ReferenceBuilder(); builder.reconnect("reconnect"); Assertions.assertEquals("reconnect", builder.build().getReconnect()); } @Test void sticky() { ReferenceBuilder builder = new ReferenceBuilder(); builder.sticky(true); Assertions.assertTrue(builder.build().getSticky()); builder.sticky(false); Assertions.assertFalse(builder.build().getSticky()); } @Test void version() { ReferenceBuilder builder = new ReferenceBuilder(); builder.version("version"); Assertions.assertEquals("version", builder.build().getVersion()); } @Test void group() { ReferenceBuilder builder = new ReferenceBuilder(); builder.group("group"); Assertions.assertEquals("group", builder.build().getGroup()); } @Test void build() { ReferenceBuilder builder = new ReferenceBuilder(); builder.check(true) .init(false) .generic(true) .injvm(false) .lazy(true) .reconnect("reconnect") .sticky(false) .version("version") .group("group") .id("id"); ReferenceConfig config = builder.build(); ReferenceConfig config2 = builder.build(); Assertions.assertEquals("id", config.getId()); Assertions.assertTrue(config.isCheck()); Assertions.assertFalse(config.isInit()); Assertions.assertTrue(config.isGeneric()); Assertions.assertFalse(config.isInjvm()); Assertions.assertTrue(config.getLazy()); Assertions.assertFalse(config.getSticky()); Assertions.assertEquals("reconnect", config.getReconnect()); Assertions.assertEquals("version", config.getVersion()); Assertions.assertEquals("group", config.getGroup()); Assertions.assertNotSame(config, config2); } private static
AbstractReferenceBuilderTest
java
FasterXML__jackson-databind
src/main/java/tools/jackson/databind/ser/jdk/JDKArraySerializers.java
{ "start": 19232, "end": 22907 }
class ____ extends ArraySerializerBase<double[]> { // as above, assuming no one re-defines primitive/wrapper types private final static JavaType VALUE_TYPE = simpleElementType(Double.TYPE); // @since 2.20 final static DoubleArraySerializer instance = new DoubleArraySerializer(); public DoubleArraySerializer() { super(double[].class); } /** * @since 2.6 */ protected DoubleArraySerializer(DoubleArraySerializer src, BeanProperty prop, Boolean unwrapSingle) { super(src, prop, unwrapSingle); } @Override public ValueSerializer<?> _withResolved(BeanProperty prop, Boolean unwrapSingle) { return new DoubleArraySerializer(this, prop, unwrapSingle); } /** * Doubles never add type info; hence, even if type serializer is suggested, * we'll ignore it... */ @Override public StdContainerSerializer<?> _withValueTypeSerializer(TypeSerializer vts) { return this; } @Override public JavaType getContentType() { return VALUE_TYPE; } @Override public ValueSerializer<?> getContentSerializer() { // 14-Jan-2012, tatu: We could refer to an actual serializer if absolutely necessary return null; } @Override public boolean isEmpty(SerializationContext prov, double[] value) { return value.length == 0; } @Override public boolean hasSingleElement(double[] value) { return (value.length == 1); } @Override public ValueSerializer<?> createContextual(SerializationContext ctxt, BeanProperty property) { JsonFormat.Value format = findFormatOverrides(ctxt, property, handledType()); if (format != null) { if (format.getShape() == JsonFormat.Shape.BINARY) { return BinaryDoubleArraySerializer.instance; } } return super.createContextual(ctxt, property); } @Override public void serialize(double[] value, JsonGenerator g, SerializationContext ctxt) throws JacksonException { final int len = value.length; if ((len == 1) && _shouldUnwrapSingle(ctxt)) { serializeContents(value, g, ctxt); return; } // 11-May-2016, tatu: As per [core#277] we have efficient `writeArray(...)` available g.writeArray(value, 0, value.length); } @Override public void serializeContents(double[] value, JsonGenerator g, SerializationContext ctxt) throws JacksonException { for (int i = 0, len = value.length; i < len; ++i) { g.writeNumber(value[i]); } } @Override public void acceptJsonFormatVisitor(JsonFormatVisitorWrapper visitor, JavaType typeHint) { visitArrayFormat(visitor, typeHint, JsonFormatTypes.NUMBER); } } /* /********************************************************************** /* Concrete serializers, alternative "binary Vector" representations /********************************************************************** */ /** * Alternative serializer for arrays of primitive floats, using "packed binary" * representation ("binary vector") instead of JSON array. * * @since 2.20 */ @JacksonStdImpl public static
DoubleArraySerializer
java
FasterXML__jackson-databind
src/test/java/tools/jackson/databind/objectid/TestObjectId.java
{ "start": 2084, "end": 2508 }
class ____ extends BaseEntity { public Foo next; } // for [databind#1083] @JsonTypeInfo( use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = JsonMapSchema.class) @JsonSubTypes({ @JsonSubTypes.Type(value = JsonMapSchema.class, name = "map"), @JsonSubTypes.Type(value = JsonJdbcSchema.class, name = "jdbc") }) public static abstract
Bar
java
spring-projects__spring-boot
core/spring-boot/src/test/java/org/springframework/boot/diagnostics/analyzer/UnboundConfigurationPropertyFailureAnalyzerTests.java
{ "start": 3958, "end": 4216 }
class ____ { private @Nullable List<String> listValue; @Nullable List<String> getListValue() { return this.listValue; } void setListValue(@Nullable List<String> listValue) { this.listValue = listValue; } } }
UnboundElementsFailureProperties
java
spring-projects__spring-framework
spring-test/src/test/java/org/springframework/test/context/junit/jupiter/FailingBeforeAndAfterMethodsSpringExtensionTests.java
{ "start": 8306, "end": 8573 }
class ____ { @Bean PlatformTransactionManager transactionManager() { return new DataSourceTransactionManager(dataSource()); } @Bean DataSource dataSource() { return new EmbeddedDatabaseBuilder().generateUniqueName(true).build(); } } }
DatabaseConfig
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/generics/MultipleEmbeddedGenericsTest.java
{ "start": 7516, "end": 7836 }
class ____ extends GenericEmbeddableOne { private int invoicePropertyA; public InvoiceEmbeddableOne() { } public InvoiceEmbeddableOne(String genericPropertyA, int invoicePropertyA) { super( genericPropertyA ); this.invoicePropertyA = invoicePropertyA; } } @Embeddable public static
InvoiceEmbeddableOne
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/bytecode/enhancement/lazy/LazyManyToOneNoProxyTest.java
{ "start": 2771, "end": 3238 }
class ____ { @Id Long id; String name; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "team_id") UserGroup team; public User() { } public User(Long id, String name, UserGroup team) { this.id = id; this.name = name; this.team = team; } public Long getId() { return id; } public String getName() { return name; } public UserGroup getTeam() { return team; } } @Entity(name = "UserGroup") public static
User
java
apache__camel
components/camel-micrometer/src/main/java/org/apache/camel/component/micrometer/json/MicrometerModule.java
{ "start": 3149, "end": 3640 }
class ____ extends StdSerializer<Meter.Id> { private IdSerializer() { super(Meter.Id.class); } @Override public void serialize(Meter.Id id, JsonGenerator json, SerializerProvider provider) throws IOException { json.writeStartObject(); json.writeStringField("name", id.getName()); json.writeObjectField("tags", id.getTags()); json.writeEndObject(); } } private static final
IdSerializer
java
alibaba__nacos
core/src/test/java/com/alibaba/nacos/core/model/request/LogUpdateRequestTest.java
{ "start": 762, "end": 1078 }
class ____ { @Test void test() { LogUpdateRequest request = new LogUpdateRequest(); request.setLogName("test"); request.setLogLevel("info"); assertEquals("test", request.getLogName()); assertEquals("info", request.getLogLevel()); } }
LogUpdateRequestTest
java
elastic__elasticsearch
x-pack/plugin/monitoring/src/test/java/org/elasticsearch/xpack/monitoring/test/MonitoringIntegTestCase.java
{ "start": 1671, "end": 6072 }
class ____ extends ESIntegTestCase { protected static final String MONITORING_INDICES_PREFIX = ".monitoring-"; protected static final String ALL_MONITORING_INDICES = MONITORING_INDICES_PREFIX + "*"; @Override protected Settings nodeSettings(int nodeOrdinal, Settings otherSettings) { Settings.Builder builder = Settings.builder() .put(super.nodeSettings(nodeOrdinal, otherSettings)) .put(MonitoringService.INTERVAL.getKey(), MonitoringService.MIN_INTERVAL) // .put(XPackSettings.SECURITY_ENABLED.getKey(), false) // .put(XPackSettings.WATCHER_ENABLED.getKey(), false) // Disable native ML autodetect_process as the c++ controller won't be available // .put(MachineLearningField.AUTODETECT_PROCESS.getKey(), false) // .put(XPackSettings.MACHINE_LEARNING_ENABLED.getKey(), false) // we do this by default in core, but for monitoring this isn't needed and only adds noise. .put("indices.lifecycle.history_index_enabled", false) .put("index.store.mock.check_index_on_close", false); return builder.build(); } @Override protected Collection<Class<? extends Plugin>> getMockPlugins() { Set<Class<? extends Plugin>> plugins = new HashSet<>(super.getMockPlugins()); plugins.remove(MockTransportService.TestPlugin.class); // security has its own transport service plugins.add(MockFSIndexStore.TestPlugin.class); return plugins; } @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Arrays.asList( LocalStateMonitoring.class, MockClusterAlertScriptEngine.TestPlugin.class, MockIngestPlugin.class, CommonAnalysisPlugin.class, MapperExtrasPlugin.class, Wildcard.class ); } @Override protected Set<String> excludeTemplates() { return new HashSet<>(Arrays.asList(MonitoringTemplateRegistry.TEMPLATE_NAMES)); } @Before public void setUp() throws Exception { super.setUp(); startMonitoringService(); } @After public void tearDown() throws Exception { stopMonitoringService(); super.tearDown(); } protected void startMonitoringService() { internalCluster().getInstances(MonitoringService.class).forEach(MonitoringService::unpause); } protected void stopMonitoringService() { internalCluster().getInstances(MonitoringService.class).forEach(MonitoringService::pause); } protected void wipeMonitoringIndices() throws Exception { CountDown retries = new CountDown(3); assertBusy(() -> { try { if (indexExists(ALL_MONITORING_INDICES)) { deleteMonitoringIndices(); } else { retries.countDown(); } } catch (IndexNotFoundException e) { retries.countDown(); } assertThat(retries.isCountedDown(), is(true)); }); } protected void deleteMonitoringIndices() { assertAcked(client().admin().indices().prepareDelete(ALL_MONITORING_INDICES)); } protected List<Tuple<String, String>> monitoringWatches() { final ClusterService clusterService = clusterService(); return Arrays.stream(ClusterAlertsUtil.WATCH_IDS) .map(id -> new Tuple<>(id, ClusterAlertsUtil.loadWatch(clusterService, id))) .collect(Collectors.toList()); } protected void assertTemplateInstalled(String name) { boolean found = false; for (IndexTemplateMetadata template : client().admin() .indices() .prepareGetTemplates(TEST_REQUEST_TIMEOUT) .get() .getIndexTemplates()) { if (Regex.simpleMatch(name, template.getName())) { found = true; } } assertTrue("failed to find a template matching [" + name + "]", found); } protected void enableMonitoringCollection() { updateClusterSettings(Settings.builder().put(MonitoringService.ENABLED.getKey(), true)); } protected void disableMonitoringCollection() { updateClusterSettings(Settings.builder().putNull(MonitoringService.ENABLED.getKey())); } }
MonitoringIntegTestCase
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/sql/exec/manytoone/EntityWithLazyManyToOneTest.java
{ "start": 4235, "end": 4773 }
class ____ { @Id @GeneratedValue private Integer id; @ManyToOne(fetch = FetchType.LAZY) private ConcreteEntity entity; public LazyConcreteEntityReference() { } public LazyConcreteEntityReference(ConcreteEntity entity) { setEntity( entity ); } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public ConcreteEntity getEntity() { return entity; } public void setEntity(ConcreteEntity entity) { this.entity = entity; } } }
LazyConcreteEntityReference
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/sql/mysql/show/MySqlShowTest_38_hints.java
{ "start": 348, "end": 1874 }
class ____ extends MysqlTest { private static final SQLParserFeature[] defaultFeatures = {SQLParserFeature.EnableSQLBinaryOpExprGroup, SQLParserFeature.UseInsertColumnsCache, SQLParserFeature.OptimizedForParameterized, SQLParserFeature.TDDLHint}; public void test_0() throws Exception { String sql = "/* +TDDL:scan()*/show table status from corona_qatest_0;"; MySqlStatementParser parser = new MySqlStatementParser(sql, SQLParserFeature.TDDLHint); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); assertEquals(1, statementList.size()); assertEquals("/*+TDDL:scan()*/\n" + "SHOW TABLE STATUS FROM corona_qatest_0;", stmt.toString()); assertEquals("/*+TDDL:scan()*/\n" + "show table status from corona_qatest_0;", stmt.toLowerCaseString()); } public void test_1() throws Exception { String sql = "/* +TDDL:node(1)*/show table status from corona_qatest_0;"; MySqlStatementParser parser = new MySqlStatementParser(sql, defaultFeatures); List<SQLStatement> statementList = parser.parseStatementList(); SQLStatement stmt = statementList.get(0); assertEquals(1, statementList.size()); assertEquals("/*+TDDL:node(1)*/\n" + "SHOW TABLE STATUS FROM corona_qatest_0;", stmt.toString()); assertEquals("/*+TDDL:node(1)*/\n" + "show table status from corona_qatest_0;", stmt.toLowerCaseString()); } }
MySqlShowTest_38_hints
java
google__dagger
javatests/dagger/functional/nullables/JspecifyNullableTest.java
{ "start": 1866, "end": 3824 }
class ____ { private final Dependency dependency; DependencyModule(Dependency dependency) { this.dependency = dependency; } @Provides @Nullable Dependency provideDependency() { return dependency; } } @Test public void testWithValue() { MyComponent component = DaggerJspecifyNullableTest_MyComponent.builder() .myModule(new MyModule(15, new InnerType() {})) .componentDependency( DaggerJspecifyNullableTest_ComponentDependency.builder() .dependencyModule(new DependencyModule(new Dependency() {})).build()) .build(); assertThat(component.getInt()).isEqualTo(15); assertThat(component.getInnerType()).isNotNull(); assertThat(component.getDependencyProvider().get()).isNotNull(); } @Test public void testWithNull() { MyComponent component = DaggerJspecifyNullableTest_MyComponent.builder() .myModule(new MyModule(null, null)) .componentDependency( DaggerJspecifyNullableTest_ComponentDependency.builder() .dependencyModule(new DependencyModule(null)).build()) .build(); NullPointerException expectedException = assertThrows(NullPointerException.class, component::getInt); assertThat(expectedException) .hasMessageThat() .contains("Cannot return null from a non-@Nullable @Provides method"); NullPointerException expectedException2 = assertThrows(NullPointerException.class, component::getInnerType); assertThat(expectedException2) .hasMessageThat() .contains("Cannot return null from a non-@Nullable @Provides method"); NullPointerException expectedException3 = assertThrows(NullPointerException.class, () -> component.getDependencyProvider().get()); assertThat(expectedException3) .hasMessageThat() .contains("Cannot return null from a non-@Nullable @Provides method"); } }
DependencyModule
java
bumptech__glide
library/test/src/test/java/com/bumptech/glide/manager/RequestTrackerTest.java
{ "start": 9429, "end": 10746 }
class ____ implements Request { private boolean isPaused; @Override public void pause() { isPaused = true; if (isRunning) { clear(); } } private boolean isRunning; private boolean isCleared; private boolean isComplete; void setIsComplete() { setIsComplete(true); } void setIsComplete(boolean isComplete) { this.isComplete = isComplete; } void setIsRunning() { isRunning = true; } boolean isPaused() { return isPaused; } @Override public void begin() { if (isRunning) { throw new IllegalStateException(); } isRunning = true; } @Override public void clear() { if (isCleared) { throw new IllegalStateException(); } isRunning = false; isCleared = true; } @Override public boolean isRunning() { return isRunning; } @Override public boolean isComplete() { return isComplete; } @Override public boolean isCleared() { return isCleared; } @Override public boolean isAnyResourceSet() { return isComplete; } @Override public boolean isEquivalentTo(Request other) { throw new UnsupportedOperationException(); } } private
FakeRequest
java
apache__flink
flink-core/src/main/java/org/apache/flink/streaming/api/operators/OutputTypeConfigurable.java
{ "start": 1066, "end": 1369 }
interface ____ they need access to the output type information * at {@code org.apache.flink.streaming.api.graph.StreamGraph} generation. This can be useful for * cases where the output type is specified by the returns method and, thus, after the stream * operator has been created. * * <p>NOTE: this
if
java
spring-projects__spring-boot
buildpack/spring-boot-buildpack-platform/src/test/java/org/springframework/boot/buildpack/platform/build/BuilderTests.java
{ "start": 29032, "end": 29226 }
class ____ extends PrintStream { TestPrintStream() { super(new ByteArrayOutputStream()); } @Override public String toString() { return this.out.toString(); } } }
TestPrintStream
java
alibaba__nacos
naming/src/main/java/com/alibaba/nacos/naming/core/CatalogService.java
{ "start": 1024, "end": 4351 }
interface ____ { /** * Get service detail information. * * @param namespaceId namespace id of service * @param groupName group name of service * @param serviceName service name * @return detail information of service * @throws NacosException exception in query */ ServiceDetailInfo getServiceDetail(String namespaceId, String groupName, String serviceName) throws NacosException; /** * List all instances of specified services. * * @param namespaceId namespace id of service * @param groupName group name of service * @param serviceName service name * @param clusterName cluster name of instances * @return instances page object * @throws NacosException exception in query */ List<? extends Instance> listInstances(String namespaceId, String groupName, String serviceName, String clusterName) throws NacosException; /** * List all instances of specified services. * * @param namespaceId namespace id of service * @param groupName group name of service * @param serviceName service name * @return instances list */ List<? extends Instance> listAllInstances(String namespaceId, String groupName, String serviceName); /** * List service by page. * * @param namespaceId namespace id of service * @param groupName group name of service * @param serviceName service name * @param pageNo page number * @param pageSize page size * @param instancePattern contained instances pattern * @param ignoreEmptyService whether ignore empty service * @return service list * @throws NacosException exception in query * @deprecated after v1 http api removed, use {@link #listService(String, String, String, int, int, boolean)} replace. */ @Deprecated Object pageListService(String namespaceId, String groupName, String serviceName, int pageNo, int pageSize, String instancePattern, boolean ignoreEmptyService) throws NacosException; /** * List service with cluster and instances by page. * * @param namespaceId namespace id of service * @param groupName group name of service * @param serviceName service name * @param pageNo page number * @param pageSize page size * @return service page object * @throws NacosException exception in query */ Page<ServiceDetailInfo> pageListServiceDetail(String namespaceId, String groupName, String serviceName, int pageNo, int pageSize) throws NacosException; /** * List service by page. * * @param namespaceId namespace id of service * @param groupName group name of service * @param serviceName service name * @param pageNo page number * @param pageSize page size * @param ignoreEmptyService whether ignore empty service * @return service page object * @throws NacosException exception in query */ Page<ServiceView> listService(String namespaceId, String groupName, String serviceName, int pageNo, int pageSize, boolean ignoreEmptyService) throws NacosException; }
CatalogService
java
apache__maven
compat/maven-artifact/src/main/java/org/apache/maven/artifact/versioning/ComparableVersion.java
{ "start": 3519, "end": 5366 }
class ____ implements Item { private final int value; public static final IntItem ZERO = new IntItem(); private IntItem() { this.value = 0; } IntItem(String str) { this.value = Integer.parseInt(str); } @Override public int getType() { return INT_ITEM; } @Override public boolean isNull() { return value == 0; } @Override public int compareTo(Item item) { if (item == null) { return (value == 0) ? 0 : 1; // 1.0 == 1, 1.1 > 1 } return switch (item.getType()) { case INT_ITEM -> { int itemValue = ((IntItem) item).value; yield Integer.compare(value, itemValue); } case LONG_ITEM, BIGINTEGER_ITEM -> -1; case STRING_ITEM -> 1; case COMBINATION_ITEM -> 1; // 1.1 > 1-sp case LIST_ITEM -> 1; // 1.1 > 1-1 default -> throw new IllegalStateException("invalid item: " + item.getClass()); }; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IntItem intItem = (IntItem) o; return value == intItem.value; } @Override public int hashCode() { return value; } @Override public String toString() { return Integer.toString(value); } } /** * Represents a numeric item in the version item list that can be represented with a long. */ private static
IntItem
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/sql/exec/EntityWithEmbeddedIdTest.java
{ "start": 865, "end": 1855 }
class ____ { private PK entityId; @BeforeEach public void setUp(SessionFactoryScope scope) { final TestEntity entity = new TestEntity(); entityId = new PK( 25, "Acme" ); scope.inTransaction( session -> { entity.setId( entityId ); entity.setData( "test" ); session.persist( entity ); } ); } @AfterEach public void tearDown(SessionFactoryScope scope) { scope.getSessionFactory().getSchemaManager().truncate(); } @Test public void testHqlSelectOnlyTheEmbeddedId(SessionFactoryScope scope) { StatisticsImplementor statistics = scope.getSessionFactory().getStatistics(); statistics.clear(); scope.inTransaction( session -> { final PK value = session.createQuery( "select e.id FROM TestEntity e", PK.class ).uniqueResult(); assertThat( value, equalTo( entityId ) ); } ); assertThat( statistics.getPrepareStatementCount(), is( 1L ) ); } @Entity(name = "TestEntity") public static
EntityWithEmbeddedIdTest
java
spring-projects__spring-boot
buildSrc/src/main/java/org/springframework/boot/build/test/autoconfigure/CheckAutoConfigureImports.java
{ "start": 1926, "end": 7647 }
class ____ extends DefaultTask { private FileCollection sourceFiles = getProject().getObjects().fileCollection(); private FileCollection classpath = getProject().getObjects().fileCollection(); public CheckAutoConfigureImports() { getOutputDirectory().convention(getProject().getLayout().getBuildDirectory().dir(getName())); setGroup(LifecycleBasePlugin.VERIFICATION_GROUP); } @InputFiles @SkipWhenEmpty @PathSensitive(PathSensitivity.RELATIVE) public FileTree getSource() { return this.sourceFiles.getAsFileTree() .matching((filter) -> filter.include("META-INF/spring/*.AutoConfigure*.imports")); } public void setSource(Object source) { this.sourceFiles = getProject().getObjects().fileCollection().from(source); } @Classpath public FileCollection getClasspath() { return this.classpath; } public void setClasspath(Object classpath) { this.classpath = getProject().getObjects().fileCollection().from(classpath); } @OutputDirectory public abstract DirectoryProperty getOutputDirectory(); @TaskAction void execute() { Map<String, List<String>> allProblems = new TreeMap<>(); for (AutoConfigureImports autoConfigureImports : loadImports()) { List<String> problems = new ArrayList<>(); if (!find(autoConfigureImports.annotationName)) { problems.add("Annotation '%s' was not found".formatted(autoConfigureImports.annotationName)); } for (String imported : autoConfigureImports.imports) { String importedClassName = imported; if (importedClassName.startsWith("optional:")) { importedClassName = importedClassName.substring("optional:".length()); } boolean found = find(importedClassName, (input) -> { if (!correctlyAnnotated(input)) { problems.add("Imported auto-configuration '%s' is not annotated with @AutoConfiguration" .formatted(imported)); } }); if (!found) { problems.add("Imported auto-configuration '%s' was not found".formatted(importedClassName)); } } List<String> sortedValues = new ArrayList<>(autoConfigureImports.imports); Collections.sort(sortedValues, (i1, i2) -> { boolean imported1 = i1.startsWith("optional:"); boolean imported2 = i2.startsWith("optional:"); int comparison = Boolean.compare(imported1, imported2); if (comparison != 0) { return comparison; } return i1.compareTo(i2); }); if (!sortedValues.equals(autoConfigureImports.imports)) { File sortedOutputFile = getOutputDirectory().file("sorted-" + autoConfigureImports.fileName) .get() .getAsFile(); writeString(sortedOutputFile, sortedValues.stream().collect(Collectors.joining(System.lineSeparator())) + System.lineSeparator()); problems.add( "Entries should be required then optional, each sorted alphabetically (expected content written to '%s')" .formatted(sortedOutputFile.getAbsolutePath())); } if (!problems.isEmpty()) { allProblems.computeIfAbsent(autoConfigureImports.fileName, (unused) -> new ArrayList<>()) .addAll(problems); } } File outputFile = getOutputDirectory().file("failure-report.txt").get().getAsFile(); writeReport(allProblems, outputFile); if (!allProblems.isEmpty()) { throw new VerificationException( "AutoConfigure….imports checks failed. See '%s' for details".formatted(outputFile)); } } private List<AutoConfigureImports> loadImports() { return getSource().getFiles().stream().map((file) -> { String fileName = file.getName(); String annotationName = fileName.substring(0, fileName.length() - ".imports".length()); return new AutoConfigureImports(annotationName, loadImports(file), fileName); }).toList(); } private List<String> loadImports(File importsFile) { try { return Files.readAllLines(importsFile.toPath()); } catch (IOException ex) { throw new UncheckedIOException(ex); } } private boolean find(String className) { return find(className, (input) -> { }); } private boolean find(String className, Consumer<InputStream> handler) { for (File root : this.classpath.getFiles()) { String classFilePath = className.replace(".", "/") + ".class"; if (root.isDirectory()) { File classFile = new File(root, classFilePath); if (classFile.isFile()) { try (InputStream input = new FileInputStream(classFile)) { handler.accept(input); } catch (IOException ex) { throw new UncheckedIOException(ex); } return true; } } else { try (JarFile jar = new JarFile(root)) { ZipEntry entry = jar.getEntry(classFilePath); if (entry != null) { try (InputStream input = jar.getInputStream(entry)) { handler.accept(input); } return true; } } catch (IOException ex) { throw new UncheckedIOException(ex); } } } return false; } private boolean correctlyAnnotated(InputStream classFile) { return AutoConfigurationClass.of(classFile) != null; } private void writeReport(Map<String, List<String>> allProblems, File outputFile) { outputFile.getParentFile().mkdirs(); StringBuilder report = new StringBuilder(); if (!allProblems.isEmpty()) { allProblems.forEach((fileName, problems) -> { report.append("Found problems in '%s':%n".formatted(fileName)); problems.forEach((problem) -> report.append(" - %s%n".formatted(problem))); }); } writeString(outputFile, report.toString()); } private void writeString(File file, String content) { try { Files.writeString(file.toPath(), content); } catch (IOException ex) { throw new UncheckedIOException(ex); } } record AutoConfigureImports(String annotationName, List<String> imports, String fileName) { } }
CheckAutoConfigureImports
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/resourcemanager/slotmanager/SlotManager.java
{ "start": 6645, "end": 6922 }
enum ____ { SUCCESS, // task manager has not been registered before and is registered successfully IGNORED, // task manager has been registered before and is ignored REJECTED, // task manager is rejected and should be disconnected } }
RegistrationResult
java
spring-projects__spring-boot
module/spring-boot-http-client/src/main/java/org/springframework/boot/http/client/reactive/JettyClientHttpConnectorBuilder.java
{ "start": 5770, "end": 6149 }
class ____ { static final String HTTP_CLIENT = "org.eclipse.jetty.client.HttpClient"; static final String REACTIVE_REQUEST = "org.eclipse.jetty.reactive.client.ReactiveRequest"; static boolean present(@Nullable ClassLoader classLoader) { return ClassUtils.isPresent(HTTP_CLIENT, classLoader) && ClassUtils.isPresent(REACTIVE_REQUEST, classLoader); } } }
Classes
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestFileStatusSerialization.java
{ "start": 1786, "end": 7445 }
class ____ { private static void checkFields(FileStatus expected, FileStatus actual) { assertEquals(expected.getPath(), actual.getPath()); assertEquals(expected.isDirectory(), actual.isDirectory()); assertEquals(expected.getLen(), actual.getLen()); assertEquals(expected.getPermission(), actual.getPermission()); assertEquals(expected.getOwner(), actual.getOwner()); assertEquals(expected.getGroup(), actual.getGroup()); assertEquals(expected.getModificationTime(), actual.getModificationTime()); assertEquals(expected.getAccessTime(), actual.getAccessTime()); assertEquals(expected.getReplication(), actual.getReplication()); assertEquals(expected.getBlockSize(), actual.getBlockSize()); } private static final URI BASEURI = new Path("hdfs://foobar").toUri(); private static final Path BASEPATH = new Path("/dingos"); private static final String FILE = "zot"; private static final Path FULLPATH = new Path("hdfs://foobar/dingos/zot"); private static HdfsFileStatusProto.Builder baseStatus() { FsPermission perm = FsPermission.getFileDefault(); HdfsFileStatusProto.Builder hspb = HdfsFileStatusProto.newBuilder() .setFileType(FileType.IS_FILE) .setPath(ByteString.copyFromUtf8("zot")) .setLength(4344) .setPermission(PBHelperClient.convert(perm)) .setOwner("hadoop") .setGroup("unqbbc") .setModificationTime(12345678L) .setAccessTime(87654321L) .setBlockReplication(10) .setBlocksize(1L << 33) .setFlags(0); return hspb; } /** * Test API backwards-compatibility with 2.x applications w.r.t. FsPermission. */ @Test @SuppressWarnings("deprecation") public void testFsPermissionCompatibility() throws Exception { final int flagmask = 0x8; // flags compatible with 2.x; fixed as constant in this test to ensure // compatibility is maintained. New flags are not part of the contract this // test verifies. for (int i = 0; i < flagmask; ++i) { FsPermission perm = FsPermission.createImmutable((short) 0013); HdfsFileStatusProto.Builder hspb = baseStatus() .setPermission(PBHelperClient.convert(perm)) .setFlags(i); HdfsFileStatus stat = PBHelperClient.convert(hspb.build()); stat.makeQualified(BASEURI, BASEPATH); assertEquals(FULLPATH, stat.getPath()); // verify deprecated FsPermissionExtension methods FsPermission sp = stat.getPermission(); assertEquals(sp.getAclBit(), stat.hasAcl()); assertEquals(sp.getEncryptedBit(), stat.isEncrypted()); assertEquals(sp.getErasureCodedBit(), stat.isErasureCoded()); // verify Writable contract DataOutputBuffer dob = new DataOutputBuffer(); stat.write(dob); DataInputBuffer dib = new DataInputBuffer(); dib.reset(dob.getData(), 0, dob.getLength()); FileStatus fstat = new FileStatus(); fstat.readFields(dib); checkFields((FileStatus) stat, fstat); // FsPermisisonExtension used for HdfsFileStatus, not FileStatus, // attribute flags should still be preserved assertEquals(sp.getAclBit(), fstat.hasAcl()); assertEquals(sp.getEncryptedBit(), fstat.isEncrypted()); assertEquals(sp.getErasureCodedBit(), fstat.isErasureCoded()); } } @Test public void testJavaSerialization() throws Exception { HdfsFileStatusProto hsp = baseStatus().build(); HdfsFileStatus hs = PBHelperClient.convert(hsp); hs.makeQualified(BASEURI, BASEPATH); ByteArrayOutputStream baos = new ByteArrayOutputStream(1024); try (ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(hs); } ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); try (ObjectInputStream ois = new ObjectInputStream(bais)) { FileStatus deser = (FileStatus) ois.readObject(); assertEquals(hs, deser); checkFields((FileStatus) hs, deser); } } @Test public void testCrossSerializationProto() throws Exception { for (FileType t : FileType.values()) { HdfsFileStatusProto.Builder hspb = baseStatus() .setFileType(t); if (FileType.IS_SYMLINK.equals(t)) { hspb.setSymlink(ByteString.copyFromUtf8("hdfs://yaks/dingos")); } if (FileType.IS_FILE.equals(t)) { hspb.setFileId(4544); } HdfsFileStatusProto hsp = hspb.build(); byte[] src = hsp.toByteArray(); FileStatusProto fsp = FileStatusProto.parseFrom(src); assertEquals(hsp.getPath().toStringUtf8(), fsp.getPath()); assertEquals(hsp.getLength(), fsp.getLength()); assertEquals(hsp.getPermission().getPerm(), fsp.getPermission().getPerm()); assertEquals(hsp.getOwner(), fsp.getOwner()); assertEquals(hsp.getGroup(), fsp.getGroup()); assertEquals(hsp.getModificationTime(), fsp.getModificationTime()); assertEquals(hsp.getAccessTime(), fsp.getAccessTime()); assertEquals(hsp.getSymlink().toStringUtf8(), fsp.getSymlink()); assertEquals(hsp.getBlockReplication(), fsp.getBlockReplication()); assertEquals(hsp.getBlocksize(), fsp.getBlockSize()); assertEquals(hsp.getFileType().ordinal(), fsp.getFileType().ordinal()); // verify unknown fields preserved byte[] dst = fsp.toByteArray(); HdfsFileStatusProto hsp2 = HdfsFileStatusProto.parseFrom(dst); assertEquals(hsp, hsp2); FileStatus hstat = (FileStatus) PBHelperClient.convert(hsp); FileStatus hstat2 = (FileStatus) PBHelperClient.convert(hsp2); checkFields(hstat, hstat2); } } }
TestFileStatusSerialization
java
apache__camel
core/camel-base/src/main/java/org/apache/camel/impl/event/CamelContextResumedEvent.java
{ "start": 951, "end": 1348 }
class ____ extends AbstractContextEvent implements CamelEvent.CamelContextResumedEvent { private static final @Serial long serialVersionUID = 6761726800283234512L; public CamelContextResumedEvent(CamelContext source) { super(source); } @Override public String toString() { return "Resumed CamelContext: " + getContext().getName(); } }
CamelContextResumedEvent
java
google__gson
gson/src/test/java/com/google/gson/functional/JsonAdapterAnnotationOnClassesTest.java
{ "start": 26602, "end": 27564 }
class ____ implements JsonDeserializer<WithJsonDeserializer> { @Override public WithJsonDeserializer deserialize( JsonElement json, Type typeOfT, JsonDeserializationContext context) { return new WithJsonDeserializer("123"); } } } /** * Tests creation of the adapter referenced by {@code @JsonAdapter} using an {@link * InstanceCreator}. */ @Test public void testAdapterCreatedByInstanceCreator() { CreatedByInstanceCreator.Serializer serializer = new CreatedByInstanceCreator.Serializer("custom"); Gson gson = new GsonBuilder() .registerTypeAdapter( CreatedByInstanceCreator.Serializer.class, (InstanceCreator<?>) t -> serializer) .create(); String json = gson.toJson(new CreatedByInstanceCreator()); assertThat(json).isEqualTo("\"custom\""); } @JsonAdapter(CreatedByInstanceCreator.Serializer.class) private static
Deserializer
java
apache__maven
its/core-it-suite/src/test/java/org/apache/maven/it/MavenITmng7967ArtifactHandlerLanguageTest.java
{ "start": 1288, "end": 2645 }
class ____ extends AbstractMavenIntegrationTestCase { @Test void javadocIsExecutedAndFailed() throws Exception { File testDir = extractResources("/mng-7967-artifact-handler-language"); Verifier verifier = newVerifier(testDir.getAbsolutePath()); verifier.deleteDirectory("target"); verifier.addCliArgument("org.apache.maven.plugins:maven-javadoc-plugin:3.6.3:jar"); boolean invocationFailed = false; // whatever outcome we do not fail here, but later try { verifier.execute(); } catch (VerificationException e) { invocationFailed = true; } List<String> logs = verifier.loadLogLines(); // javadoc:jar uses language to detect is this "Java classpath-capable package" verifyTextNotInLog(logs, "[INFO] Not executing Javadoc as the project is not a Java classpath-capable package"); // javadoc invocation should actually fail the build verifyTextInLog(logs, "[INFO] BUILD FAILURE"); // javadoc invocation should actually fail the build verifyTextInLog(logs, "[ERROR] Failed to execute goal org.apache.maven.plugins:maven-javadoc-plugin"); assertTrue(invocationFailed, "The Maven invocation should have failed: the javadoc should error out"); } }
MavenITmng7967ArtifactHandlerLanguageTest
java
hibernate__hibernate-orm
hibernate-envers/src/main/java/org/hibernate/envers/configuration/internal/metadata/reader/PersistentPropertiesSource.java
{ "start": 2837, "end": 3634 }
class ____ * @param dynamic whether the component is dynamic or not * @return the properties source */ static PersistentPropertiesSource forComponent(Component component, ClassDetails classDetails, boolean dynamic) { return new PersistentPropertiesSource() { @Override public Iterator<Property> getPropertyIterator() { return component.getProperties().iterator(); } @Override public Property getProperty(String propertyName) { return component.getProperty( propertyName ); } @Override public ClassDetails getClassDetails() { return classDetails; } @Override public boolean isDynamicComponent() { return dynamic; } @Override public boolean hasCompositeUserType() { return component.getTypeName() != null; } }; } }
details
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/logaggregation/ExtendedLogMetaRequest.java
{ "start": 6419, "end": 8143 }
class ____ { public static final String GREATER_OPERATOR = ">"; public static final String LESSER_OPERATOR = "<"; private String expression; private Predicate<Long> comparisonFn; private Long convertedValue; public ComparisonExpression(String expression) { if (expression == null) { return; } if (expression.startsWith(GREATER_OPERATOR)) { convertedValue = Long.parseLong(expression.substring(1)); comparisonFn = a -> a > convertedValue; } else if (expression.startsWith(LESSER_OPERATOR)) { convertedValue = Long.parseLong(expression.substring(1)); comparisonFn = a -> a < convertedValue; } else { convertedValue = Long.parseLong(expression); comparisonFn = a -> a.equals(convertedValue); } this.expression = expression; } public boolean match(String value) { return match(Long.valueOf(value), true); } public boolean match(Long value) { return match(value, true); } /** * Test the given value with the defined comparison functions based on * stringified expression. * @param value value to test with * @param defaultValue value to return when no expression was defined * @return comparison test result or the given default value */ public boolean match(Long value, boolean defaultValue) { if (expression == null) { return defaultValue; } else { return comparisonFn.test(value); } } @Override public String toString() { return convertedValue != null ? String.valueOf(convertedValue) : ""; } } /** * Wraps a regex matcher. */ public static
ComparisonExpression
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-server/hadoop-yarn-server-resourcemanager/src/main/java/org/apache/hadoop/yarn/server/resourcemanager/rmapp/attempt/RMAppAttemptImpl.java
{ "start": 42462, "end": 43891 }
class ____ extends BaseTransition { @Override public void transition(RMAppAttemptImpl appAttempt, RMAppAttemptEvent event) { boolean transferStateFromPreviousAttempt = false; if (event instanceof RMAppStartAttemptEvent) { transferStateFromPreviousAttempt = ((RMAppStartAttemptEvent) event) .getTransferStateFromPreviousAttempt(); } appAttempt.startTime = System.currentTimeMillis(); // Register with the ApplicationMasterService appAttempt.masterService .registerAppAttempt(appAttempt.applicationAttemptId); if (UserGroupInformation.isSecurityEnabled()) { appAttempt.clientTokenMasterKey = appAttempt.rmContext.getClientToAMTokenSecretManager() .createMasterKey(appAttempt.applicationAttemptId); } // Add the applicationAttempt to the scheduler and inform the scheduler // whether to transfer the state from previous attempt. appAttempt.eventHandler.handle(new AppAttemptAddedSchedulerEvent( appAttempt.applicationAttemptId, transferStateFromPreviousAttempt)); } } private static final List<ContainerId> EMPTY_CONTAINER_RELEASE_LIST = new ArrayList<ContainerId>(); private static final List<ResourceRequest> EMPTY_CONTAINER_REQUEST_LIST = new ArrayList<ResourceRequest>(); @VisibleForTesting public static final
AttemptStartedTransition
java
spring-projects__spring-framework
spring-webmvc/src/main/java/org/springframework/web/servlet/config/annotation/ViewControllerRegistry.java
{ "start": 1316, "end": 5771 }
class ____ { private final @Nullable ApplicationContext applicationContext; private final List<ViewControllerRegistration> registrations = new ArrayList<>(4); private final List<RedirectViewControllerRegistration> redirectRegistrations = new ArrayList<>(10); private int order = 1; /** * Class constructor with {@link ApplicationContext}. * @since 4.3.12 */ public ViewControllerRegistry(@Nullable ApplicationContext applicationContext) { this.applicationContext = applicationContext; } /** * Map a URL path or pattern to a view controller to render a response with * the configured status code and view. * <p>Patterns such as {@code "/admin/**"} or {@code "/articles/{articlename:\\w+}"} * are supported. For pattern syntax see {@link PathPattern} when parsed * patterns are {@link PathMatchConfigurer#setPatternParser enabled} or * {@link AntPathMatcher} otherwise. The syntax is largely the same with * {@link PathPattern} more tailored for web usage and more efficient. * <p><strong>Note:</strong> If an {@code @RequestMapping} method is mapped * to a URL for any HTTP method then a view controller cannot handle the * same URL. For this reason it is recommended to avoid splitting URL * handling across an annotated controller and a view controller. */ public ViewControllerRegistration addViewController(String urlPathOrPattern) { ViewControllerRegistration registration = new ViewControllerRegistration(urlPathOrPattern); registration.setApplicationContext(this.applicationContext); this.registrations.add(registration); return registration; } /** * Map a view controller to the given URL path or pattern in order to redirect * to another URL. * <p>For pattern syntax see {@link PathPattern} when parsed patterns * are {@link PathMatchConfigurer#setPatternParser enabled} or * {@link AntPathMatcher} otherwise. The syntax is largely the same with * {@link PathPattern} more tailored for web usage and more efficient. * <p>By default the redirect URL is expected to be relative to the current * ServletContext, i.e. as relative to the web application root. * @since 4.1 */ public RedirectViewControllerRegistration addRedirectViewController(String urlPath, String redirectUrl) { RedirectViewControllerRegistration registration = new RedirectViewControllerRegistration(urlPath, redirectUrl); registration.setApplicationContext(this.applicationContext); this.redirectRegistrations.add(registration); return registration; } /** * Map a simple controller to the given URL path (or pattern) in order to * set the response status to the given code without rendering a body. * <p>For pattern syntax see {@link PathPattern} when parsed patterns * are {@link PathMatchConfigurer#setPatternParser enabled} or * {@link AntPathMatcher} otherwise. The syntax is largely the same with * {@link PathPattern} more tailored for web usage and more efficient. * @since 4.1 */ public void addStatusController(String urlPath, HttpStatusCode statusCode) { ViewControllerRegistration registration = new ViewControllerRegistration(urlPath); registration.setApplicationContext(this.applicationContext); registration.setStatusCode(statusCode); registration.getViewController().setStatusOnly(true); this.registrations.add(registration); } /** * Specify the order to use for the {@code HandlerMapping} used to map view * controllers relative to other handler mappings configured in Spring MVC. * <p>By default this is set to 1, i.e. right after annotated controllers, * which are ordered at 0. */ public void setOrder(int order) { this.order = order; } /** * Return the {@code HandlerMapping} that contains the registered view * controller mappings, or {@code null} for no registrations. * @since 4.3.12 */ protected @Nullable SimpleUrlHandlerMapping buildHandlerMapping() { if (this.registrations.isEmpty() && this.redirectRegistrations.isEmpty()) { return null; } Map<String, Object> urlMap = new LinkedHashMap<>(); for (ViewControllerRegistration registration : this.registrations) { urlMap.put(registration.getUrlPath(), registration.getViewController()); } for (RedirectViewControllerRegistration registration : this.redirectRegistrations) { urlMap.put(registration.getUrlPath(), registration.getViewController()); } return new SimpleUrlHandlerMapping(urlMap, this.order); } }
ViewControllerRegistry
java
apache__flink
flink-streaming-java/src/main/java/org/apache/flink/streaming/api/operators/async/queue/WatermarkQueueEntry.java
{ "start": 1244, "end": 1923 }
class ____<OUT> implements StreamElementQueueEntry<OUT> { @Nonnull private final Watermark watermark; WatermarkQueueEntry(Watermark watermark) { this.watermark = Preconditions.checkNotNull(watermark); } @Override public void emitResult(TimestampedCollector<OUT> output) { output.emitWatermark(watermark); } @Nonnull @Override public Watermark getInputElement() { return watermark; } @Override public boolean isDone() { return true; } @Override public void complete(Collection result) { throw new IllegalStateException("Cannot complete a watermark."); } }
WatermarkQueueEntry
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/exceptionhandling/StaleObjectStateExceptionHandlingTest.java
{ "start": 2582, "end": 2705 }
class ____ { @Id private long id; private String name; @Version @Column(name = "ver") private int version; } }
A
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/maybe/MaybeTimer.java
{ "start": 980, "end": 1564 }
class ____ extends Maybe<Long> { final long delay; final TimeUnit unit; final Scheduler scheduler; public MaybeTimer(long delay, TimeUnit unit, Scheduler scheduler) { this.delay = delay; this.unit = unit; this.scheduler = scheduler; } @Override protected void subscribeActual(final MaybeObserver<? super Long> observer) { TimerDisposable parent = new TimerDisposable(observer); observer.onSubscribe(parent); parent.setFuture(scheduler.scheduleDirect(parent, delay, unit)); } static final
MaybeTimer
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/api/protocolrecords/impl/pb/GetNodesToAttributesRequestPBImpl.java
{ "start": 1287, "end": 3694 }
class ____ extends GetNodesToAttributesRequest { private GetNodesToAttributesRequestProto proto = GetNodesToAttributesRequestProto.getDefaultInstance(); private GetNodesToAttributesRequestProto.Builder builder = null; private Set<String> hostNames = null; private boolean viaProto = false; public GetNodesToAttributesRequestPBImpl() { builder = GetNodesToAttributesRequestProto.newBuilder(); } public GetNodesToAttributesRequestPBImpl( GetNodesToAttributesRequestProto proto) { this.proto = proto; viaProto = true; } public GetNodesToAttributesRequestProto getProto() { mergeLocalToProto(); proto = viaProto ? proto : builder.build(); viaProto = true; return proto; } private void mergeLocalToProto() { if (viaProto) { maybeInitBuilder(); } mergeLocalToBuilder(); proto = builder.build(); viaProto = true; } private void mergeLocalToBuilder() { if (hostNames != null && !hostNames.isEmpty()) { builder.clearHostnames(); builder.addAllHostnames(hostNames); } } @Override public int hashCode() { return getProto().hashCode(); } @Override public boolean equals(Object other) { if (other == null) { return false; } if (other.getClass().isAssignableFrom(this.getClass())) { return this.getProto().equals(this.getClass().cast(other).getProto()); } return false; } @Override public String toString() { return TextFormat.shortDebugString(getProto()); } @Override public void setHostNames(Set<String> hostnames) { maybeInitBuilder(); if (hostNames == null) { builder.clearHostnames(); } this.hostNames = hostnames; } private void maybeInitBuilder() { if (viaProto || builder == null) { builder = YarnServiceProtos.GetNodesToAttributesRequestProto.newBuilder(proto); } viaProto = false; } @Override public Set<String> getHostNames() { initNodeToAttributes(); return this.hostNames; } private void initNodeToAttributes() { if (this.hostNames != null) { return; } YarnServiceProtos.GetNodesToAttributesRequestProtoOrBuilder p = viaProto ? proto : builder; List<String> hostNamesList = p.getHostnamesList(); this.hostNames = new HashSet<>(); this.hostNames.addAll(hostNamesList); } }
GetNodesToAttributesRequestPBImpl
java
apache__kafka
connect/runtime/src/main/java/org/apache/kafka/connect/runtime/errors/Stage.java
{ "start": 1092, "end": 1917 }
enum ____ { /** * When calling {@link SourceTask#poll()} */ TASK_POLL, /** * When calling {@link SinkTask#put(Collection)} */ TASK_PUT, /** * When running any transformation operation on a record */ TRANSFORMATION, /** * When using the key converter to serialize/deserialize keys in {@link ConnectRecord}s */ KEY_CONVERTER, /** * When using the value converter to serialize/deserialize values in {@link ConnectRecord}s */ VALUE_CONVERTER, /** * When using the header converter to serialize/deserialize headers in {@link ConnectRecord}s */ HEADER_CONVERTER, /** * When producing to a Kafka topic */ KAFKA_PRODUCE, /** * When consuming from a Kafka topic */ KAFKA_CONSUME }
Stage
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/operators/flowable/FlowableBufferTest.java
{ "start": 10793, "end": 78681 }
class ____ implements Consumer<List<Integer>> { CountDownLatch latch; boolean fail; LongTimeAction(CountDownLatch latch) { this.latch = latch; } @Override public void accept(List<Integer> t1) { try { if (fail) { return; } Thread.sleep(200); } catch (InterruptedException e) { fail = true; } finally { latch.countDown(); } } } private List<String> list(String... args) { List<String> list = new ArrayList<>(); for (String arg : args) { list.add(arg); } return list; } private <T> void push(final Subscriber<T> subscriber, final T value, int delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { subscriber.onNext(value); } }, delay, TimeUnit.MILLISECONDS); } private void complete(final Subscriber<?> subscriber, int delay) { innerScheduler.schedule(new Runnable() { @Override public void run() { subscriber.onComplete(); } }, delay, TimeUnit.MILLISECONDS); } @Test public void bufferStopsWhenUnsubscribed1() { Flowable<Integer> source = Flowable.never(); Subscriber<List<Integer>> subscriber = TestHelper.mockSubscriber(); TestSubscriber<List<Integer>> ts = new TestSubscriber<>(subscriber, 0L); source.buffer(100, 200, TimeUnit.MILLISECONDS, scheduler) .doOnNext(new Consumer<List<Integer>>() { @Override public void accept(List<Integer> pv) { System.out.println(pv); } }) .subscribe(ts); InOrder inOrder = Mockito.inOrder(subscriber); scheduler.advanceTimeBy(1001, TimeUnit.MILLISECONDS); inOrder.verify(subscriber, times(5)).onNext(Arrays.<Integer> asList()); ts.cancel(); scheduler.advanceTimeBy(999, TimeUnit.MILLISECONDS); inOrder.verifyNoMoreInteractions(); } @Test public void bufferWithBONormal1() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); InOrder inOrder = Mockito.inOrder(subscriber); source.buffer(boundary).subscribe(subscriber); source.onNext(1); source.onNext(2); source.onNext(3); boundary.onNext(1); inOrder.verify(subscriber, times(1)).onNext(Arrays.asList(1, 2, 3)); source.onNext(4); source.onNext(5); boundary.onNext(2); inOrder.verify(subscriber, times(1)).onNext(Arrays.asList(4, 5)); source.onNext(6); boundary.onComplete(); inOrder.verify(subscriber, times(1)).onNext(Arrays.asList(6)); inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithBOEmptyLastViaBoundary() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); InOrder inOrder = Mockito.inOrder(subscriber); source.buffer(boundary).subscribe(subscriber); boundary.onComplete(); inOrder.verify(subscriber, times(1)).onNext(Arrays.asList()); inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithBOEmptyLastViaSource() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); InOrder inOrder = Mockito.inOrder(subscriber); source.buffer(boundary).subscribe(subscriber); source.onComplete(); inOrder.verify(subscriber, times(1)).onNext(Arrays.asList()); inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithBOEmptyLastViaBoth() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); InOrder inOrder = Mockito.inOrder(subscriber); source.buffer(boundary).subscribe(subscriber); source.onComplete(); boundary.onComplete(); inOrder.verify(subscriber, times(1)).onNext(Arrays.asList()); inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithBOSourceThrows() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); source.buffer(boundary).subscribe(subscriber); source.onNext(1); source.onError(new TestException()); verify(subscriber).onError(any(TestException.class)); verify(subscriber, never()).onComplete(); verify(subscriber, never()).onNext(any()); } @Test public void bufferWithBOBoundaryThrows() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> boundary = PublishProcessor.create(); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); source.buffer(boundary).subscribe(subscriber); source.onNext(1); boundary.onError(new TestException()); verify(subscriber).onError(any(TestException.class)); verify(subscriber, never()).onComplete(); verify(subscriber, never()).onNext(any()); } @Test public void bufferWithSizeTake1() { Flowable<Integer> source = Flowable.just(1).repeat(); Flowable<List<Integer>> result = source.buffer(2).take(1); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); result.subscribe(subscriber); verify(subscriber).onNext(Arrays.asList(1, 1)); verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithSizeSkipTake1() { Flowable<Integer> source = Flowable.just(1).repeat(); Flowable<List<Integer>> result = source.buffer(2, 3).take(1); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); result.subscribe(subscriber); verify(subscriber).onNext(Arrays.asList(1, 1)); verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithTimeTake1() { Flowable<Long> source = Flowable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); Flowable<List<Long>> result = source.buffer(100, TimeUnit.MILLISECONDS, scheduler).take(1); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); result.subscribe(subscriber); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); verify(subscriber).onNext(Arrays.asList(0L, 1L)); verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithTimeSkipTake2() { Flowable<Long> source = Flowable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); Flowable<List<Long>> result = source.buffer(100, 60, TimeUnit.MILLISECONDS, scheduler).take(2); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(subscriber); result.subscribe(subscriber); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); inOrder.verify(subscriber).onNext(Arrays.asList(0L, 1L)); inOrder.verify(subscriber).onNext(Arrays.asList(1L, 2L)); inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithBoundaryTake2() { Flowable<Long> boundary = Flowable.interval(60, 60, TimeUnit.MILLISECONDS, scheduler); Flowable<Long> source = Flowable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); Flowable<List<Long>> result = source.buffer(boundary).take(2); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(subscriber); result.subscribe(subscriber); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); inOrder.verify(subscriber).onNext(Arrays.asList(0L)); inOrder.verify(subscriber).onNext(Arrays.asList(1L)); inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithStartEndBoundaryTake2() { Flowable<Long> start = Flowable.interval(61, 61, TimeUnit.MILLISECONDS, scheduler); Function<Long, Flowable<Long>> end = new Function<Long, Flowable<Long>>() { @Override public Flowable<Long> apply(Long t1) { return Flowable.interval(100, 100, TimeUnit.MILLISECONDS, scheduler); } }; Flowable<Long> source = Flowable.interval(40, 40, TimeUnit.MILLISECONDS, scheduler); Flowable<List<Long>> result = source.buffer(start, end).take(2); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(subscriber); result .doOnNext(new Consumer<List<Long>>() { @Override public void accept(List<Long> pv) { System.out.println(pv); } }) .subscribe(subscriber); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); inOrder.verify(subscriber).onNext(Arrays.asList(1L, 2L, 3L)); inOrder.verify(subscriber).onNext(Arrays.asList(3L, 4L)); inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithSizeThrows() { PublishProcessor<Integer> source = PublishProcessor.create(); Flowable<List<Integer>> result = source.buffer(2); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(subscriber); result.subscribe(subscriber); source.onNext(1); source.onNext(2); source.onNext(3); source.onError(new TestException()); inOrder.verify(subscriber).onNext(Arrays.asList(1, 2)); inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); verify(subscriber, never()).onNext(Arrays.asList(3)); verify(subscriber, never()).onComplete(); } @Test public void bufferWithTimeThrows() { PublishProcessor<Integer> source = PublishProcessor.create(); Flowable<List<Integer>> result = source.buffer(100, TimeUnit.MILLISECONDS, scheduler); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(subscriber); result.subscribe(subscriber); source.onNext(1); source.onNext(2); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); source.onNext(3); source.onError(new TestException()); scheduler.advanceTimeBy(100, TimeUnit.MILLISECONDS); inOrder.verify(subscriber).onNext(Arrays.asList(1, 2)); inOrder.verify(subscriber).onError(any(TestException.class)); inOrder.verifyNoMoreInteractions(); verify(subscriber, never()).onNext(Arrays.asList(3)); verify(subscriber, never()).onComplete(); } @Test public void bufferWithTimeAndSize() { Flowable<Long> source = Flowable.interval(30, 30, TimeUnit.MILLISECONDS, scheduler); Flowable<List<Long>> result = source.buffer(100, TimeUnit.MILLISECONDS, scheduler, 2).take(3); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); InOrder inOrder = inOrder(subscriber); result.subscribe(subscriber); scheduler.advanceTimeBy(5, TimeUnit.SECONDS); inOrder.verify(subscriber).onNext(Arrays.asList(0L, 1L)); inOrder.verify(subscriber).onNext(Arrays.asList(2L)); inOrder.verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); } @Test public void bufferWithStartEndStartThrows() { PublishProcessor<Integer> start = PublishProcessor.create(); Function<Integer, Flowable<Integer>> end = new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer t1) { return Flowable.never(); } }; PublishProcessor<Integer> source = PublishProcessor.create(); Flowable<List<Integer>> result = source.buffer(start, end); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); result.subscribe(subscriber); start.onNext(1); source.onNext(1); source.onNext(2); start.onError(new TestException()); verify(subscriber, never()).onNext(any()); verify(subscriber, never()).onComplete(); verify(subscriber).onError(any(TestException.class)); } @Test public void bufferWithStartEndEndFunctionThrows() { PublishProcessor<Integer> start = PublishProcessor.create(); Function<Integer, Flowable<Integer>> end = new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer t1) { throw new TestException(); } }; PublishProcessor<Integer> source = PublishProcessor.create(); Flowable<List<Integer>> result = source.buffer(start, end); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); result.subscribe(subscriber); start.onNext(1); source.onNext(1); source.onNext(2); verify(subscriber, never()).onNext(any()); verify(subscriber, never()).onComplete(); verify(subscriber).onError(any(TestException.class)); } @Test public void bufferWithStartEndEndThrows() { PublishProcessor<Integer> start = PublishProcessor.create(); Function<Integer, Flowable<Integer>> end = new Function<Integer, Flowable<Integer>>() { @Override public Flowable<Integer> apply(Integer t1) { return Flowable.error(new TestException()); } }; PublishProcessor<Integer> source = PublishProcessor.create(); Flowable<List<Integer>> result = source.buffer(start, end); Subscriber<Object> subscriber = TestHelper.mockSubscriber(); result.subscribe(subscriber); start.onNext(1); source.onNext(1); source.onNext(2); verify(subscriber, never()).onNext(any()); verify(subscriber, never()).onComplete(); verify(subscriber).onError(any(TestException.class)); } @Test public void producerRequestThroughBufferWithSize1() { TestSubscriber<List<Integer>> ts = new TestSubscriber<>(3L); final AtomicLong requested = new AtomicLong(); Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { requested.set(n); } @Override public void cancel() { } }); } }).buffer(5, 5).subscribe(ts); assertEquals(15, requested.get()); ts.request(4); assertEquals(20, requested.get()); } @Test public void producerRequestThroughBufferWithSize2() { TestSubscriber<List<Integer>> ts = new TestSubscriber<>(); final AtomicLong requested = new AtomicLong(); Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { requested.set(n); } @Override public void cancel() { } }); } }).buffer(5, 5).subscribe(ts); assertEquals(Long.MAX_VALUE, requested.get()); } @Test public void producerRequestThroughBufferWithSize3() { TestSubscriber<List<Integer>> ts = new TestSubscriber<>(3L); final AtomicLong requested = new AtomicLong(); Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { requested.set(n); } @Override public void cancel() { } }); } }).buffer(5, 2).subscribe(ts); assertEquals(9, requested.get()); ts.request(3); assertEquals(6, requested.get()); } @Test public void producerRequestThroughBufferWithSize4() { TestSubscriber<List<Integer>> ts = new TestSubscriber<>(); final AtomicLong requested = new AtomicLong(); Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { requested.set(n); } @Override public void cancel() { } }); } }).buffer(5, 2).subscribe(ts); assertEquals(Long.MAX_VALUE, requested.get()); } @Test public void producerRequestOverflowThroughBufferWithSize1() { TestSubscriber<List<Integer>> ts = new TestSubscriber<>(Long.MAX_VALUE >> 1); final AtomicLong requested = new AtomicLong(); Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { requested.set(n); } @Override public void cancel() { } }); } }).buffer(3, 3).subscribe(ts); assertEquals(Long.MAX_VALUE, requested.get()); } @Test public void producerRequestOverflowThroughBufferWithSize2() { TestSubscriber<List<Integer>> ts = new TestSubscriber<>(Long.MAX_VALUE >> 1); final AtomicLong requested = new AtomicLong(); Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(Subscriber<? super Integer> s) { s.onSubscribe(new Subscription() { @Override public void request(long n) { requested.set(n); } @Override public void cancel() { } }); } }).buffer(3, 2).subscribe(ts); assertEquals(Long.MAX_VALUE, requested.get()); } @Test public void producerRequestOverflowThroughBufferWithSize3() { final AtomicLong requested = new AtomicLong(); Flowable.unsafeCreate(new Publisher<Integer>() { @Override public void subscribe(final Subscriber<? super Integer> s) { s.onSubscribe(new Subscription() { AtomicBoolean once = new AtomicBoolean(); @Override public void request(long n) { requested.set(n); if (once.compareAndSet(false, true)) { s.onNext(1); s.onNext(2); s.onNext(3); } } @Override public void cancel() { } }); } }).buffer(3, 2).subscribe(new DefaultSubscriber<List<Integer>>() { @Override public void onStart() { request(Long.MAX_VALUE / 2 - 4); } @Override public void onComplete() { } @Override public void onError(Throwable e) { } @Override public void onNext(List<Integer> t) { request(Long.MAX_VALUE / 2); } }); // FIXME I'm not sure why this is MAX_VALUE in 1.x because MAX_VALUE/2 is even and thus can't overflow when multiplied by 2 assertEquals(Long.MAX_VALUE - 1, requested.get()); } @Test public void bufferWithTimeDoesntUnsubscribeDownstream() throws InterruptedException { final Subscriber<Object> subscriber = TestHelper.mockSubscriber(); final CountDownLatch cdl = new CountDownLatch(1); ResourceSubscriber<Object> s = new ResourceSubscriber<Object>() { @Override public void onNext(Object t) { subscriber.onNext(t); } @Override public void onError(Throwable e) { subscriber.onError(e); cdl.countDown(); } @Override public void onComplete() { subscriber.onComplete(); cdl.countDown(); } }; Flowable.range(1, 1).delay(1, TimeUnit.SECONDS).buffer(2, TimeUnit.SECONDS).subscribe(s); cdl.await(); verify(subscriber).onNext(Arrays.asList(1)); verify(subscriber).onComplete(); verify(subscriber, never()).onError(any(Throwable.class)); assertFalse(s.isDisposed()); } @Test public void postCompleteBackpressure() { Flowable<List<Integer>> source = Flowable.range(1, 10).buffer(3, 1); TestSubscriber<List<Integer>> ts = TestSubscriber.create(0L); source.subscribe(ts); ts.assertNoValues(); ts.assertNotComplete(); ts.assertNoErrors(); ts.request(7); ts.assertValues( Arrays.asList(1, 2, 3), Arrays.asList(2, 3, 4), Arrays.asList(3, 4, 5), Arrays.asList(4, 5, 6), Arrays.asList(5, 6, 7), Arrays.asList(6, 7, 8), Arrays.asList(7, 8, 9) ); ts.assertNotComplete(); ts.assertNoErrors(); ts.request(1); ts.assertValues( Arrays.asList(1, 2, 3), Arrays.asList(2, 3, 4), Arrays.asList(3, 4, 5), Arrays.asList(4, 5, 6), Arrays.asList(5, 6, 7), Arrays.asList(6, 7, 8), Arrays.asList(7, 8, 9), Arrays.asList(8, 9, 10) ); ts.assertNotComplete(); ts.assertNoErrors(); ts.request(1); ts.assertValues( Arrays.asList(1, 2, 3), Arrays.asList(2, 3, 4), Arrays.asList(3, 4, 5), Arrays.asList(4, 5, 6), Arrays.asList(5, 6, 7), Arrays.asList(6, 7, 8), Arrays.asList(7, 8, 9), Arrays.asList(8, 9, 10), Arrays.asList(9, 10) ); ts.assertNotComplete(); ts.assertNoErrors(); ts.request(1); ts.assertValues( Arrays.asList(1, 2, 3), Arrays.asList(2, 3, 4), Arrays.asList(3, 4, 5), Arrays.asList(4, 5, 6), Arrays.asList(5, 6, 7), Arrays.asList(6, 7, 8), Arrays.asList(7, 8, 9), Arrays.asList(8, 9, 10), Arrays.asList(9, 10), Arrays.asList(10) ); ts.assertComplete(); ts.assertNoErrors(); } @Test public void timeAndSkipOverlap() { PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = TestSubscriber.create(); pp.buffer(2, 1, TimeUnit.SECONDS, scheduler).subscribe(ts); pp.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(2); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(3); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(4); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onComplete(); ts.assertValues( Arrays.asList(1, 2), Arrays.asList(2, 3), Arrays.asList(3, 4), Arrays.asList(4), Collections.<Integer>emptyList() ); ts.assertNoErrors(); ts.assertComplete(); } @Test public void timeAndSkipSkip() { PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = TestSubscriber.create(); pp.buffer(2, 3, TimeUnit.SECONDS, scheduler).subscribe(ts); pp.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(2); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(3); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(4); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onComplete(); ts.assertValues( Arrays.asList(1, 2), Arrays.asList(4) ); ts.assertNoErrors(); ts.assertComplete(); } @Test public void timeAndSkipOverlapScheduler() { RxJavaPlugins.setComputationSchedulerHandler(new Function<Scheduler, Scheduler>() { @Override public Scheduler apply(Scheduler t) { return scheduler; } }); try { PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = TestSubscriber.create(); pp.buffer(2, 1, TimeUnit.SECONDS).subscribe(ts); pp.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(2); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(3); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(4); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onComplete(); ts.assertValues( Arrays.asList(1, 2), Arrays.asList(2, 3), Arrays.asList(3, 4), Arrays.asList(4), Collections.<Integer>emptyList() ); ts.assertNoErrors(); ts.assertComplete(); } finally { RxJavaPlugins.reset(); } } @Test public void timeAndSkipSkipDefaultScheduler() { RxJavaPlugins.setComputationSchedulerHandler(new Function<Scheduler, Scheduler>() { @Override public Scheduler apply(Scheduler t) { return scheduler; } }); try { PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = TestSubscriber.create(); pp.buffer(2, 3, TimeUnit.SECONDS).subscribe(ts); pp.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(2); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(3); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onNext(4); scheduler.advanceTimeBy(1, TimeUnit.SECONDS); pp.onComplete(); ts.assertValues( Arrays.asList(1, 2), Arrays.asList(4) ); ts.assertNoErrors(); ts.assertComplete(); } finally { RxJavaPlugins.reset(); } } @Test public void bufferBoundaryHint() { Flowable.range(1, 5).buffer(Flowable.timer(1, TimeUnit.MINUTES), 2) .test() .assertResult(Arrays.asList(1, 2, 3, 4, 5)); } static HashSet<Integer> set(Integer... values) { return new HashSet<>(Arrays.asList(values)); } @Test public void bufferIntoCustomCollection() { Flowable.just(1, 1, 2, 2, 3, 3, 4, 4) .buffer(3, new Supplier<Collection<Integer>>() { @Override public Collection<Integer> get() throws Exception { return new HashSet<>(); } }) .test() .assertResult(set(1, 2), set(2, 3), set(4)); } @Test public void bufferSkipIntoCustomCollection() { Flowable.just(1, 1, 2, 2, 3, 3, 4, 4) .buffer(3, 3, new Supplier<Collection<Integer>>() { @Override public Collection<Integer> get() throws Exception { return new HashSet<>(); } }) .test() .assertResult(set(1, 2), set(2, 3), set(4)); } @Test public void bufferTimeSkipDefault() { Flowable.range(1, 5).buffer(1, 1, TimeUnit.MINUTES) .test() .assertResult(Arrays.asList(1, 2, 3, 4, 5)); } @Test public void dispose() { TestHelper.checkDisposed(Flowable.range(1, 5).buffer(1, TimeUnit.DAYS, Schedulers.single())); TestHelper.checkDisposed(Flowable.range(1, 5).buffer(2, 1, TimeUnit.DAYS, Schedulers.single())); TestHelper.checkDisposed(Flowable.range(1, 5).buffer(1, 2, TimeUnit.DAYS, Schedulers.single())); TestHelper.checkDisposed(Flowable.range(1, 5) .buffer(1, TimeUnit.DAYS, Schedulers.single(), 2, Functions.<Integer>createArrayList(16), true)); TestHelper.checkDisposed(Flowable.range(1, 5).buffer(1)); TestHelper.checkDisposed(Flowable.range(1, 5).buffer(2, 1)); TestHelper.checkDisposed(Flowable.range(1, 5).buffer(1, 2)); } @Test public void supplierReturnsNull() { Flowable.<Integer>never() .buffer(1, TimeUnit.MILLISECONDS, Schedulers.single(), Integer.MAX_VALUE, new Supplier<Collection<Integer>>() { int count; @Override public Collection<Integer> get() throws Exception { if (count++ == 1) { return null; } else { return new ArrayList<>(); } } }, false) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(NullPointerException.class); } @Test public void supplierReturnsNull2() { Flowable.<Integer>never() .buffer(1, TimeUnit.MILLISECONDS, Schedulers.single(), 10, new Supplier<Collection<Integer>>() { int count; @Override public Collection<Integer> get() throws Exception { if (count++ == 1) { return null; } else { return new ArrayList<>(); } } }, false) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(NullPointerException.class); } @Test public void supplierReturnsNull3() { Flowable.<Integer>never() .buffer(2, 1, TimeUnit.MILLISECONDS, Schedulers.single(), new Supplier<Collection<Integer>>() { int count; @Override public Collection<Integer> get() throws Exception { if (count++ == 1) { return null; } else { return new ArrayList<>(); } } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(NullPointerException.class); } @Test public void supplierThrows() { Flowable.just(1) .buffer(1, TimeUnit.SECONDS, Schedulers.single(), Integer.MAX_VALUE, new Supplier<Collection<Integer>>() { @Override public Collection<Integer> get() throws Exception { throw new TestException(); } }, false) .test() .assertFailure(TestException.class); } @Test public void supplierThrows2() { Flowable.just(1) .buffer(1, TimeUnit.SECONDS, Schedulers.single(), 10, new Supplier<Collection<Integer>>() { @Override public Collection<Integer> get() throws Exception { throw new TestException(); } }, false) .test() .assertFailure(TestException.class); } @Test public void supplierThrows3() { Flowable.just(1) .buffer(2, 1, TimeUnit.SECONDS, Schedulers.single(), new Supplier<Collection<Integer>>() { @Override public Collection<Integer> get() throws Exception { throw new TestException(); } }) .test() .assertFailure(TestException.class); } @Test public void supplierThrows4() { Flowable.<Integer>never() .buffer(1, TimeUnit.MILLISECONDS, Schedulers.single(), Integer.MAX_VALUE, new Supplier<Collection<Integer>>() { int count; @Override public Collection<Integer> get() throws Exception { if (count++ == 1) { throw new TestException(); } else { return new ArrayList<>(); } } }, false) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test public void supplierThrows5() { Flowable.<Integer>never() .buffer(1, TimeUnit.MILLISECONDS, Schedulers.single(), 10, new Supplier<Collection<Integer>>() { int count; @Override public Collection<Integer> get() throws Exception { if (count++ == 1) { throw new TestException(); } else { return new ArrayList<>(); } } }, false) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test public void supplierThrows6() { Flowable.<Integer>never() .buffer(2, 1, TimeUnit.MILLISECONDS, Schedulers.single(), new Supplier<Collection<Integer>>() { int count; @Override public Collection<Integer> get() throws Exception { if (count++ == 1) { throw new TestException(); } else { return new ArrayList<>(); } } }) .test() .awaitDone(5, TimeUnit.SECONDS) .assertFailure(TestException.class); } @Test public void restartTimer() { Flowable.range(1, 5) .buffer(1, TimeUnit.DAYS, Schedulers.single(), 2, Functions.<Integer>createArrayList(16), true) .test() .assertResult(Arrays.asList(1, 2), Arrays.asList(3, 4), Arrays.asList(5)); } @Test public void bufferSkipError() { Flowable.<Integer>error(new TestException()) .buffer(2, 1) .test() .assertFailure(TestException.class); } @Test public void bufferSupplierCrash2() { Flowable.range(1, 2) .buffer(1, new Supplier<List<Integer>>() { int calls; @Override public List<Integer> get() throws Exception { if (++calls == 2) { throw new TestException(); } return new ArrayList<>(); } }) .test() .assertFailure(TestException.class, Arrays.asList(1)); } @Test public void bufferSkipSupplierCrash2() { Flowable.range(1, 2) .buffer(1, 2, new Supplier<List<Integer>>() { int calls; @Override public List<Integer> get() throws Exception { if (++calls == 1) { throw new TestException(); } return new ArrayList<>(); } }) .test() .assertFailure(TestException.class); } @Test public void bufferOverlapSupplierCrash2() { Flowable.range(1, 2) .buffer(2, 1, new Supplier<List<Integer>>() { int calls; @Override public List<Integer> get() throws Exception { if (++calls == 2) { throw new TestException(); } return new ArrayList<>(); } }) .test() .assertFailure(TestException.class); } @Test public void bufferSkipOverlap() { Flowable.range(1, 5) .buffer(5, 1) .test() .assertResult( Arrays.asList(1, 2, 3, 4, 5), Arrays.asList(2, 3, 4, 5), Arrays.asList(3, 4, 5), Arrays.asList(4, 5), Arrays.asList(5) ); } @Test public void bufferTimedExactError() { Flowable.error(new TestException()) .buffer(1, TimeUnit.DAYS) .test() .assertFailure(TestException.class); } @Test public void bufferTimedSkipError() { Flowable.error(new TestException()) .buffer(1, 2, TimeUnit.DAYS) .test() .assertFailure(TestException.class); } @Test public void bufferTimedOverlapError() { Flowable.error(new TestException()) .buffer(2, 1, TimeUnit.DAYS) .test() .assertFailure(TestException.class); } @Test public void bufferTimedExactEmpty() { Flowable.empty() .buffer(1, TimeUnit.DAYS) .test() .assertResult(Collections.emptyList()); } @Test public void bufferTimedSkipEmpty() { Flowable.empty() .buffer(1, 2, TimeUnit.DAYS) .test() .assertResult(Collections.emptyList()); } @Test public void bufferTimedOverlapEmpty() { Flowable.empty() .buffer(2, 1, TimeUnit.DAYS) .test() .assertResult(Collections.emptyList()); } @Test public void bufferTimedExactSupplierCrash() { TestScheduler scheduler = new TestScheduler(); PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = pp .buffer(1, TimeUnit.MILLISECONDS, scheduler, 1, new Supplier<List<Integer>>() { int calls; @Override public List<Integer> get() throws Exception { if (++calls == 2) { throw new TestException(); } return new ArrayList<>(); } }, true) .test(); pp.onNext(1); scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); pp.onNext(2); ts .assertFailure(TestException.class, Arrays.asList(1)); } @Test public void bufferTimedExactBoundedError() { TestScheduler scheduler = new TestScheduler(); PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = pp .buffer(1, TimeUnit.MILLISECONDS, scheduler, 1, Functions.<Integer>createArrayList(16), true) .test(); pp.onError(new TestException()); ts .assertFailure(TestException.class); } @Test public void badSource() { TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override public Object apply(Flowable<Integer> f) throws Exception { return f.buffer(1); } }, false, 1, 1, Arrays.asList(1)); TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override public Object apply(Flowable<Integer> f) throws Exception { return f.buffer(1, 2); } }, false, 1, 1, Arrays.asList(1)); TestHelper.checkBadSourceFlowable(new Function<Flowable<Integer>, Object>() { @Override public Object apply(Flowable<Integer> f) throws Exception { return f.buffer(2, 1); } }, false, 1, 1, Arrays.asList(1)); } @Test public void doubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<List<Object>>>() { @Override public Publisher<List<Object>> apply(Flowable<Object> f) throws Exception { return f.buffer(1); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<List<Object>>>() { @Override public Publisher<List<Object>> apply(Flowable<Object> f) throws Exception { return f.buffer(1, 2); } }); TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<List<Object>>>() { @Override public Publisher<List<Object>> apply(Flowable<Object> f) throws Exception { return f.buffer(2, 1); } }); } @Test public void badRequest() { TestHelper.assertBadRequestReported(PublishProcessor.create().buffer(1)); TestHelper.assertBadRequestReported(PublishProcessor.create().buffer(1, 2)); TestHelper.assertBadRequestReported(PublishProcessor.create().buffer(2, 1)); } @Test public void skipError() { Flowable.error(new TestException()) .buffer(1, 2) .test() .assertFailure(TestException.class); } @Test public void skipSingleResult() { Flowable.just(1) .buffer(2, 3) .test() .assertResult(Arrays.asList(1)); } @Test public void skipBackpressure() { Flowable.range(1, 10) .buffer(2, 3) .rebatchRequests(1) .test() .assertResult(Arrays.asList(1, 2), Arrays.asList(4, 5), Arrays.asList(7, 8), Arrays.asList(10)); } @Test public void withTimeAndSizeCapacityRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { final TestScheduler scheduler = new TestScheduler(); final PublishProcessor<Object> pp = PublishProcessor.create(); TestSubscriber<List<Object>> ts = pp.buffer(1, TimeUnit.SECONDS, scheduler, 5).test(); pp.onNext(1); pp.onNext(2); pp.onNext(3); pp.onNext(4); Runnable r1 = new Runnable() { @Override public void run() { pp.onNext(5); } }; Runnable r2 = new Runnable() { @Override public void run() { scheduler.advanceTimeBy(1, TimeUnit.SECONDS); } }; TestHelper.race(r1, r2); pp.onComplete(); int items = 0; for (List<Object> o : ts.values()) { items += o.size(); } assertEquals("Round: " + i, 5, items); } } @Test public void noCompletionCancelExact() { final AtomicInteger counter = new AtomicInteger(); Flowable.<Integer>empty() .doOnCancel(new Action() { @Override public void run() throws Exception { counter.getAndIncrement(); } }) .buffer(5, TimeUnit.SECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(Collections.<Integer>emptyList()); assertEquals(0, counter.get()); } @Test public void noCompletionCancelSkip() { final AtomicInteger counter = new AtomicInteger(); Flowable.<Integer>empty() .doOnCancel(new Action() { @Override public void run() throws Exception { counter.getAndIncrement(); } }) .buffer(5, 10, TimeUnit.SECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(Collections.<Integer>emptyList()); assertEquals(0, counter.get()); } @Test public void noCompletionCancelOverlap() { final AtomicInteger counter = new AtomicInteger(); Flowable.<Integer>empty() .doOnCancel(new Action() { @Override public void run() throws Exception { counter.getAndIncrement(); } }) .buffer(10, 5, TimeUnit.SECONDS) .test() .awaitDone(5, TimeUnit.SECONDS) .assertResult(Collections.<Integer>emptyList()); assertEquals(0, counter.get()); } @Test public void boundaryOpenCloseDisposedOnComplete() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> openIndicator = PublishProcessor.create(); PublishProcessor<Integer> closeIndicator = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(); assertTrue(source.hasSubscribers()); assertTrue(openIndicator.hasSubscribers()); assertFalse(closeIndicator.hasSubscribers()); openIndicator.onNext(1); assertTrue(openIndicator.hasSubscribers()); assertTrue(closeIndicator.hasSubscribers()); source.onComplete(); ts.assertResult(Collections.<Integer>emptyList()); assertFalse(openIndicator.hasSubscribers()); assertFalse(closeIndicator.hasSubscribers()); } @Test public void bufferedCanCompleteIfOpenNeverCompletesDropping() { Flowable.range(1, 50) .zipWith(Flowable.interval(5, TimeUnit.MILLISECONDS), new BiFunction<Integer, Long, Integer>() { @Override public Integer apply(Integer integer, Long aLong) { return integer; } }) .buffer(Flowable.interval(0, 200, TimeUnit.MILLISECONDS), new Function<Long, Publisher<?>>() { @Override public Publisher<?> apply(Long a) { return Flowable.just(a).delay(100, TimeUnit.MILLISECONDS); } }) .to(TestHelper.<List<Integer>>testConsumer()) .assertSubscribed() .awaitDone(3, TimeUnit.SECONDS) .assertComplete(); } @Test public void bufferedCanCompleteIfOpenNeverCompletesOverlapping() { Flowable.range(1, 50) .zipWith(Flowable.interval(5, TimeUnit.MILLISECONDS), new BiFunction<Integer, Long, Integer>() { @Override public Integer apply(Integer integer, Long aLong) { return integer; } }) .buffer(Flowable.interval(0, 100, TimeUnit.MILLISECONDS), new Function<Long, Publisher<?>>() { @Override public Publisher<?> apply(Long a) { return Flowable.just(a).delay(200, TimeUnit.MILLISECONDS); } }) .to(TestHelper.<List<Integer>>testConsumer()) .assertSubscribed() .awaitDone(3, TimeUnit.SECONDS) .assertComplete(); } @Test public void openClosemainError() { Flowable.error(new TestException()) .buffer(Flowable.never(), Functions.justFunction(Flowable.never())) .test() .assertFailure(TestException.class); } @Test public void openClosebadSource() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { new Flowable<Object>() { @Override protected void subscribeActual(Subscriber<? super Object> s) { BooleanSubscription bs1 = new BooleanSubscription(); BooleanSubscription bs2 = new BooleanSubscription(); s.onSubscribe(bs1); assertFalse(bs1.isCancelled()); assertFalse(bs2.isCancelled()); s.onSubscribe(bs2); assertFalse(bs1.isCancelled()); assertTrue(bs2.isCancelled()); s.onError(new IOException()); s.onComplete(); s.onNext(1); s.onError(new TestException()); } } .buffer(Flowable.never(), Functions.justFunction(Flowable.never())) .test() .assertFailure(IOException.class); TestHelper.assertError(errors, 0, ProtocolViolationException.class); TestHelper.assertUndeliverable(errors, 1, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void openCloseOpenCompletes() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> openIndicator = PublishProcessor.create(); PublishProcessor<Integer> closeIndicator = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(); openIndicator.onNext(1); assertTrue(closeIndicator.hasSubscribers()); openIndicator.onComplete(); assertTrue(source.hasSubscribers()); assertTrue(closeIndicator.hasSubscribers()); closeIndicator.onComplete(); assertFalse(source.hasSubscribers()); ts.assertResult(Collections.<Integer>emptyList()); } @Test public void openCloseOpenCompletesNoBuffers() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> openIndicator = PublishProcessor.create(); PublishProcessor<Integer> closeIndicator = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(); openIndicator.onNext(1); assertTrue(closeIndicator.hasSubscribers()); closeIndicator.onComplete(); assertTrue(source.hasSubscribers()); assertTrue(openIndicator.hasSubscribers()); openIndicator.onComplete(); assertFalse(source.hasSubscribers()); ts.assertResult(Collections.<Integer>emptyList()); } @Test public void openCloseTake() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> openIndicator = PublishProcessor.create(); PublishProcessor<Integer> closeIndicator = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .take(1) .test(2); openIndicator.onNext(1); closeIndicator.onComplete(); assertFalse(source.hasSubscribers()); assertFalse(openIndicator.hasSubscribers()); assertFalse(closeIndicator.hasSubscribers()); ts.assertResult(Collections.<Integer>emptyList()); } @Test public void openCloseEmptyBackpressure() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> openIndicator = PublishProcessor.create(); PublishProcessor<Integer> closeIndicator = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(0); source.onComplete(); assertFalse(openIndicator.hasSubscribers()); assertFalse(closeIndicator.hasSubscribers()); ts.assertResult(); } @Test public void openCloseErrorBackpressure() { PublishProcessor<Integer> source = PublishProcessor.create(); PublishProcessor<Integer> openIndicator = PublishProcessor.create(); PublishProcessor<Integer> closeIndicator = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = source .buffer(openIndicator, Functions.justFunction(closeIndicator)) .test(0); source.onError(new TestException()); assertFalse(openIndicator.hasSubscribers()); assertFalse(closeIndicator.hasSubscribers()); ts.assertFailure(TestException.class); } @Test public void openCloseBadOpen() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { Flowable.never() .buffer(new Flowable<Object>() { @Override protected void subscribeActual(Subscriber<? super Object> s) { assertFalse(((Disposable)s).isDisposed()); BooleanSubscription bs1 = new BooleanSubscription(); BooleanSubscription bs2 = new BooleanSubscription(); s.onSubscribe(bs1); assertFalse(bs1.isCancelled()); assertFalse(bs2.isCancelled()); s.onSubscribe(bs2); assertFalse(bs1.isCancelled()); assertTrue(bs2.isCancelled()); s.onError(new IOException()); assertTrue(((Disposable)s).isDisposed()); s.onComplete(); s.onNext(1); s.onError(new TestException()); } }, Functions.justFunction(Flowable.never())) .test() .assertFailure(IOException.class); TestHelper.assertError(errors, 0, ProtocolViolationException.class); TestHelper.assertUndeliverable(errors, 1, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void openCloseBadClose() { List<Throwable> errors = TestHelper.trackPluginErrors(); try { Flowable.never() .buffer(Flowable.just(1).concatWith(Flowable.<Integer>never()), Functions.justFunction(new Flowable<Object>() { @Override protected void subscribeActual(Subscriber<? super Object> s) { assertFalse(((Disposable)s).isDisposed()); BooleanSubscription bs1 = new BooleanSubscription(); BooleanSubscription bs2 = new BooleanSubscription(); s.onSubscribe(bs1); assertFalse(bs1.isCancelled()); assertFalse(bs2.isCancelled()); s.onSubscribe(bs2); assertFalse(bs1.isCancelled()); assertTrue(bs2.isCancelled()); s.onError(new IOException()); assertTrue(((Disposable)s).isDisposed()); s.onComplete(); s.onNext(1); s.onError(new TestException()); } })) .test() .assertFailure(IOException.class); TestHelper.assertError(errors, 0, ProtocolViolationException.class); TestHelper.assertUndeliverable(errors, 1, TestException.class); } finally { RxJavaPlugins.reset(); } } @Test public void bufferExactBoundaryDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable( new Function<Flowable<Object>, Flowable<List<Object>>>() { @Override public Flowable<List<Object>> apply(Flowable<Object> f) throws Exception { return f.buffer(Flowable.never()); } } ); } @Test public void bufferExactBoundarySecondBufferCrash() { PublishProcessor<Integer> pp = PublishProcessor.create(); PublishProcessor<Integer> b = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = pp.buffer(b, new Supplier<List<Integer>>() { int calls; @Override public List<Integer> get() throws Exception { if (++calls == 2) { throw new TestException(); } return new ArrayList<>(); } }).test(); b.onNext(1); ts.assertFailure(TestException.class); } @Test public void bufferExactBoundaryBadSource() { Flowable<Integer> pp = new Flowable<Integer>() { @Override protected void subscribeActual(Subscriber<? super Integer> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); subscriber.onComplete(); subscriber.onNext(1); subscriber.onComplete(); } }; final AtomicReference<Subscriber<? super Integer>> ref = new AtomicReference<>(); Flowable<Integer> b = new Flowable<Integer>() { @Override protected void subscribeActual(Subscriber<? super Integer> subscriber) { subscriber.onSubscribe(new BooleanSubscription()); ref.set(subscriber); } }; TestSubscriber<List<Integer>> ts = pp.buffer(b).test(); ref.get().onNext(1); ts.assertResult(Collections.<Integer>emptyList()); } @Test public void bufferExactBoundaryCancelUpfront() { PublishProcessor<Integer> pp = PublishProcessor.create(); PublishProcessor<Integer> b = PublishProcessor.create(); pp.buffer(b).test(0L, true) .assertEmpty(); assertFalse(pp.hasSubscribers()); assertFalse(b.hasSubscribers()); } @Test public void bufferExactBoundaryDisposed() { Flowable<Integer> pp = new Flowable<Integer>() { @Override protected void subscribeActual(Subscriber<? super Integer> s) { s.onSubscribe(new BooleanSubscription()); Disposable d = (Disposable)s; assertFalse(d.isDisposed()); d.dispose(); assertTrue(d.isDisposed()); } }; PublishProcessor<Integer> b = PublishProcessor.create(); pp.buffer(b).test(); } @Test public void timedDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<List<Object>>>() { @Override public Publisher<List<Object>> apply(Flowable<Object> f) throws Exception { return f.buffer(1, TimeUnit.SECONDS); } }); } @Test public void timedCancelledUpfront() { TestScheduler sch = new TestScheduler(); TestSubscriber<List<Object>> ts = Flowable.never() .buffer(1, TimeUnit.MILLISECONDS, sch) .test(1L, true); sch.advanceTimeBy(1, TimeUnit.MILLISECONDS); ts.assertEmpty(); } @Test public void timedInternalState() { TestScheduler sch = new TestScheduler(); TestSubscriber<List<Integer>> ts = new TestSubscriber<>(); BufferExactUnboundedSubscriber<Integer, List<Integer>> sub = new BufferExactUnboundedSubscriber<>( ts, Functions.justSupplier((List<Integer>) new ArrayList<Integer>()), 1, TimeUnit.SECONDS, sch); sub.onSubscribe(new BooleanSubscription()); assertFalse(sub.isDisposed()); sub.onError(new TestException()); sub.onNext(1); sub.onComplete(); sub.run(); sub.dispose(); assertTrue(sub.isDisposed()); sub.buffer = new ArrayList<>(); sub.enter(); sub.onComplete(); } @Test public void timedSkipDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<List<Object>>>() { @Override public Publisher<List<Object>> apply(Flowable<Object> f) throws Exception { return f.buffer(2, 1, TimeUnit.SECONDS); } }); } @Test public void timedSizedDoubleOnSubscribe() { TestHelper.checkDoubleOnSubscribeFlowable(new Function<Flowable<Object>, Publisher<List<Object>>>() { @Override public Publisher<List<Object>> apply(Flowable<Object> f) throws Exception { return f.buffer(2, TimeUnit.SECONDS, 10); } }); } @Test public void timedSkipInternalState() { TestScheduler sch = new TestScheduler(); TestSubscriber<List<Integer>> ts = new TestSubscriber<>(); BufferSkipBoundedSubscriber<Integer, List<Integer>> sub = new BufferSkipBoundedSubscriber<>( ts, Functions.justSupplier((List<Integer>) new ArrayList<Integer>()), 1, 1, TimeUnit.SECONDS, sch.createWorker()); sub.onSubscribe(new BooleanSubscription()); sub.enter(); sub.onComplete(); sub.cancel(); sub.run(); } @Test public void timedSkipCancelWhenSecondBuffer() { TestScheduler sch = new TestScheduler(); final TestSubscriber<List<Integer>> ts = new TestSubscriber<>(); BufferSkipBoundedSubscriber<Integer, List<Integer>> sub = new BufferSkipBoundedSubscriber<>( ts, new Supplier<List<Integer>>() { int calls; @Override public List<Integer> get() throws Exception { if (++calls == 2) { ts.cancel(); } return new ArrayList<>(); } }, 1, 1, TimeUnit.SECONDS, sch.createWorker()); sub.onSubscribe(new BooleanSubscription()); sub.run(); assertTrue(ts.isCancelled()); } @Test public void timedSizeBufferAlreadyCleared() { TestScheduler sch = new TestScheduler(); TestSubscriber<List<Integer>> ts = new TestSubscriber<>(); BufferExactBoundedSubscriber<Integer, List<Integer>> sub = new BufferExactBoundedSubscriber<>( ts, Functions.justSupplier((List<Integer>) new ArrayList<Integer>()), 1, TimeUnit.SECONDS, 1, false, sch.createWorker()) ; BooleanSubscription bs = new BooleanSubscription(); sub.onSubscribe(bs); sub.producerIndex++; sub.run(); assertFalse(sub.isDisposed()); sub.enter(); sub.onComplete(); assertTrue(sub.isDisposed()); sub.run(); } @Test public void bufferExactFailingSupplier() { Flowable.empty() .buffer(1, TimeUnit.SECONDS, Schedulers.computation(), 10, new Supplier<List<Object>>() { @Override public List<Object> get() throws Exception { throw new TestException(); } }, false) .test() .awaitDone(1, TimeUnit.SECONDS) .assertFailure(TestException.class) ; } @Test public void exactBadRequest() { TestHelper.assertBadRequestReported(Flowable.never().buffer(1)); } @Test public void skipBadRequest() { TestHelper.assertBadRequestReported(Flowable.never().buffer(1, 2)); } @Test public void overlapBadRequest() { TestHelper.assertBadRequestReported(Flowable.never().buffer(2, 1)); } @Test public void bufferExactBoundedOnNextAfterDispose() { TestSubscriber<Object> ts = new TestSubscriber<>(); Flowable.unsafeCreate(s -> { s.onSubscribe(new BooleanSubscription()); ts.cancel(); s.onNext(1); }) .buffer(1, TimeUnit.MINUTES, 2) .subscribe(ts); ts.assertEmpty(); } @Test public void boundaryCloseCompleteRace() { for (int i = 0; i < TestHelper.RACE_DEFAULT_LOOPS; i++) { BehaviorProcessor<Integer> bp = BehaviorProcessor.createDefault(1); PublishProcessor<Integer> pp = PublishProcessor.create(); TestSubscriber<List<Integer>> ts = bp .buffer(BehaviorProcessor.createDefault(0), v -> pp) .test(); TestHelper.race( () -> bp.onComplete(), () -> pp.onComplete() ); ts.assertResult(Arrays.asList(1)); } } @Test public void doubleOnSubscribeStartEnd() { TestHelper.checkDoubleOnSubscribeFlowable(f -> f.buffer(Flowable.never(), v -> Flowable.never())); } @Test public void cancel() { TestHelper.checkDisposed(Flowable.never().buffer(Flowable.never(), v -> Flowable.never())); } @Test public void startEndCancelAfterOneBuffer() { BehaviorProcessor.createDefault(1) .buffer(BehaviorProcessor.createDefault(2), v -> Flowable.just(1)) .takeUntil(v -> true) .test() .assertResult(Arrays.asList()); } @Test public void startEndCompleteOnBoundary() { Flowable.empty() .buffer(Flowable.never(), v -> Flowable.just(1)) .take(1) .test() .assertResult(); } @Test public void startEndBackpressure() { BehaviorProcessor.createDefault(1) .buffer(BehaviorProcessor.createDefault(2), v -> Flowable.just(1)) .test(1L) .assertValuesOnly(Arrays.asList()); } @Test public void startEndBackpressureMoreWork() { PublishProcessor<Integer> bp = PublishProcessor.create(); PublishProcessor<Integer> pp = PublishProcessor.create(); AtomicInteger counter = new AtomicInteger(); TestSubscriber<List<Integer>> ts = bp .buffer(pp, v -> Flowable.just(1)) .doOnNext(v -> { if (counter.getAndIncrement() == 0) { pp.onNext(2); pp.onComplete(); } }) .test(1L); pp.onNext(1); bp.onNext(1); ts .assertValuesOnly(Arrays.asList()); } }
LongTimeAction
java
elastic__elasticsearch
x-pack/plugin/esql/src/main/generated/org/elasticsearch/xpack/esql/expression/predicate/operator/comparison/LessThanOrEqualIntsEvaluator.java
{ "start": 1204, "end": 5016 }
class ____ implements EvalOperator.ExpressionEvaluator { private static final long BASE_RAM_BYTES_USED = RamUsageEstimator.shallowSizeOfInstance(LessThanOrEqualIntsEvaluator.class); private final Source source; private final EvalOperator.ExpressionEvaluator lhs; private final EvalOperator.ExpressionEvaluator rhs; private final DriverContext driverContext; private Warnings warnings; public LessThanOrEqualIntsEvaluator(Source source, EvalOperator.ExpressionEvaluator lhs, EvalOperator.ExpressionEvaluator rhs, DriverContext driverContext) { this.source = source; this.lhs = lhs; this.rhs = rhs; this.driverContext = driverContext; } @Override public Block eval(Page page) { try (IntBlock lhsBlock = (IntBlock) lhs.eval(page)) { try (IntBlock rhsBlock = (IntBlock) rhs.eval(page)) { IntVector lhsVector = lhsBlock.asVector(); if (lhsVector == null) { return eval(page.getPositionCount(), lhsBlock, rhsBlock); } IntVector rhsVector = rhsBlock.asVector(); if (rhsVector == null) { return eval(page.getPositionCount(), lhsBlock, rhsBlock); } return eval(page.getPositionCount(), lhsVector, rhsVector).asBlock(); } } } @Override public long baseRamBytesUsed() { long baseRamBytesUsed = BASE_RAM_BYTES_USED; baseRamBytesUsed += lhs.baseRamBytesUsed(); baseRamBytesUsed += rhs.baseRamBytesUsed(); return baseRamBytesUsed; } public BooleanBlock eval(int positionCount, IntBlock lhsBlock, IntBlock rhsBlock) { try(BooleanBlock.Builder result = driverContext.blockFactory().newBooleanBlockBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { switch (lhsBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } switch (rhsBlock.getValueCount(p)) { case 0: result.appendNull(); continue position; case 1: break; default: warnings().registerException(new IllegalArgumentException("single-value function encountered multi-value")); result.appendNull(); continue position; } int lhs = lhsBlock.getInt(lhsBlock.getFirstValueIndex(p)); int rhs = rhsBlock.getInt(rhsBlock.getFirstValueIndex(p)); result.appendBoolean(LessThanOrEqual.processInts(lhs, rhs)); } return result.build(); } } public BooleanVector eval(int positionCount, IntVector lhsVector, IntVector rhsVector) { try(BooleanVector.FixedBuilder result = driverContext.blockFactory().newBooleanVectorFixedBuilder(positionCount)) { position: for (int p = 0; p < positionCount; p++) { int lhs = lhsVector.getInt(p); int rhs = rhsVector.getInt(p); result.appendBoolean(p, LessThanOrEqual.processInts(lhs, rhs)); } return result.build(); } } @Override public String toString() { return "LessThanOrEqualIntsEvaluator[" + "lhs=" + lhs + ", rhs=" + rhs + "]"; } @Override public void close() { Releasables.closeExpectNoException(lhs, rhs); } private Warnings warnings() { if (warnings == null) { this.warnings = Warnings.createWarnings( driverContext.warningsMode(), source.source().getLineNumber(), source.source().getColumnNumber(), source.text() ); } return warnings; } static
LessThanOrEqualIntsEvaluator
java
elastic__elasticsearch
x-pack/plugin/watcher/src/main/java/org/elasticsearch/xpack/watcher/notification/email/Email.java
{ "start": 15010, "end": 18705 }
class ____ extends javax.mail.internet.InternetAddress implements ToXContentFragment { public static final ParseField ADDRESS_NAME_FIELD = new ParseField("name"); public static final ParseField ADDRESS_EMAIL_FIELD = new ParseField("email"); public Address(String address) throws AddressException { super(address); } public Address(String address, String personal) throws UnsupportedEncodingException { super(address, personal, StandardCharsets.UTF_8.name()); } public static Address parse(String field, XContentParser.Token token, XContentParser parser) throws IOException { if (token == XContentParser.Token.VALUE_STRING) { String text = parser.text(); try { return new Email.Address(parser.text()); } catch (AddressException ae) { String msg = "could not parse [" + text + "] in field [" + field + "] as address. address must be RFC822 encoded"; throw new ElasticsearchParseException(msg, ae); } } if (token == XContentParser.Token.START_OBJECT) { String email = null; String name = null; String currentFieldName = null; while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token == XContentParser.Token.FIELD_NAME) { currentFieldName = parser.currentName(); } else if (token == XContentParser.Token.VALUE_STRING) { if (ADDRESS_EMAIL_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { email = parser.text(); } else if (ADDRESS_NAME_FIELD.match(currentFieldName, parser.getDeprecationHandler())) { name = parser.text(); } else { throw new ElasticsearchParseException( "could not parse [" + field + "] object as address. unknown address " + "field [" + currentFieldName + "]" ); } } } if (email == null) { String msg = "could not parse [" + field + "] as address. address object must define an [email] field"; throw new ElasticsearchParseException(msg); } try { return name != null ? new Email.Address(email, name) : new Email.Address(email); } catch (AddressException ae) { throw new ElasticsearchParseException("could not parse [" + field + "] as address", ae); } } throw new ElasticsearchParseException( "could not parse [{}] as address. address must either be a string (RFC822 encoded) or " + "an object specifying the address [name] and [email]", field ); } public static Address parse(Settings settings, String name) { String value = settings.get(name); try { return value != null ? new Address(value) : null; } catch (AddressException ae) { throw new IllegalArgumentException("[" + value + "] is not a valid RFC822 email address", ae); } } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { return builder.value(toString()); } } public static
Address
java
spring-projects__spring-boot
module/spring-boot-jackson2/src/test/java/org/springframework/boot/jackson2/JsonComponentModuleTests.java
{ "start": 8948, "end": 9033 }
class ____ extends NameAndAgeJsonComponent.Serializer { } static
AbstractSerializer
java
junit-team__junit5
jupiter-tests/src/test/java/org/junit/jupiter/engine/descriptor/subpackage/Class1WithTestCases.java
{ "start": 437, "end": 495 }
class ____ { @Test void test1() { } }
Class1WithTestCases
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/InstantiationException.java
{ "start": 1418, "end": 1764 }
class ____ are unable to instantiate */ public Class<?> getUninstantiatableClass() { return clazz; } @Override public String getMessage() { final String message = super.getMessage() + " '" + clazz.getName() + "'"; final Throwable cause = getCause(); return cause != null ? message + " due to: " + cause.getMessage() : message; } }
we
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/collection/list/ListIndexReferenceFromListElementTest.java
{ "start": 3194, "end": 3551 }
class ____ { @Id @GeneratedValue public Integer id; public String name; @ManyToOne @JoinColumn public LocalOrder order; @Column(insertable = false, updatable = false) public int position; public LocalLineItem() { } public LocalLineItem(String name, LocalOrder order) { this.name = name; this.order = order; } } }
LocalLineItem
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/indexcoll/eager/Atmosphere.java
{ "start": 1106, "end": 2827 }
enum ____ { LOW, HIGH } @Id @GeneratedValue public Integer id; @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @MapKeyColumn(name = "gas_name") public Map<String, Gas> gases = new HashMap<>(); @MapKeyTemporal(TemporalType.DATE) @ElementCollection(fetch = FetchType.EAGER) @MapKeyColumn(nullable = false) public Map<Date, String> colorPerDate = new HashMap<>(); @ElementCollection(fetch = FetchType.EAGER) @MapKeyEnumerated(EnumType.STRING) @MapKeyColumn(nullable = false) public Map<Level, String> colorPerLevel = new HashMap<>(); @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @MapKeyJoinColumn(name = "gas_id") @JoinTable(name = "Gas_per_key") public Map<GasKey, Gas> gasesPerKey = new HashMap<GasKey, Gas>(); @ElementCollection(fetch = FetchType.EAGER) @Column(name = "composition_rate") @MapKeyJoinColumns({@MapKeyJoinColumn(name = "gas_id")}) //use @MapKeyJoinColumns explicitly for tests @JoinTable(name = "Composition", joinColumns = @JoinColumn(name = "atmosphere_id")) public Map<Gas, Double> composition = new HashMap<>(); //use default JPA 2 column name for map key @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @MapKeyColumn @JoinTable(name = "Atm_Gas_Def") public Map<String, Gas> gasesDef = new HashMap<>(); //use default HAN legacy column name for map key @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @MapKeyColumn @JoinTable(name = "Atm_Gas_DefLeg") public Map<String, Gas> gasesDefLeg = new HashMap<>(); @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER) @MapKeyJoinColumn @JoinTable(name = "Gas_p_key_def") public Map<GasKey, Gas> gasesPerKeyDef = new HashMap<>(); }
Level
java
apache__hadoop
hadoop-mapreduce-project/hadoop-mapreduce-client/hadoop-mapreduce-client-app/src/test/java/org/apache/hadoop/mapreduce/v2/app/MockAppContext.java
{ "start": 1433, "end": 4346 }
class ____ implements AppContext { final ApplicationAttemptId appAttemptID; final ApplicationId appID; final String user = MockJobs.newUserName(); final Map<JobId, Job> jobs; final long startTime = System.currentTimeMillis(); Set<String> blacklistedNodes; String queue; public MockAppContext(int appid) { appID = MockJobs.newAppID(appid); appAttemptID = ApplicationAttemptId.newInstance(appID, 0); jobs = null; } public MockAppContext(int appid, int numTasks, int numAttempts, Path confPath) { appID = MockJobs.newAppID(appid); appAttemptID = ApplicationAttemptId.newInstance(appID, 0); Map<JobId, Job> map = Maps.newHashMap(); Job job = MockJobs.newJob(appID, 0, numTasks, numAttempts, confPath); map.put(job.getID(), job); jobs = map; } public MockAppContext(int appid, int numJobs, int numTasks, int numAttempts) { this(appid, numJobs, numTasks, numAttempts, false); } public MockAppContext(int appid, int numJobs, int numTasks, int numAttempts, boolean hasFailedTasks) { appID = MockJobs.newAppID(appid); appAttemptID = ApplicationAttemptId.newInstance(appID, 0); jobs = MockJobs.newJobs(appID, numJobs, numTasks, numAttempts, hasFailedTasks); } @Override public ApplicationAttemptId getApplicationAttemptId() { return appAttemptID; } @Override public ApplicationId getApplicationID() { return appID; } @Override public CharSequence getUser() { return user; } @Override public Job getJob(JobId jobID) { return jobs.get(jobID); } @Override public Map<JobId, Job> getAllJobs() { return jobs; // OK } @Override public EventHandler<Event> getEventHandler() { return new MockEventHandler(); } @Override public Clock getClock() { return null; } @Override public String getApplicationName() { return "TestApp"; } @Override public long getStartTime() { return startTime; } @Override public ClusterInfo getClusterInfo() { return null; } @Override public Set<String> getBlacklistedNodes() { return blacklistedNodes; } public void setBlacklistedNodes(Set<String> blacklistedNodes) { this.blacklistedNodes = blacklistedNodes; } public ClientToAMTokenSecretManager getClientToAMTokenSecretManager() { // Not implemented return null; } @Override public boolean isLastAMRetry() { return false; } @Override public boolean hasSuccessfullyUnregistered() { // bogus - Not Required return true; } @Override public String getNMHostname() { // bogus - Not Required return null; } @Override public TaskAttemptFinishingMonitor getTaskAttemptFinishingMonitor() { return null; } @Override public String getHistoryUrl() { return null; } @Override public void setHistoryUrl(String historyUrl) { return; } }
MockAppContext
java
netty__netty
handler/src/main/java/io/netty/handler/ipfilter/IpFilterRule.java
{ "start": 730, "end": 772 }
interface ____ create new rules. */ public
to
java
junit-team__junit5
platform-tests/src/test/java/org/junit/platform/suite/engine/testcases/TaggedTestTestCase.java
{ "start": 444, "end": 524 }
class ____ { @Test @Tag("excluded") public void test() { } }
TaggedTestTestCase
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/streaming/runtime/tasks/StreamIterationTail.java
{ "start": 4685, "end": 6365 }
class ____<IN> implements Output<StreamRecord<IN>> { @SuppressWarnings("NonSerializableFieldInSerializableClass") private final BlockingQueue<StreamRecord<IN>> dataChannel; private final long iterationWaitTime; private final boolean shouldWait; IterationTailOutput(BlockingQueue<StreamRecord<IN>> dataChannel, long iterationWaitTime) { this.dataChannel = dataChannel; this.iterationWaitTime = iterationWaitTime; this.shouldWait = iterationWaitTime > 0; } @Override public void emitWatermark(Watermark mark) {} @Override public void emitWatermarkStatus(WatermarkStatus watermarkStatus) {} @Override public void emitLatencyMarker(LatencyMarker latencyMarker) {} @Override public void emitRecordAttributes(RecordAttributes recordAttributes) {} @Override public void emitWatermark(WatermarkEvent watermark) {} @Override public void collect(StreamRecord<IN> record) { try { if (shouldWait) { dataChannel.offer(record, iterationWaitTime, TimeUnit.MILLISECONDS); } else { dataChannel.put(record); } } catch (InterruptedException e) { throw new RuntimeException(e); } } @Override public <X> void collect(OutputTag<X> outputTag, StreamRecord<X> record) { throw new UnsupportedOperationException("Side outputs not used in iteration tail"); } @Override public void close() {} } }
IterationTailOutput
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/StateTransformationFunction.java
{ "start": 1328, "end": 1940 }
interface ____<S, T> { /** * Binary function that applies a given value to the given old state to compute the new state. * * @param previousState the previous state that is the basis for the transformation. * @param value the value that the implementation applies to the old state to obtain the new * state. * @return the new state, computed by applying the given value on the given old state. * @throws Exception if something goes wrong in applying the transformation function. */ S apply(S previousState, T value) throws Exception; }
StateTransformationFunction
java
apache__logging-log4j2
log4j-perf-test/src/main/java/org/apache/logging/log4j/perf/jmh/AnnotationVsMarkerInterface.java
{ "start": 1495, "end": 1734 }
interface ____ annotation. */ @OutputTimeUnit(TimeUnit.NANOSECONDS) @Warmup(iterations = 5, time = 1, timeUnit = TimeUnit.SECONDS) @Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS) @Fork(1) @State(Scope.Benchmark) public
vs
java
elastic__elasticsearch
x-pack/plugin/core/src/test/java/org/elasticsearch/xpack/core/ml/dataframe/evaluation/classification/PainlessScriptsTests.java
{ "start": 467, "end": 771 }
class ____ extends ESTestCase { public void testBuildIsEqualScript() { Script script = PainlessScripts.buildIsEqualScript("act", "pred"); assertThat(script.getIdOrCode(), equalTo("String.valueOf(doc['act'].value).equals(String.valueOf(doc['pred'].value))")); } }
PainlessScriptsTests