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
spring-projects__spring-framework
spring-web/src/main/java/org/springframework/web/filter/UrlHandlerFilter.java
{ "start": 6109, "end": 7283 }
class ____ implements TrailingSlashSpec { private final List<PathPattern> pathPatterns; private @Nullable Consumer<HttpServletRequest> interceptor; private DefaultTrailingSlashSpec(String[] patterns) { this.pathPatterns = Arrays.stream(patterns) .map(pattern -> pattern.endsWith("**") || pattern.endsWith("/") ? pattern : pattern + "/") .map(patternParser::parse) .toList(); } @Override public TrailingSlashSpec intercept(Consumer<HttpServletRequest> consumer) { this.interceptor = (this.interceptor != null ? this.interceptor.andThen(consumer) : consumer); return this; } @Override public Builder redirect(HttpStatus status) { Handler handler = new RedirectTrailingSlashHandler(status, this.interceptor); return DefaultBuilder.this.addHandler(this.pathPatterns, handler); } @Override public Builder wrapRequest() { Handler handler = new RequestWrappingTrailingSlashHandler(this.interceptor); return DefaultBuilder.this.addHandler(this.pathPatterns, handler); } } } /** * Internal handler to encapsulate different ways to handle a request. */ private
DefaultTrailingSlashSpec
java
apache__camel
dsl/camel-componentdsl/src/generated/java/org/apache/camel/builder/component/dsl/Aws2SesComponentBuilderFactory.java
{ "start": 1865, "end": 18371 }
interface ____ extends ComponentBuilder<Ses2Component> { /** * List of comma-separated destination blind carbon copy (bcc) email * address. Can be overridden with 'CamelAwsSesBcc' header. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param bcc the value to set * @return the dsl builder */ default Aws2SesComponentBuilder bcc(java.lang.String bcc) { doSetProperty("bcc", bcc); return this; } /** * List of comma-separated destination carbon copy (cc) email address. * Can be overridden with 'CamelAwsSesCc' header. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param cc the value to set * @return the dsl builder */ default Aws2SesComponentBuilder cc(java.lang.String cc) { doSetProperty("cc", cc); return this; } /** * component configuration. * * The option is a: * &lt;code&gt;org.apache.camel.component.aws2.ses.Ses2Configuration&lt;/code&gt; type. * * Group: producer * * @param configuration the value to set * @return the dsl builder */ default Aws2SesComponentBuilder configuration(org.apache.camel.component.aws2.ses.Ses2Configuration configuration) { doSetProperty("configuration", configuration); return this; } /** * Set the configuration set to send with every request. Override it * with 'CamelAwsSesConfigurationSet' header. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param configurationSet the value to set * @return the dsl builder */ default Aws2SesComponentBuilder configurationSet(java.lang.String configurationSet) { doSetProperty("configurationSet", configurationSet); return this; } /** * Whether the producer should be started lazy (on the first message). * By starting lazy you can use this to allow CamelContext and routes to * startup in situations where a producer may otherwise fail during * starting and cause the route to fail being started. By deferring this * startup to be lazy then the startup failure can be handled during * routing messages via Camel's routing error handlers. Beware that when * the first message is processed then creating and starting the * producer may take a little time and prolong the total processing time * of the processing. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param lazyStartProducer the value to set * @return the dsl builder */ default Aws2SesComponentBuilder lazyStartProducer(boolean lazyStartProducer) { doSetProperty("lazyStartProducer", lazyStartProducer); return this; } /** * Set the need for overriding the endpoint. This option needs to be * used in combination with the uriEndpointOverride option. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: producer * * @param overrideEndpoint the value to set * @return the dsl builder */ default Aws2SesComponentBuilder overrideEndpoint(boolean overrideEndpoint) { doSetProperty("overrideEndpoint", overrideEndpoint); return this; } /** * The region in which SES client needs to work. When using this * parameter, the configuration will expect the lowercase name of the * region (for example, ap-east-1) You'll need to use the name * Region.EU_WEST_1.id(). * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param region the value to set * @return the dsl builder */ default Aws2SesComponentBuilder region(java.lang.String region) { doSetProperty("region", region); return this; } /** * List of comma separated reply-to email address(es) for the message, * override it using 'CamelAwsSesReplyToAddresses' header. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param replyToAddresses the value to set * @return the dsl builder */ default Aws2SesComponentBuilder replyToAddresses(java.lang.String replyToAddresses) { doSetProperty("replyToAddresses", replyToAddresses); return this; } /** * The email address to which bounce notifications are to be forwarded, * override it using 'CamelAwsSesReturnPath' header. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param returnPath the value to set * @return the dsl builder */ default Aws2SesComponentBuilder returnPath(java.lang.String returnPath) { doSetProperty("returnPath", returnPath); return this; } /** * The subject which is used if the message header 'CamelAwsSesSubject' * is not present. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param subject the value to set * @return the dsl builder */ default Aws2SesComponentBuilder subject(java.lang.String subject) { doSetProperty("subject", subject); return this; } /** * List of comma separated destination email address. Can be overridden * with 'CamelAwsSesTo' header. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param to the value to set * @return the dsl builder */ default Aws2SesComponentBuilder to(java.lang.String to) { doSetProperty("to", to); return this; } /** * Set the overriding uri endpoint. This option needs to be used in * combination with overrideEndpoint option. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: producer * * @param uriEndpointOverride the value to set * @return the dsl builder */ default Aws2SesComponentBuilder uriEndpointOverride(java.lang.String uriEndpointOverride) { doSetProperty("uriEndpointOverride", uriEndpointOverride); return this; } /** * To use the AmazonSimpleEmailService as the client. * * The option is a: * &lt;code&gt;software.amazon.awssdk.services.ses.SesClient&lt;/code&gt; type. * * Group: advanced * * @param amazonSESClient the value to set * @return the dsl builder */ default Aws2SesComponentBuilder amazonSESClient(software.amazon.awssdk.services.ses.SesClient amazonSESClient) { doSetProperty("amazonSESClient", amazonSESClient); return this; } /** * Whether autowiring is enabled. This is used for automatic autowiring * options (the option must be marked as autowired) by looking up in the * registry to find if there is a single instance of matching type, * which then gets configured on the component. This can be used for * automatic configuring JDBC data sources, JMS connection factories, * AWS Clients, etc. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: advanced * * @param autowiredEnabled the value to set * @return the dsl builder */ default Aws2SesComponentBuilder autowiredEnabled(boolean autowiredEnabled) { doSetProperty("autowiredEnabled", autowiredEnabled); return this; } /** * Used for enabling or disabling all consumer based health checks from * this component. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: health * * @param healthCheckConsumerEnabled the value to set * @return the dsl builder */ default Aws2SesComponentBuilder healthCheckConsumerEnabled(boolean healthCheckConsumerEnabled) { doSetProperty("healthCheckConsumerEnabled", healthCheckConsumerEnabled); return this; } /** * Used for enabling or disabling all producer based health checks from * this component. Notice: Camel has by default disabled all producer * based health-checks. You can turn on producer checks globally by * setting camel.health.producersEnabled=true. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: true * Group: health * * @param healthCheckProducerEnabled the value to set * @return the dsl builder */ default Aws2SesComponentBuilder healthCheckProducerEnabled(boolean healthCheckProducerEnabled) { doSetProperty("healthCheckProducerEnabled", healthCheckProducerEnabled); return this; } /** * To define a proxy host when instantiating the SES client. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: proxy * * @param proxyHost the value to set * @return the dsl builder */ default Aws2SesComponentBuilder proxyHost(java.lang.String proxyHost) { doSetProperty("proxyHost", proxyHost); return this; } /** * To define a proxy port when instantiating the SES client. * * The option is a: &lt;code&gt;java.lang.Integer&lt;/code&gt; type. * * Group: proxy * * @param proxyPort the value to set * @return the dsl builder */ default Aws2SesComponentBuilder proxyPort(java.lang.Integer proxyPort) { doSetProperty("proxyPort", proxyPort); return this; } /** * To define a proxy protocol when instantiating the SES client. * * The option is a: * &lt;code&gt;software.amazon.awssdk.core.Protocol&lt;/code&gt; type. * * Default: HTTPS * Group: proxy * * @param proxyProtocol the value to set * @return the dsl builder */ default Aws2SesComponentBuilder proxyProtocol(software.amazon.awssdk.core.Protocol proxyProtocol) { doSetProperty("proxyProtocol", proxyProtocol); return this; } /** * Amazon AWS Access Key. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param accessKey the value to set * @return the dsl builder */ default Aws2SesComponentBuilder accessKey(java.lang.String accessKey) { doSetProperty("accessKey", accessKey); return this; } /** * If using a profile credentials provider, this parameter will set the * profile name. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param profileCredentialsName the value to set * @return the dsl builder */ default Aws2SesComponentBuilder profileCredentialsName(java.lang.String profileCredentialsName) { doSetProperty("profileCredentialsName", profileCredentialsName); return this; } /** * Amazon AWS Secret Key. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param secretKey the value to set * @return the dsl builder */ default Aws2SesComponentBuilder secretKey(java.lang.String secretKey) { doSetProperty("secretKey", secretKey); return this; } /** * Amazon AWS Session Token used when the user needs to assume an IAM * role. * * The option is a: &lt;code&gt;java.lang.String&lt;/code&gt; type. * * Group: security * * @param sessionToken the value to set * @return the dsl builder */ default Aws2SesComponentBuilder sessionToken(java.lang.String sessionToken) { doSetProperty("sessionToken", sessionToken); return this; } /** * If we want to trust all certificates in case of overriding the * endpoint. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param trustAllCertificates the value to set * @return the dsl builder */ default Aws2SesComponentBuilder trustAllCertificates(boolean trustAllCertificates) { doSetProperty("trustAllCertificates", trustAllCertificates); return this; } /** * Set whether the Ses client should expect to load credentials through * a default credentials provider or to expect static credentials to be * passed in. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useDefaultCredentialsProvider the value to set * @return the dsl builder */ default Aws2SesComponentBuilder useDefaultCredentialsProvider(boolean useDefaultCredentialsProvider) { doSetProperty("useDefaultCredentialsProvider", useDefaultCredentialsProvider); return this; } /** * Set whether the SES client should expect to load credentials through * a profile credentials provider. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useProfileCredentialsProvider the value to set * @return the dsl builder */ default Aws2SesComponentBuilder useProfileCredentialsProvider(boolean useProfileCredentialsProvider) { doSetProperty("useProfileCredentialsProvider", useProfileCredentialsProvider); return this; } /** * Set whether the SES client should expect to use Session Credentials. * This is useful in a situation in which the user needs to assume an * IAM role for doing operations in SES. * * The option is a: &lt;code&gt;boolean&lt;/code&gt; type. * * Default: false * Group: security * * @param useSessionCredentials the value to set * @return the dsl builder */ default Aws2SesComponentBuilder useSessionCredentials(boolean useSessionCredentials) { doSetProperty("useSessionCredentials", useSessionCredentials); return this; } }
Aws2SesComponentBuilder
java
eclipse-vertx__vert.x
vertx-core/src/test/java/io/vertx/tests/eventbus/MessageQueueOnWorkerThreadTest.java
{ "start": 992, "end": 2350 }
class ____ extends VertxTestBase { private Vertx vertx; @Override public void setUp() throws Exception { super.setUp(); CustomNodeSelector selector = new CustomNodeSelector(); VertxBootstrapImpl factory = new VertxBootstrapImpl().init().clusterManager(new FakeClusterManager()).clusterNodeSelector(selector); Future<Vertx> fut = factory.clusteredVertx(); vertx = fut.await(); } @Test public void testWorkerContext() throws Exception { test(true); } @Test public void testExecuteBlocking() throws Exception { test(false); } private void test(boolean worker) throws Exception { int senderInstances = 20, messagesToSend = 100, expected = senderInstances * messagesToSend; waitFor(expected); vertx.eventBus().consumer("foo", msg -> complete()).completion().onComplete(onSuccess(registered -> { DeploymentOptions options = new DeploymentOptions().setThreadingModel(ThreadingModel.WORKER).setInstances(senderInstances); vertx.deployVerticle(() -> new SenderVerticle(worker, messagesToSend), options); })); await(5, SECONDS); } @Override protected void tearDown() throws Exception { try { if (vertx != null) { close(Collections.singletonList(vertx)); } } finally { super.tearDown(); } } private static
MessageQueueOnWorkerThreadTest
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/fetch/subphase/SeqNoPrimaryTermPhase.java
{ "start": 993, "end": 2783 }
class ____ implements FetchSubPhase { @Override public FetchSubPhaseProcessor getProcessor(FetchContext context) { if (context.seqNoAndPrimaryTerm() == false) { return null; } return new FetchSubPhaseProcessor() { NumericDocValues seqNoField = null; NumericDocValues primaryTermField = null; @Override public void setNextReader(LeafReaderContext readerContext) throws IOException { seqNoField = readerContext.reader().getNumericDocValues(SeqNoFieldMapper.NAME); primaryTermField = readerContext.reader().getNumericDocValues(SeqNoFieldMapper.PRIMARY_TERM_NAME); } @Override public StoredFieldsSpec storedFieldsSpec() { return StoredFieldsSpec.NO_REQUIREMENTS; } @Override public void process(HitContext hitContext) throws IOException { int docId = hitContext.docId(); long seqNo = SequenceNumbers.UNASSIGNED_SEQ_NO; long primaryTerm = SequenceNumbers.UNASSIGNED_PRIMARY_TERM; // we have to check the primary term field as it is only assigned for non-nested documents if (primaryTermField != null && primaryTermField.advanceExact(docId)) { boolean found = seqNoField.advanceExact(docId); assert found : "found seq no for " + docId + " but not a primary term"; seqNo = seqNoField.longValue(); primaryTerm = primaryTermField.longValue(); } hitContext.hit().setSeqNo(seqNo); hitContext.hit().setPrimaryTerm(primaryTerm); } }; } }
SeqNoPrimaryTermPhase
java
apache__camel
core/camel-main/src/test/java/org/apache/camel/main/MainBeansTest.java
{ "start": 9654, "end": 9818 }
class ____ extends RouteBuilder { @Override public void configure() { from("direct:start").to("mock:foo"); } } }
MyRouteBuilder
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/MonoCacheInvalidateIf.java
{ "start": 2012, "end": 5229 }
class ____<T> implements State<T> { @Nullable T value; ValueState(T value) { this.value = value; } @Override public @Nullable T get() { return value; } @Override public void clear() { this.value = null; } } /** * Singleton implementation of an empty {@link State}, to represent initial state * pre-subscription, when no caching has been requested. */ static final State<?> EMPTY_STATE = new State<Object>() { @Override public @Nullable Object get() { return null; } @Override public void clear() { //NO-OP } }; final Predicate<? super T> shouldInvalidatePredicate; volatile State<T> state; @SuppressWarnings("rawtypes") static final AtomicReferenceFieldUpdater<MonoCacheInvalidateIf, State> STATE = AtomicReferenceFieldUpdater.newUpdater(MonoCacheInvalidateIf.class, State.class, "state"); MonoCacheInvalidateIf(Mono<T> source, Predicate<? super T> invalidationPredicate) { super(source); this.shouldInvalidatePredicate = Objects.requireNonNull(invalidationPredicate, "invalidationPredicate"); @SuppressWarnings("unchecked") State<T> state = (State<T>) EMPTY_STATE; this.state = state; } @Override public @Nullable CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super T> actual) { CacheMonoSubscriber<T> inner = new CacheMonoSubscriber<>(actual); //important: onSubscribe should be deferred until we're sure we're in the Coordinator case OR the cached value passes the predicate for(;;) { State<T> state = this.state; if (state == EMPTY_STATE || state instanceof CoordinatorSubscriber) { boolean connectToUpstream = false; CoordinatorSubscriber<T> coordinator; if (state == EMPTY_STATE) { coordinator = new CoordinatorSubscriber<>(this, this.source); if (!STATE.compareAndSet(this, EMPTY_STATE, coordinator)) { continue; } connectToUpstream = true; } else { coordinator = (CoordinatorSubscriber<T>) state; } if (coordinator.add(inner)) { if (inner.isCancelled()) { coordinator.remove(inner); } else { inner.coordinator = coordinator; actual.onSubscribe(inner); } if (connectToUpstream) { coordinator.delayedSubscribe(); } return null; } } else { //state is an actual signal, cached T cached = state.get(); try { boolean invalidated = this.shouldInvalidatePredicate.test(cached); if (invalidated) { if (STATE.compareAndSet(this, state, EMPTY_STATE)) { Operators.onDiscard(cached, actual.currentContext()); } //we CAS but even if it fails we want to loop back continue; } } catch (Throwable error) { if (STATE.compareAndSet(this, state, EMPTY_STATE)) { Operators.onDiscard(cached, actual.currentContext()); Operators.error(actual, error); return null; } } actual.onSubscribe(inner); inner.complete(state.get()); return null; } } } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } static final
ValueState
java
google__guice
extensions/persist/test/com/google/inject/persist/jpa/ClassLevelManagedLocalTransactionsTest.java
{ "start": 7107, "end": 7654 }
class ____ { @Inject Provider<EntityManager> sessionProvider; @Transactional public void runOperationInTxnThrowingUnchecked() { EntityManager session = sessionProvider.get(); assertTrue(session.getTransaction().isActive()); JpaTestEntity entity = new JpaTestEntity(); entity.setText(TRANSIENT_UNIQUE_TEXT); session.persist(entity); throw new IllegalStateException(); } } @Transactional(rollbackOn = IOException.class, ignore = FileNotFoundException.class) public static
TransactionalObject4
java
apache__hadoop
hadoop-tools/hadoop-aliyun/src/test/java/org/apache/hadoop/fs/aliyun/oss/contract/TestAliyunOSSContractMkdir.java
{ "start": 1081, "end": 1277 }
class ____ extends AbstractContractMkdirTest { @Override protected AbstractFSContract createContract(Configuration conf) { return new AliyunOSSContract(conf); } }
TestAliyunOSSContractMkdir
java
google__guava
guava-gwt/src-super/com/google/common/collect/super/com/google/common/collect/ImmutableCollection.java
{ "start": 1176, "end": 3812 }
class ____<E> extends AbstractCollection<E> implements Serializable { static final int SPLITERATOR_CHARACTERISTICS = Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.ORDERED; ImmutableCollection() {} @Override public abstract UnmodifiableIterator<E> iterator(); @Override public boolean contains(@Nullable Object object) { return object != null && super.contains(object); } @Override public final boolean add(E e) { throw new UnsupportedOperationException(); } @Override public final boolean remove(@Nullable Object object) { throw new UnsupportedOperationException(); } @Override public final boolean addAll(Collection<? extends E> newElements) { throw new UnsupportedOperationException(); } @Override public final boolean removeAll(Collection<?> oldElements) { throw new UnsupportedOperationException(); } @Override public final boolean removeIf(Predicate<? super E> predicate) { throw new UnsupportedOperationException(); } @Override public final boolean retainAll(Collection<?> elementsToKeep) { throw new UnsupportedOperationException(); } @Override public final void clear() { throw new UnsupportedOperationException(); } private transient @Nullable ImmutableList<E> asList; public ImmutableList<E> asList() { ImmutableList<E> list = asList; return (list == null) ? (asList = createAsList()) : list; } ImmutableList<E> createAsList() { switch (size()) { case 0: return ImmutableList.of(); case 1: return ImmutableList.of(iterator().next()); default: return new RegularImmutableAsList<E>(this, toArray()); } } /** If this collection is backed by an array of its elements in insertion order, returns it. */ Object @Nullable [] internalArray() { return null; } /** * If this collection is backed by an array of its elements in insertion order, returns the offset * where this collection's elements start. */ int internalArrayStart() { throw new UnsupportedOperationException(); } /** * If this collection is backed by an array of its elements in insertion order, returns the offset * where this collection's elements end. */ int internalArrayEnd() { throw new UnsupportedOperationException(); } static <E> ImmutableCollection<E> unsafeDelegate(Collection<E> delegate) { return new ForwardingImmutableCollection<E>(delegate); } boolean isPartialView() { return false; } /** GWT emulated version of {@link ImmutableCollection.Builder}. */ public abstract static
ImmutableCollection
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/state/DefaultOperatorStateBackend.java
{ "start": 2054, "end": 3411 }
class ____ implements OperatorStateBackend { private static final Logger LOG = LoggerFactory.getLogger(DefaultOperatorStateBackend.class); /** The default namespace for state in cases where no state name is provided */ public static final String DEFAULT_OPERATOR_STATE_NAME = "_default_"; /** Map for all registered operator states. Maps state name -> state */ private final Map<String, PartitionableListState<?>> registeredOperatorStates; /** Map for all registered operator broadcast states. Maps state name -> state */ private final Map<String, BackendWritableBroadcastState<?, ?>> registeredBroadcastStates; /** CloseableRegistry to participate in the tasks lifecycle. */ private final CloseableRegistry closeStreamOnCancelRegistry; /** Default typeSerializer. Only used for the default operator state. */ private final JavaSerializer<Serializable> deprecatedDefaultJavaSerializer = new JavaSerializer<>(); /** The execution configuration. */ private final ExecutionConfig executionConfig; /** * Cache of already accessed states. * * <p>In contrast to {@link #registeredOperatorStates} which may be repopulated with restored * state, this map is always empty at the beginning. * * <p>TODO this map should be moved to a base
DefaultOperatorStateBackend
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/main/generated-src/org/elasticsearch/compute/operator/topn/KeyExtractorForFloat.java
{ "start": 2678, "end": 3248 }
class ____ extends KeyExtractorForFloat { private final FloatBlock block; MinFromAscendingBlock(TopNEncoder encoder, byte nul, byte nonNul, FloatBlock block) { super(encoder, nul, nonNul); this.block = block; } @Override public int writeKey(BreakingBytesRefBuilder key, int position) { if (block.isNull(position)) { return nul(key); } return nonNul(key, block.getFloat(block.getFirstValueIndex(position))); } } static
MinFromAscendingBlock
java
quarkusio__quarkus
extensions/opentelemetry/runtime/src/main/java/io/quarkus/opentelemetry/runtime/exporter/otlp/tracing/RemoveableLateBoundSpanProcessor.java
{ "start": 217, "end": 352 }
class ____ to allow {@link TracerProviderCustomizer} * to easily ignore the configured {@link LateBoundSpanProcessor}. */ public final
is
java
quarkusio__quarkus
extensions/panache/hibernate-orm-rest-data-panache/deployment/src/test/java/io/quarkus/hibernate/orm/rest/data/panache/deployment/openapi/EmptyListItemsResource.java
{ "start": 245, "end": 363 }
interface ____ extends PanacheRepositoryResource<EmptyListItemsRepository, EmptyListItem, Long> { }
EmptyListItemsResource
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/KubernetesServiceAccountsEndpointBuilderFactory.java
{ "start": 15654, "end": 18918 }
interface ____ { /** * Kubernetes Service Account (camel-kubernetes) * Perform operations on Kubernetes Service Accounts. * * Category: container,cloud * Since: 2.17 * Maven coordinates: org.apache.camel:camel-kubernetes * * @return the dsl builder for the headers' name. */ default KubernetesServiceAccountsHeaderNameBuilder kubernetesServiceAccounts() { return KubernetesServiceAccountsHeaderNameBuilder.INSTANCE; } /** * Kubernetes Service Account (camel-kubernetes) * Perform operations on Kubernetes Service Accounts. * * Category: container,cloud * Since: 2.17 * Maven coordinates: org.apache.camel:camel-kubernetes * * Syntax: <code>kubernetes-service-accounts:masterUrl</code> * * Path parameter: masterUrl (required) * URL to a remote Kubernetes API server. This should only be used when * your Camel application is connecting from outside Kubernetes. If you * run your Camel application inside Kubernetes, then you can use local * or client as the URL to tell Camel to run in local mode. If you * connect remotely to Kubernetes, then you may also need some of the * many other configuration options for secured connection with * certificates, etc. * * @param path masterUrl * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder kubernetesServiceAccounts(String path) { return KubernetesServiceAccountsEndpointBuilderFactory.endpointBuilder("kubernetes-service-accounts", path); } /** * Kubernetes Service Account (camel-kubernetes) * Perform operations on Kubernetes Service Accounts. * * Category: container,cloud * Since: 2.17 * Maven coordinates: org.apache.camel:camel-kubernetes * * Syntax: <code>kubernetes-service-accounts:masterUrl</code> * * Path parameter: masterUrl (required) * URL to a remote Kubernetes API server. This should only be used when * your Camel application is connecting from outside Kubernetes. If you * run your Camel application inside Kubernetes, then you can use local * or client as the URL to tell Camel to run in local mode. If you * connect remotely to Kubernetes, then you may also need some of the * many other configuration options for secured connection with * certificates, etc. * * @param componentName to use a custom component name for the endpoint * instead of the default name * @param path masterUrl * @return the dsl builder */ default KubernetesServiceAccountsEndpointBuilder kubernetesServiceAccounts(String componentName, String path) { return KubernetesServiceAccountsEndpointBuilderFactory.endpointBuilder(componentName, path); } } /** * The builder of headers' name for the Kubernetes Service Account component. */ public static
KubernetesServiceAccountsBuilders
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/sequencedmultisetstate/linked/RowSqnInfoSerializer.java
{ "start": 1272, "end": 2824 }
class ____ extends CompositeSerializer<RowSqnInfo> { public RowSqnInfoSerializer() { this(null, LongSerializer.INSTANCE, LongSerializer.INSTANCE); } protected RowSqnInfoSerializer( PrecomputedParameters precomputed, TypeSerializer<?>... fieldSerializers) { super( PrecomputedParameters.precompute( true, true, (TypeSerializer<Object>[]) fieldSerializers), fieldSerializers); } @Override public RowSqnInfo createInstance(Object... values) { return new RowSqnInfo((Long) values[0], (Long) values[1]); } @Override protected void setField(RowSqnInfo sqnInfo, int index, Object fieldValue) { throw new UnsupportedOperationException(); } @Override protected Object getField(RowSqnInfo value, int index) { switch (index) { case 0: return value.firstSqn; case 1: return value.lastSqn; default: throw new IllegalArgumentException("invalid index: " + index); } } @Override protected CompositeSerializer<RowSqnInfo> createSerializerInstance( PrecomputedParameters precomputed, TypeSerializer<?>... originalSerializers) { return new RowSqnInfoSerializer(precomputed, originalSerializers); } @Override public TypeSerializerSnapshot<RowSqnInfo> snapshotConfiguration() { return new RowSqnInfoSerializerSnapshot(this); } public static
RowSqnInfoSerializer
java
redisson__redisson
redisson/src/main/java/org/redisson/client/protocol/convertor/NumberConvertor.java
{ "start": 738, "end": 1808 }
class ____ implements Convertor<Object> { private Class<?> resultClass; public NumberConvertor(Class<?> resultClass) { super(); this.resultClass = resultClass; } @Override public Object convert(Object result) { String res = (String) result; if (resultClass.isAssignableFrom(Long.class)) { Object obj = Long.parseLong(res); return obj; } if (resultClass.isAssignableFrom(Integer.class)) { Object obj = Integer.parseInt(res); return obj; } if (resultClass.isAssignableFrom(Float.class)) { Object obj = Float.parseFloat(res); return obj; } if (resultClass.isAssignableFrom(Double.class)) { Object obj = Double.parseDouble(res); return obj; } if (resultClass.isAssignableFrom(BigDecimal.class)) { Object obj = new BigDecimal(res); return obj; } throw new IllegalStateException("Wrong value type!"); } }
NumberConvertor
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/query/hhh12076/Extension.java
{ "start": 182, "end": 1241 }
class ____ { public static final long serialVersionUID = 1L; private Long _id; private Date _creationDate; private Date _modifiedDate; private Integer _version; private String _type; private Claim _claim; public Extension() { String[] name = this.getClass().getName().split( "\\." ); _type = name[name.length - 1]; } public Long getId() { return _id; } protected void setId(Long id) { _id = id; } public Date getCreationDate() { return _creationDate; } public void setCreationDate(Date creationDate) { _creationDate = creationDate; } public Date getModifiedDate() { return _modifiedDate; } public void setModifiedDate(Date modifiedDate) { _modifiedDate = modifiedDate; } public Integer getVersion() { return _version; } public void setVersion(Integer version) { _version = version; } public Claim getClaim() { return _claim; } public void setClaim(Claim claim) { _claim = claim; } public String getType() { return _type; } public void setType(String type) { _type = type; } }
Extension
java
elastic__elasticsearch
x-pack/plugin/esql/compute/src/test/java/org/elasticsearch/compute/aggregation/CountDistinctBytesRefGroupingAggregatorFunctionTests.java
{ "start": 967, "end": 3012 }
class ____ extends GroupingAggregatorFunctionTestCase { @Override protected AggregatorFunctionSupplier aggregatorFunction() { return new CountDistinctBytesRefAggregatorFunctionSupplier(40000); } @Override protected String expectedDescriptionOfAggregator() { return "count_distinct of bytes"; } @Override protected SourceOperator simpleInput(BlockFactory blockFactory, int size) { return new LongBytesRefTupleBlockSourceOperator( blockFactory, LongStream.range(0, size).mapToObj(l -> Tuple.tuple(randomGroupId(size), new BytesRef(String.valueOf(between(1, 10000))))) ); } @Override protected void assertSimpleGroup(List<Page> input, Block result, int position, Long group) { long distinct = input.stream().flatMap(p -> allBytesRefs(p, group)).distinct().count(); long count = ((LongBlock) result).getLong(position); // HLL is an approximation algorithm and precision depends on the number of values computed and the precision_threshold param // https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-cardinality-aggregation.html // For a number of values close to 10k and precision_threshold=1000, precision should be less than 10% assertThat((double) count, closeTo(distinct, distinct * 0.1)); } @Override protected void assertOutputFromNullOnly(Block b, int position) { assertThat(b.isNull(position), equalTo(false)); assertThat(b.getValueCount(position), equalTo(1)); assertThat(((LongBlock) b).getLong(b.getFirstValueIndex(position)), equalTo(0L)); } @Override protected void assertOutputFromAllFiltered(Block b) { assertThat(b.elementType(), equalTo(ElementType.LONG)); LongVector v = (LongVector) b.asVector(); for (int p = 0; p < v.getPositionCount(); p++) { assertThat(v.getLong(p), equalTo(0L)); } } }
CountDistinctBytesRefGroupingAggregatorFunctionTests
java
quarkusio__quarkus
integration-tests/gradle/src/main/resources/basic-java-library-module/application/src/main/java/org/acme/ApplicationConfigResource.java
{ "start": 233, "end": 555 }
class ____ { @ConfigProperty(name = "quarkus.application.name") String name; @ConfigProperty(name = "quarkus.application.version") String version; @GET @Produces(MediaType.TEXT_PLAIN) public String hello() { return String.format("%s:%s", name, version); } }
ApplicationConfigResource
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/bucket/terms/InternalMappedSignificantTerms.java
{ "start": 1047, "end": 5263 }
class ____< A extends InternalMappedSignificantTerms<A, B>, B extends InternalSignificantTerms.Bucket<B>> extends InternalSignificantTerms<A, B> { protected final DocValueFormat format; protected final long subsetSize; protected final long supersetSize; protected final SignificanceHeuristic significanceHeuristic; protected final List<B> buckets; protected Map<String, B> bucketMap; protected InternalMappedSignificantTerms( String name, int requiredSize, long minDocCount, Map<String, Object> metadata, DocValueFormat format, long subsetSize, long supersetSize, SignificanceHeuristic significanceHeuristic, List<B> buckets ) { super(name, requiredSize, minDocCount, metadata); this.format = format; this.buckets = buckets; this.subsetSize = subsetSize; this.supersetSize = supersetSize; this.significanceHeuristic = significanceHeuristic; } protected InternalMappedSignificantTerms(StreamInput in, Bucket.Reader<B> bucketReader) throws IOException { super(in); format = in.readNamedWriteable(DocValueFormat.class); subsetSize = in.readVLong(); supersetSize = in.readVLong(); significanceHeuristic = in.readNamedWriteable(SignificanceHeuristic.class); buckets = in.readCollectionAsList(stream -> bucketReader.read(stream, format)); } @Override protected final void writeTermTypeInfoTo(StreamOutput out) throws IOException { out.writeNamedWriteable(format); out.writeVLong(subsetSize); out.writeVLong(supersetSize); out.writeNamedWriteable(significanceHeuristic); out.writeCollection(buckets); } @Override @SuppressWarnings({ "rawtypes", "unchecked" }) public Iterator<SignificantTerms.Bucket> iterator() { return (Iterator) buckets.iterator(); } @Override public List<B> getBuckets() { return buckets; } @Override public B getBucketByKey(String term) { if (bucketMap == null) { bucketMap = buckets.stream().collect(Collectors.toMap(InternalSignificantTerms.Bucket::getKeyAsString, Function.identity())); } return bucketMap.get(term); } @Override public long getSubsetSize() { return subsetSize; } @Override public long getSupersetSize() { return supersetSize; } @Override public SignificanceHeuristic getSignificanceHeuristic() { return significanceHeuristic; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null || getClass() != obj.getClass()) return false; if (super.equals(obj) == false) return false; InternalMappedSignificantTerms<?, ?> that = (InternalMappedSignificantTerms<?, ?>) obj; return Objects.equals(format, that.format) && subsetSize == that.subsetSize && supersetSize == that.supersetSize && Objects.equals(significanceHeuristic, that.significanceHeuristic) && Objects.equals(buckets, that.buckets) && Objects.equals(bucketMap, that.bucketMap); } @Override public int hashCode() { return Objects.hash(super.hashCode(), format, subsetSize, supersetSize, significanceHeuristic, buckets, bucketMap); } @Override public XContentBuilder doXContentBody(XContentBuilder builder, Params params) throws IOException { builder.field(CommonFields.DOC_COUNT.getPreferredName(), subsetSize); builder.field(BG_COUNT, supersetSize); builder.startArray(CommonFields.BUCKETS.getPreferredName()); for (Bucket<?> bucket : buckets) { // There is a condition (presumably when only one shard has a bucket?) where reduce is not called // and I end up with buckets that contravene the user's min_doc_count criteria in my reducer if (bucket.subsetDf >= minDocCount) { bucket.bucketToXContent(builder, params); } } builder.endArray(); return builder; } }
InternalMappedSignificantTerms
java
mapstruct__mapstruct
processor/src/main/java/org/mapstruct/ap/internal/conversion/DateToStringConversion.java
{ "start": 995, "end": 3384 }
class ____ implements ConversionProvider { @Override public Assignment to(ConversionContext conversionContext) { return new TypeConversion( getImportTypes( conversionContext ), Collections.emptyList(), getConversionExpression( conversionContext, "format" ) ); } @Override public Assignment from(ConversionContext conversionContext) { return new TypeConversion( getImportTypes( conversionContext ), Collections.singletonList( conversionContext.getTypeFactory().getType( ParseException.class ) ), getConversionExpression( conversionContext, "parse" ) ); } @Override public List<HelperMethod> getRequiredHelperMethods(ConversionContext conversionContext) { return Collections.emptyList(); } private Set<Type> getImportTypes(ConversionContext conversionContext) { if ( conversionContext.getLocale() == null ) { return Collections.singleton( conversionContext.getTypeFactory().getType( SimpleDateFormat.class ) ); } return asSet( conversionContext.getTypeFactory().getType( SimpleDateFormat.class ), conversionContext.getTypeFactory().getType( Locale.class ) ); } private String getConversionExpression(ConversionContext conversionContext, String method) { StringBuilder conversionString = new StringBuilder( "new " ); conversionString.append( simpleDateFormat( conversionContext ) ); conversionString.append( '(' ); if ( conversionContext.getDateFormat() != null ) { conversionString.append( " \"" ); conversionString.append( conversionContext.getDateFormat() ); conversionString.append( "\"" ); if ( conversionContext.getLocale() != null ) { conversionString.append( ", " ).append( locale( conversionContext ) ).append( ".forLanguageTag( \"" ); conversionString.append( conversionContext.getLocale() ); conversionString.append( "\" ) " ); } else { conversionString.append( " " ); } } conversionString.append( ")." ); conversionString.append( method ); conversionString.append( "( <SOURCE> )" ); return conversionString.toString(); } }
DateToStringConversion
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/annotations/lob/CompiledCode.java
{ "start": 338, "end": 530 }
class ____ extends AbstractCompiledCode { private Integer id; @Id @GeneratedValue public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } }
CompiledCode
java
netty__netty
codec-http2/src/main/java/io/netty/handler/codec/http2/Http2HeadersFrame.java
{ "start": 715, "end": 1103 }
interface ____ extends Http2StreamFrame { /** * A complete header list. CONTINUATION frames are automatically handled. */ Http2Headers headers(); /** * Frame padding to use. Must be non-negative and less than 256. */ int padding(); /** * Returns {@code true} if the END_STREAM flag is set. */ boolean isEndStream(); }
Http2HeadersFrame
java
quarkusio__quarkus
extensions/resteasy-classic/resteasy/runtime/src/main/java/io/quarkus/resteasy/runtime/standalone/ResteasyConfigurationMPConfig.java
{ "start": 596, "end": 2766 }
class ____ implements ResteasyConfiguration { private static final Map<String, Function<Config, Optional<String>>> RESTEASY_QUARKUS_MAPPING_PARAMS = Map.of( ResteasyContextParameters.RESTEASY_GZIP_MAX_INPUT, ResteasyConfigurationMPConfig::getGzipMaxInput); @Override public String getParameter(String name) { Config config = ConfigProvider.getConfig(); if (config == null) { return null; } Optional<String> value = Optional.empty(); Function<Config, Optional<String>> mappingFunction = RESTEASY_QUARKUS_MAPPING_PARAMS.get(name); if (mappingFunction != null) { // try to use Quarkus configuration value = mappingFunction.apply(config); } // if the parameter name is not mapped or there is no value, use the parameter name as provided return value.or(() -> config.getOptionalValue(name, String.class)) .orElse(null); } @Override public Set<String> getParameterNames() { Config config = ConfigProvider.getConfig(); if (config == null) { return Set.of(); } HashSet<String> set = new HashSet<>(); for (String name : config.getPropertyNames()) { set.add(name); } set.addAll(RESTEASY_QUARKUS_MAPPING_PARAMS.keySet()); return set; } @Override public String getInitParameter(String name) { return getParameter(name); } @Override public Set<String> getInitParameterNames() { return getParameterNames(); } private static Optional<String> getGzipMaxInput(Config config) { if (config.getOptionalValue("resteasy.gzip.max.input", String.class).isPresent()) { // resteasy-specific properties have priority return Optional.empty(); } Optional<MemorySize> rawValue = config.getOptionalValue("quarkus.resteasy.gzip.max-input", MemorySize.class); if (rawValue.isEmpty()) { return Optional.empty(); } return Optional.of(Long.toString(rawValue.get().asLongValue())); } }
ResteasyConfigurationMPConfig
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/inject/MoreThanOneScopeAnnotationOnClass.java
{ "start": 2056, "end": 2145 }
class ____ be annotated with at most one scope annotation.", severity = ERROR) public
can
java
apache__camel
components/camel-hashicorp-vault/src/generated/java/org/apache/camel/component/hashicorp/vault/HashicorpVaultEndpointConfigurer.java
{ "start": 742, "end": 4731 }
class ____ extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { HashicorpVaultEndpoint target = (HashicorpVaultEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "cloud": target.getConfiguration().setCloud(property(camelContext, boolean.class, value)); return true; case "host": target.getConfiguration().setHost(property(camelContext, java.lang.String.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "namespace": target.getConfiguration().setNamespace(property(camelContext, java.lang.String.class, value)); return true; case "operation": target.getConfiguration().setOperation(property(camelContext, org.apache.camel.component.hashicorp.vault.HashicorpVaultOperation.class, value)); return true; case "port": target.getConfiguration().setPort(property(camelContext, java.lang.String.class, value)); return true; case "scheme": target.getConfiguration().setScheme(property(camelContext, java.lang.String.class, value)); return true; case "secretpath": case "secretPath": target.getConfiguration().setSecretPath(property(camelContext, java.lang.String.class, value)); return true; case "token": target.getConfiguration().setToken(property(camelContext, java.lang.String.class, value)); return true; case "vaulttemplate": case "vaultTemplate": target.getConfiguration().setVaultTemplate(property(camelContext, org.springframework.vault.core.VaultTemplate.class, value)); return true; default: return false; } } @Override public String[] getAutowiredNames() { return new String[]{"vaultTemplate"}; } @Override public Class<?> getOptionType(String name, boolean ignoreCase) { switch (ignoreCase ? name.toLowerCase() : name) { case "cloud": return boolean.class; case "host": return java.lang.String.class; case "lazystartproducer": case "lazyStartProducer": return boolean.class; case "namespace": return java.lang.String.class; case "operation": return org.apache.camel.component.hashicorp.vault.HashicorpVaultOperation.class; case "port": return java.lang.String.class; case "scheme": return java.lang.String.class; case "secretpath": case "secretPath": return java.lang.String.class; case "token": return java.lang.String.class; case "vaulttemplate": case "vaultTemplate": return org.springframework.vault.core.VaultTemplate.class; default: return null; } } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { HashicorpVaultEndpoint target = (HashicorpVaultEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "cloud": return target.getConfiguration().isCloud(); case "host": return target.getConfiguration().getHost(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "namespace": return target.getConfiguration().getNamespace(); case "operation": return target.getConfiguration().getOperation(); case "port": return target.getConfiguration().getPort(); case "scheme": return target.getConfiguration().getScheme(); case "secretpath": case "secretPath": return target.getConfiguration().getSecretPath(); case "token": return target.getConfiguration().getToken(); case "vaulttemplate": case "vaultTemplate": return target.getConfiguration().getVaultTemplate(); default: return null; } } }
HashicorpVaultEndpointConfigurer
java
apache__kafka
clients/src/main/java/org/apache/kafka/common/config/AbstractConfig.java
{ "start": 31599, "end": 32266 }
class ____<V> extends HashMap<String, V> { private final Map<String, ?> originals; ResolvingMap(Map<String, ? extends V> resolved, Map<String, ?> originals) { super(resolved); this.originals = Collections.unmodifiableMap(originals); } @Override public V get(Object key) { if (key instanceof String && originals.containsKey(key)) { // Intentionally ignore the result; call just to mark the original entry as used originals.get(key); } // But always use the resolved entry return super.get(key); } } }
ResolvingMap
java
apache__flink
flink-runtime/src/main/java/org/apache/flink/runtime/rest/messages/job/metrics/JobManagerOperatorMetricsHeaders.java
{ "start": 1241, "end": 2320 }
class ____ extends AbstractMetricsHeaders<JobManagerOperatorMetricsMessageParameters> { private static final JobManagerOperatorMetricsHeaders INSTANCE = new JobManagerOperatorMetricsHeaders(); private JobManagerOperatorMetricsHeaders() {} @Override public String getDescription() { return "Provides access to jobmanager operator metrics. This is an operator that executes on the jobmanager and the coordinator for FLIP 27 sources is one example of such an operator."; } @Override public JobManagerOperatorMetricsMessageParameters getUnresolvedMessageParameters() { return new JobManagerOperatorMetricsMessageParameters(); } @Override public String getTargetRestEndpointURL() { return "/jobs/:" + JobIDPathParameter.KEY + "/vertices/:" + JobVertexIdPathParameter.KEY + "/jm-operator-metrics"; } public static JobManagerOperatorMetricsHeaders getInstance() { return INSTANCE; } }
JobManagerOperatorMetricsHeaders
java
quarkusio__quarkus
devtools/gradle/gradle-application-plugin/src/main/java/io/quarkus/gradle/tasks/QuarkusRemoteDev.java
{ "start": 247, "end": 725 }
class ____ extends QuarkusDev { @Inject public QuarkusRemoteDev(Configuration quarkusDevConfiguration, QuarkusPluginExtension extension) { super( "Remote development mode: enables hot deployment on remote JVM with background compilation", quarkusDevConfiguration, extension); } protected void modifyDevModeContext(DevModeCommandLineBuilder builder) { builder.remoteDev(true); } }
QuarkusRemoteDev
java
google__guava
guava-testlib/test/com/google/common/testing/NullPointerTesterTest.java
{ "start": 21614, "end": 21975 }
class ____ extends PassObject { @Override public void twoArg(String s, Integer i) { checkNotNull(s); doThrow(i); // Fail: throwing non-NPE exception for null i } } public void testFailTwoArgsSecondArgThrowsWrongType() { shouldFail(new FailTwoArgsSecondArgThrowsWrongType()); } private static
FailTwoArgsSecondArgThrowsWrongType
java
apache__camel
components/camel-dapr/src/main/java/org/apache/camel/component/dapr/WorkflowOperation.java
{ "start": 852, "end": 1030 }
enum ____ { scheduleNew, terminate, purge, suspend, resume, state, waitForInstanceStart, waitForInstanceCompletion, raiseEvent }
WorkflowOperation
java
spring-projects__spring-boot
module/spring-boot-validation/src/test/java/org/springframework/boot/validation/autoconfigure/ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests.java
{ "start": 1352, "end": 1827 }
class ____ { private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() .withConfiguration(AutoConfigurations.of(ValidationAutoConfiguration.class)); @Test void missingElDependencyIsTolerated() { this.contextRunner.run((context) -> { assertThat(context).hasSingleBean(Validator.class); assertThat(context).hasSingleBean(MethodValidationPostProcessor.class); }); } }
ValidationAutoConfigurationWithHibernateValidatorMissingElImplTests
java
alibaba__druid
core/src/test/java/com/alibaba/druid/bvt/proxy/BatchReadTest.java
{ "start": 1057, "end": 5713 }
class ____ extends TestCase { private static String create_url = "jdbc:wrap-jdbc:filters=default,commonLogging,log4j:name=batchReadTest:jdbc:derby:memory:batchDB;create=true"; protected void setUp() throws Exception { Class.forName("com.alibaba.druid.proxy.DruidDriver"); Connection conn = DriverManager.getConnection(create_url); JdbcStatManager.getInstance(); createTable(); conn.close(); } private void createTable() throws SQLException { Connection conn = DriverManager.getConnection(create_url); Statement stmt = conn.createStatement(); stmt.execute("CREATE TABLE T_USER (ID INTEGER, NAME VARCHAR(50), BIRTHDATE TIMESTAMP)"); stmt.close(); conn.close(); } private void dropTable() throws SQLException { Connection conn = DriverManager.getConnection(create_url); Statement stmt = conn.createStatement(); stmt.execute("DROP TABLE T_USER"); stmt.close(); conn.close(); } protected void tearDown() throws Exception { dropTable(); DruidDriver.getProxyDataSources().clear(); assertEquals(0, JdbcStatManager.getInstance().getSqlList().size()); } public void test_stmt_batch() throws Exception { Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection(create_url); stmt = conn.createStatement(); stmt.isClosed(); stmt.isPoolable(); stmt.addBatch("INSERT INTO T_USER (ID, NAME, BIRTHDATE) VALUES (1, 'A', NULL)"); stmt.addBatch("INSERT INTO T_USER (ID, NAME, BIRTHDATE) VALUES (2, 'B', NULL)"); stmt.executeBatch(); for (; ; ) { boolean moreResults = stmt.getMoreResults(); if (moreResults) { rs = stmt.getResultSet(); JdbcUtils.printResultSet(rs, System.out); JdbcUtils.close(rs); continue; } int updateCount = stmt.getUpdateCount(); if (updateCount == -1) { break; } } } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(conn); } } public void test_pstmt_batch() throws Exception { Connection conn = null; Statement stmt = null; PreparedStatement pstmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection(create_url); stmt = conn.createStatement(); pstmt = conn.prepareStatement("INSERT INTO T_USER (ID, NAME, BIRTHDATE) VALUES (?, ?, ?)"); pstmt.setInt(1, 1); pstmt.setString(2, "A"); pstmt.setTimestamp(3, new java.sql.Timestamp(System.currentTimeMillis())); pstmt.addBatch(); pstmt.setInt(1, 2); pstmt.setString(2, "B"); pstmt.setTimestamp(3, new java.sql.Timestamp(System.currentTimeMillis())); pstmt.addBatch(); int[] updateCounts = pstmt.executeBatch(); assertArrayEquals(new int[]{1, 1}, updateCounts); pstmt.setFetchDirection(stmt.getFetchDirection()); pstmt.setFetchSize(pstmt.getFetchSize()); ResultSet keys = stmt.getGeneratedKeys(); JdbcUtils.close(keys); // just call stmt.getConnection(); stmt.setMaxFieldSize(stmt.getMaxFieldSize()); stmt.setMaxRows(stmt.getMaxRows()); stmt.getQueryTimeout(); stmt.getResultSetConcurrency(); stmt.getResultSetHoldability(); stmt.getResultSetType(); stmt.setPoolable(true); stmt.getWarnings(); pstmt.getMetaData(); pstmt.getParameterMetaData(); pstmt.getWarnings(); stmt.execute("SELECT * FROM T_USER"); for (; ; ) { rs = stmt.getResultSet(); rs.getWarnings(); if (rs != null) { JdbcUtils.printResultSet(rs, System.out); JdbcUtils.close(rs); } if ((stmt.getMoreResults() == false) && (stmt.getUpdateCount() == -1)) { break; } } } finally { JdbcUtils.close(rs); JdbcUtils.close(stmt); JdbcUtils.close(pstmt); JdbcUtils.close(conn); } } }
BatchReadTest
java
apache__camel
components/camel-cxf/camel-cxf-soap/src/test/java/org/apache/camel/component/cxf/jaxws/CxfConsumerFaultTest.java
{ "start": 1081, "end": 2236 }
class ____ extends CxfConsumerPayloadFaultTest { @Override protected RouteBuilder createRouteBuilder() { final String serviceURI = "cxf://" + serviceAddress + "?" + PORT_NAME_PROP + "&" + SERVICE_NAME_PROP + "&" + WSDL_URL_PROP + "&serviceClass=org.apache.camel.wsdl_first.Person"; return new RouteBuilder() { public void configure() { from(serviceURI).process(new Processor() { public void process(final Exchange exchange) throws Exception { // set the fault message here org.apache.camel.wsdl_first.types.UnknownPersonFault faultDetail = new org.apache.camel.wsdl_first.types.UnknownPersonFault(); faultDetail.setPersonId(""); UnknownPersonFault fault = new UnknownPersonFault("Get the null value of person name", faultDetail); exchange.getMessage().setBody(fault); } }); } }; } }
CxfConsumerFaultTest
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/internal/operators/observable/ObservableGroupJoin.java
{ "start": 12405, "end": 13496 }
class ____ extends AtomicReference<Disposable> implements Observer<Object>, Disposable { private static final long serialVersionUID = 1883890389173668373L; final JoinSupport parent; final boolean isLeft; LeftRightObserver(JoinSupport parent, boolean isLeft) { this.parent = parent; this.isLeft = isLeft; } @Override public void dispose() { DisposableHelper.dispose(this); } @Override public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(this, d); } @Override public void onNext(Object t) { parent.innerValue(isLeft, t); } @Override public void onError(Throwable t) { parent.innerError(t); } @Override public void onComplete() { parent.innerComplete(this); } } static final
LeftRightObserver
java
micronaut-projects__micronaut-core
buffer-netty/src/test/java/io/micronaut/buffer/netty/NioReadBufferTest.java
{ "start": 98, "end": 239 }
class ____ extends AbstractReadBufferTest { NioReadBufferTest() { super(ReadBufferFactory.getJdkFactory()); } }
NioReadBufferTest
java
google__error-prone
core/src/main/java/com/google/errorprone/bugpatterns/ThrowIfUncheckedKnownChecked.java
{ "start": 1881, "end": 4024 }
class ____ extends BugChecker implements MethodInvocationTreeMatcher { private static final Matcher<MethodInvocationTree> IS_THROW_IF_UNCHECKED = allOf( anyOf( staticMethod().onClass("com.google.common.base.Throwables").named("throwIfUnchecked"), staticMethod() .onClass("com.google.common.base.Throwables") .named("propagateIfPossible")), argumentCount(1)); private static final Matcher<ExpressionTree> IS_KNOWN_CHECKED_EXCEPTION = new Matcher<ExpressionTree>() { @Override public boolean matches(ExpressionTree tree, VisitorState state) { Type type = ASTHelpers.getType(tree); if (type.isUnion()) { return ((UnionType) type) .getAlternatives().stream().allMatch(t -> isKnownCheckedException(state, (Type) t)); } else { return isKnownCheckedException(state, type); } } boolean isKnownCheckedException(VisitorState state, Type type) { Types types = state.getTypes(); Symtab symtab = state.getSymtab(); // Check erasure for generics. // TODO(cpovirk): Is that necessary here or in ThrowIfUncheckedKnownUnchecked? type = types.erasure(type); return // Has to be some Exception: A variable of type Throwable might be an Error. types.isSubtype(type, symtab.exceptionType) // Has to be some subtype: A variable of type Exception might be a RuntimeException. && !types.isSameType(type, symtab.exceptionType) // Can't be of type RuntimeException. && !types.isSubtype(type, symtab.runtimeExceptionType); } }; @Override public Description matchMethodInvocation(MethodInvocationTree tree, VisitorState state) { if (IS_THROW_IF_UNCHECKED.matches(tree, state) && argument(0, IS_KNOWN_CHECKED_EXCEPTION).matches(tree, state)) { return describeMatch(tree, delete(state.getPath().getParentPath().getLeaf())); } return NO_MATCH; } }
ThrowIfUncheckedKnownChecked
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/qualifiers/multiple/MultipleQualifierSpec.java
{ "start": 3245, "end": 3358 }
class ____ implements Processor { } @PayBy(PaymentMethod.TRANSFER) @Asynchronous @Singleton
AsyncCreditCardProcessor
java
quarkusio__quarkus
extensions/vertx-http/deployment/src/test/java/io/quarkus/vertx/http/security/FormAuthNoRedirectTestCase.java
{ "start": 807, "end": 5849 }
class ____ { private static final String APP_PROPS = "" + "quarkus.http.auth.form.enabled=true\n" + "quarkus.http.auth.form.login-page=\n" + "quarkus.http.auth.form.error-page=\n" + "quarkus.http.auth.form.landing-page=\n" + "quarkus.http.auth.policy.r1.roles-allowed=a d m i n\n" + "quarkus.http.auth.permission.roles1.paths=/admin\n" + "quarkus.http.auth.permission.roles1.policy=r1\n"; @RegisterExtension static QuarkusUnitTest test = new QuarkusUnitTest().setArchiveProducer(new Supplier<>() { @Override public JavaArchive get() { return ShrinkWrap.create(JavaArchive.class) .addClasses(TestIdentityProvider.class, TestIdentityController.class, TestTrustedIdentityProvider.class, PathHandler.class) .addAsResource(new StringAsset(APP_PROPS), "application.properties"); } }); @BeforeAll public static void setup() { TestIdentityController.resetRoles() .add("a d m i n", "a d m i n", "a d m i n"); } /** * First, protected /admin resource is accessed. No quarkus-credential cookie * is presented by the client, so server should respond with 401. * * Next, let's assume there was a login form on the /login page, * we do POST with valid credentials. * Server should provide a response with quarkus-credential cookie and respond with 200. * * Last but not least, client accesses the protected /admin resource again, * this time providing server with stored quarkus-credential cookie. * Access is granted and landing page displayed. */ @Test public void testFormBasedAuthSuccess() { RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); CookieFilter cookies = new CookieFilter(); RestAssured .given() .filter(cookies) .redirects().follow(false) .when() .get("/admin") .then() .assertThat() .statusCode(401) .header("location", nullValue()); RestAssured .given() .filter(cookies) .redirects().follow(false) .when() .formParam("j_username", "a d m i n") .formParam("j_password", "a d m i n") .post("/j_security_check") .then() .assertThat() .statusCode(200) .header("location", nullValue()) .cookie("quarkus-credential", notNullValue()); RestAssured .given() .filter(cookies) .redirects().follow(false) .when() .get("/admin") .then() .assertThat() .statusCode(200) .body(equalTo("a d m i n:/admin")); } @Test public void testFormBasedAuthSuccessNoLocation() { RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); CookieFilter cookies = new CookieFilter(); RestAssured .given() .filter(cookies) .redirects().follow(false) .when() .formParam("j_username", "a d m i n") .formParam("j_password", "a d m i n") .post("/j_security_check") .then() .assertThat() .statusCode(200) .cookie("quarkus-credential", notNullValue()); } @Test public void testFormBasedAuthSuccessWithLocation() { RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); RestAssured .given() .cookie("quarkus-redirect-location", "http://localhost:8081/admin") .redirects().follow(false) .when() .formParam("j_username", "a d m i n") .formParam("j_password", "a d m i n") .post("/j_security_check") .then() .assertThat() .statusCode(302) .header("location", containsString("/admin")) .cookie("quarkus-credential", notNullValue()); } @Test public void testFormAuthFailure() { RestAssured.enableLoggingOfRequestAndResponseIfValidationFails(); CookieFilter cookies = new CookieFilter(); RestAssured .given() .filter(cookies) .redirects().follow(false) .when() .formParam("j_username", "a d m i n") .formParam("j_password", "wrongpassword") .post("/j_security_check") .then() .assertThat() .header("location", nullValue()) .statusCode(401); } }
FormAuthNoRedirectTestCase
java
apache__camel
core/camel-core-processor/src/main/java/org/apache/camel/processor/transformer/StringDataTypeTransformer.java
{ "start": 1369, "end": 1850 }
class ____ extends Transformer { private static final Transformer DELEGATE = new TypeConverterTransformer(String.class); @Override public void transform(Message message, DataType from, DataType to) throws Exception { message.getExchange().setProperty(ExchangePropertyKey.CHARSET_NAME, StandardCharsets.UTF_8.name()); DELEGATE.transform(message, from, to); message.setHeader(Exchange.CONTENT_TYPE, "text/plain"); } }
StringDataTypeTransformer
java
quarkusio__quarkus
integration-tests/main/src/test/java/io/quarkus/it/main/ConfigPropertiesTestCase.java
{ "start": 204, "end": 622 }
class ____ { @Test public void testConfigPropertiesProperlyInjected() { RestAssured .when().get("/configuration-properties") .then().body(is("HelloONE!")); } @Test public void testImplicitConverters() { RestAssured .when().get("/configuration-properties/period") .then().body(is("P1D")); } }
ConfigPropertiesTestCase
java
apache__maven
api/maven-api-core/src/main/java/org/apache/maven/api/ExtensibleEnums.java
{ "start": 1044, "end": 1200 }
class ____ factory methods for creating instances of extensible enums * such as Language, PathScope, and ProjectScope. * * @since 4.0.0 */ abstract
provides
java
apache__hadoop
hadoop-tools/hadoop-azure/src/main/java/org/apache/hadoop/fs/azure/SecureStorageInterfaceImpl.java
{ "start": 11999, "end": 13167 }
class ____ extends CloudBlobDirectoryWrapper { private final CloudBlobDirectory directory; public SASCloudBlobDirectoryWrapperImpl(CloudBlobDirectory directory) { this.directory = directory; } @Override public URI getUri() { return directory.getUri(); } @Override public Iterable<ListBlobItem> listBlobs(String prefix, boolean useFlatBlobListing, EnumSet<BlobListingDetails> listingDetails, BlobRequestOptions options, OperationContext opContext) throws URISyntaxException, StorageException { return SASWrappingIterator.wrap(directory.listBlobs(prefix, useFlatBlobListing, listingDetails, options, opContext)); } @Override public CloudBlobContainer getContainer() throws URISyntaxException, StorageException { return directory.getContainer(); } @Override public CloudBlobDirectory getParent() throws URISyntaxException, StorageException { return directory.getParent(); } @Override public StorageUri getStorageUri() { return directory.getStorageUri(); } } abstract static
SASCloudBlobDirectoryWrapperImpl
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/config/plugins/validation/validators/ValidPortValidatorTest.java
{ "start": 1481, "end": 2678 }
class ____ { private PluginType<HostAndPort> plugin; private Node node; @SuppressWarnings("unchecked") @BeforeEach void setUp() { final PluginManager manager = new PluginManager("Test"); manager.collectPlugins(); plugin = (PluginType<HostAndPort>) manager.getPluginType("HostAndPort"); assertNotNull(plugin, "Rebuild this module to ensure annotation processing has been done."); node = new Node(null, "HostAndPort", plugin); node.getAttributes().put("host", "localhost"); } @Test void testNegativePort() { node.getAttributes().put("port", "-1"); assertNull(buildPlugin()); } @Test void testValidPort() { node.getAttributes().put("port", "10"); assertNotNull(buildPlugin()); } @Test void testInvalidPort() { node.getAttributes().put("port", "1234567890"); assertNull(buildPlugin()); } private HostAndPort buildPlugin() { return (HostAndPort) new PluginBuilder(plugin) .withConfiguration(new NullConfiguration()) .withConfigurationNode(node) .build(); } }
ValidPortValidatorTest
java
apache__flink
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/scalar/MapEntriesFunction.java
{ "start": 1413, "end": 2751 }
class ____ extends BuiltInScalarFunction { private final ArrayData.ElementGetter keyElementGetter; private final ArrayData.ElementGetter valueElementGetter; public MapEntriesFunction(SpecializedFunction.SpecializedContext context) { super(BuiltInFunctionDefinitions.MAP_ENTRIES, context); KeyValueDataType inputType = ((KeyValueDataType) context.getCallContext().getArgumentDataTypes().get(0)); keyElementGetter = ArrayData.createElementGetter(inputType.getKeyDataType().getLogicalType()); valueElementGetter = ArrayData.createElementGetter(inputType.getValueDataType().getLogicalType()); } public @Nullable ArrayData eval(@Nullable MapData input) { if (input == null) { return null; } ArrayData keys = input.keyArray(); ArrayData values = input.valueArray(); int size = input.size(); Object[] resultData = new Object[size]; for (int pos = 0; pos < size; pos++) { final Object key = keyElementGetter.getElementOrNull(keys, pos); final Object value = valueElementGetter.getElementOrNull(values, pos); resultData[pos] = GenericRowData.of(key, value); } return new GenericArrayData(resultData); } }
MapEntriesFunction
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs-rbf/src/main/java/org/apache/hadoop/hdfs/server/federation/store/StateStoreUtils.java
{ "start": 2908, "end": 3056 }
class ____ for a record. If we get an implementation of a * record we will return the real parent record class. * * @param <T> Type of the
name
java
mockito__mockito
mockito-core/src/main/java/org/mockito/internal/creation/bytebuddy/access/MockMethodInterceptor.java
{ "start": 4514, "end": 4756 }
class ____ { @SuppressWarnings("unused") public static int doIdentityHashCode(@This Object thiz) { return System.identityHashCode(thiz); } private ForHashCode() {} } public static
ForHashCode
java
apache__kafka
connect/api/src/main/java/org/apache/kafka/connect/storage/Converter.java
{ "start": 2061, "end": 5037 }
interface ____ extends Closeable { /** * Configure this class. * @param configs configs in key/value pairs * @param isKey whether this converter is for a key or a value */ void configure(Map<String, ?> configs, boolean isKey); /** * Convert a Kafka Connect data object to a native object for serialization. * @param topic the topic associated with the data * @param schema the schema for the value * @param value the value to convert * @return the serialized value */ byte[] fromConnectData(String topic, Schema schema, Object value); /** * Convert a Kafka Connect data object to a native object for serialization, * potentially using the supplied topic and headers in the record as necessary. * * <p>Connect uses this method directly, and for backward compatibility reasons this method * by default will call the {@link #fromConnectData(String, Schema, Object)} method. * Override this method to make use of the supplied headers.</p> * @param topic the topic associated with the data * @param headers the headers associated with the data; any changes done to the headers * are applied to the message sent to the broker * @param schema the schema for the value * @param value the value to convert * @return the serialized value */ default byte[] fromConnectData(String topic, Headers headers, Schema schema, Object value) { return fromConnectData(topic, schema, value); } /** * Convert a native object to a Kafka Connect data object for deserialization. * @param topic the topic associated with the data * @param value the value to convert * @return an object containing the {@link Schema} and the converted value */ SchemaAndValue toConnectData(String topic, byte[] value); /** * Convert a native object to a Kafka Connect data object for deserialization, * potentially using the supplied topic and headers in the record as necessary. * * <p>Connect uses this method directly, and for backward compatibility reasons this method * by default will call the {@link #toConnectData(String, byte[])} method. * Override this method to make use of the supplied headers.</p> * @param topic the topic associated with the data * @param headers the headers associated with the data * @param value the value to convert * @return an object containing the {@link Schema} and the converted value */ default SchemaAndValue toConnectData(String topic, Headers headers, byte[] value) { return toConnectData(topic, value); } /** * Configuration specification for this converter. * @return the configuration specification; may not be null */ default ConfigDef config() { return new ConfigDef(); } @Override default void close() throws IOException { // no op } }
Converter
java
apache__kafka
connect/api/src/main/java/org/apache/kafka/connect/connector/Connector.java
{ "start": 2295, "end": 6518 }
class ____ implements Versioned { protected ConnectorContext context; /** * Initialize this connector, using the provided ConnectorContext to notify the runtime of * input configuration changes. * @param ctx context object used to interact with the Kafka Connect runtime */ public void initialize(ConnectorContext ctx) { context = ctx; } /** * <p> * Initialize this connector, using the provided ConnectorContext to notify the runtime of * input configuration changes and using the provided set of Task configurations. * This version is only used to recover from failures. * </p> * <p> * The default implementation ignores the provided Task configurations. During recovery, Kafka Connect will request * an updated set of configurations and update the running Tasks appropriately. However, Connectors should * implement special handling of this case if it will avoid unnecessary changes to running Tasks. * </p> * * @param ctx context object used to interact with the Kafka Connect runtime * @param taskConfigs existing task configurations, which may be used when generating new task configs to avoid * churn in partition to task assignments */ public void initialize(ConnectorContext ctx, List<Map<String, String>> taskConfigs) { context = ctx; // Ignore taskConfigs. May result in more churn of tasks during recovery if updated configs // are very different, but reduces the difficulty of implementing a Connector } /** * Returns the context object used to interact with the Kafka Connect runtime. * * @return the context for this Connector. */ protected ConnectorContext context() { return context; } /** * Start this Connector. This method will only be called on a clean Connector, i.e. it has * either just been instantiated and initialized or {@link #stop()} has been invoked. * * @param props configuration settings */ public abstract void start(Map<String, String> props); /** * Reconfigure this Connector. Most implementations will not override this, using the default * implementation that calls {@link #stop()} followed by {@link #start(Map)}. * Implementations only need to override this if they want to handle this process more * efficiently, e.g. without shutting down network connections to the external system. * * @param props new configuration settings */ public void reconfigure(Map<String, String> props) { stop(); start(props); } /** * Returns the {@link Task} implementation for this Connector. */ public abstract Class<? extends Task> taskClass(); /** * Returns a set of configurations for Tasks based on the current configuration, * producing at most {@code maxTasks} configurations. * * @param maxTasks maximum number of configurations to generate * @return configurations for Tasks */ public abstract List<Map<String, String>> taskConfigs(int maxTasks); /** * Stop this connector. */ public abstract void stop(); /** * Validate the connector configuration values against configuration definitions. * @param connectorConfigs the provided configuration values * @return a parsed and validated {@link Config} containing any relevant validation errors with the raw * {@code connectorConfigs} which should prevent this configuration from being used. */ public Config validate(Map<String, String> connectorConfigs) { ConfigDef configDef = config(); if (null == configDef) { throw new ConnectException( String.format("%s.config() must return a ConfigDef that is not null.", this.getClass().getName()) ); } List<ConfigValue> configValues = configDef.validate(connectorConfigs); return new Config(configValues); } /** * Define the configuration for the connector. * @return The ConfigDef for this connector; may not be null. */ public abstract ConfigDef config(); }
Connector
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/jdbc/Expectations.java
{ "start": 907, "end": 4074 }
class ____ implements {@code Expectation} * @param callable true if the {@code Expectation} will be called with {@link CallableStatement}s. * @return a new instance of the given class * * @since 6.5 */ @Internal public static Expectation createExpectation(Supplier<? extends Expectation> expectation, boolean callable) { final Expectation instance = instantiate( expectation, callable ); instance.validate( callable ); return instance; } private static Expectation instantiate(Supplier<? extends Expectation> supplier, boolean callable) { if ( supplier == null ) { return callable ? new Expectation.OutParameter() : new Expectation.RowCount(); } else { return supplier.get(); } } static CallableStatement toCallableStatement(PreparedStatement statement) { if ( statement instanceof CallableStatement callableStatement ) { return callableStatement; } else { throw new HibernateException( "Expectation.OutParameter operates exclusively on CallableStatements: " + statement.getClass() ); } } static void checkBatched(int expectedRowCount, int rowCount, int batchPosition, String sql) { switch (rowCount) { case EXECUTE_FAILED: throw new BatchFailedException( "Batch update failed: " + batchPosition ); case SUCCESS_NO_INFO: BATCH_MESSAGE_LOGGER.batchSuccessUnknown( batchPosition ); break; default: if ( expectedRowCount > rowCount ) { throw new StaleStateException( "Batch update returned unexpected row count from update " + batchPosition + actualVsExpected( expectedRowCount, rowCount ) + " [" + sql + "]" ); } else if ( expectedRowCount < rowCount ) { throw new BatchedTooManyRowsAffectedException( "Batch update returned unexpected row count from update " + batchPosition + actualVsExpected( expectedRowCount, rowCount ), expectedRowCount, rowCount, batchPosition ); } } } static void checkNonBatched(int expectedRowCount, int rowCount, String sql) { if ( expectedRowCount > rowCount ) { throw new StaleStateException( "Unexpected row count" + actualVsExpected( expectedRowCount, rowCount ) + " [" + sql + "]" ); } if ( expectedRowCount < rowCount ) { throw new TooManyRowsAffectedException( "Unexpected row count" + actualVsExpected( expectedRowCount, rowCount ), 1, rowCount ); } } private static String actualVsExpected(int expectedRowCount, int rowCount) { return " (expected row count " + expectedRowCount + " but was " + rowCount + ")"; } // Various Expectation instances ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /** * @deprecated Use {@link Expectation.None} */ @Deprecated(since = "6.5") public static final Expectation NONE = new Expectation.None(); /** * @deprecated Use {@link Expectation.RowCount} */ @Deprecated(since = "6.5") public static final Expectation BASIC = new Expectation.RowCount(); /** * @deprecated Use {@link Expectation.OutParameter} */ @Deprecated(since = "6.5") public static final Expectation PARAM = new Expectation.OutParameter(); private Expectations() { } }
which
java
processing__processing4
app/src/processing/app/Platform.java
{ "start": 10373, "end": 14840 }
class ____ pathURL = Base.class.getProtectionDomain().getCodeSource().getLocation(); // Decode URL String decodedPath; try { decodedPath = pathURL.toURI().getSchemeSpecificPart(); } catch (URISyntaxException e) { Messages.showError("Missing File", "Could not access a required file:\n" + "<b>" + name + "</b>\n" + "You may need to reinstall Processing.", e); return null; } if (decodedPath.contains("/app/bin")) { // This means we're in Eclipse final File build = new File(decodedPath, "../../build").getAbsoluteFile(); if (Platform.isMacOS()) { processingRoot = new File(build, "macos/work/Processing.app/Contents/Java"); } else if (Platform.isWindows()) { processingRoot = new File(build, "windows/work"); } else if (Platform.isLinux()) { processingRoot = new File(build, "linux/work"); } } else { // The .jar file will be in the lib folder File jarFolder = new File(decodedPath).getParentFile(); if (jarFolder.getName().equals("lib")) { // The main Processing installation directory. // This works for Windows, Linux, and Apple's Java 6 on OS X. processingRoot = jarFolder.getParentFile(); } else if (Platform.isMacOS()) { // This works for Java 8 on OS X. We don't have things inside a 'lib' // folder on OS X. Adding it caused more problems than it was worth. processingRoot = jarFolder; } if (processingRoot == null || !processingRoot.exists()) { // Try working directory instead (user.dir, different from user.home) System.err.println("Could not find lib folder via " + jarFolder.getAbsolutePath() + ", switching to user.dir"); processingRoot = new File(""); // resolves to "user.dir" } } } return new File(processingRoot, name); } static public File getJavaHome() { // Get the build in JDK location from the Jetpack Compose resources var resourcesDir = System.getProperty("compose.application.resources.dir"); if(resourcesDir != null) { var jdkFolder = new File(resourcesDir,"jdk"); if(jdkFolder.exists()){ return jdkFolder; } } // If the JDK is set in the environment, use that. var home = System.getProperty("java.home"); if(home != null){ return new File(home); } // Otherwise try to use the Ant embedded JDK. if (Platform.isMacOS()) { //return "Contents/PlugIns/jdk1.7.0_40.jdk/Contents/Home/jre/bin/java"; File[] plugins = getContentFile("../PlugIns").listFiles((dir, name) -> dir.isDirectory() && name.contains("jdk") && !name.startsWith(".")); return new File(plugins[0], "Contents/Home"); } // On all other platforms, it's the 'java' folder adjacent to Processing return getContentFile("java"); } /** Get the path to the embedded Java executable. */ static public String getJavaPath() { String javaPath = "bin/java" + (Platform.isWindows() ? ".exe" : ""); File javaFile = new File(getJavaHome(), javaPath); try { return javaFile.getCanonicalPath(); } catch (IOException e) { return javaFile.getAbsolutePath(); } } static protected File getProcessingApp() { File appFile; if (Platform.isMacOS()) { // walks up from Processing.app/Contents/Java to Processing.app // (or whatever the user has renamed it to) appFile = getContentFile("../.."); } else if (Platform.isWindows()) { appFile = getContentFile("processing.exe"); } else { appFile = getContentFile("processing"); } try { return appFile.getCanonicalFile(); } catch (Exception e) { e.printStackTrace(); } return null; } // Not great, shows the crusty Duke icon in the dock. // Better to just re-launch the .exe instead. // Hacked up from <a href="https://lewisleo.blogspot.com/2012/08/programmatically-restart-java.html">this code</a>. static private void restartJavaApplication() { // System.out.println("java path: " + javaPath); // String java = System.getProperty("java.home") + "/bin/java"; // Tested and working with JDK 17 [fry 230122] // System.out.println("sun java command: " + System.getProperty("sun.java.command")); // System.out.println("
URL
java
apache__flink
flink-connectors/flink-connector-files/src/main/java/org/apache/flink/connector/file/table/PartitionLoader.java
{ "start": 8985, "end": 10434 }
class ____ implements PartitionCommitPolicy.Context { private final Path partitionPath; private final LinkedHashMap<String, String> partitionSpec; private CommitPolicyContextImpl( LinkedHashMap<String, String> partitionSpec, Path partitionPath) { this.partitionSpec = partitionSpec; this.partitionPath = partitionPath; } @Override public String catalogName() { return identifier.getCatalogName(); } @Override public String databaseName() { return identifier.getDatabaseName(); } @Override public String tableName() { return identifier.getObjectName(); } @Override public List<String> partitionKeys() { List<String> partitionKeys = new LinkedList<>(); for (Map.Entry<String, String> entry : partitionSpec.entrySet()) { partitionKeys.add(entry.getKey()); } return partitionKeys; } @Override public List<String> partitionValues() { return new ArrayList<>(partitionSpec.values()); } @Override public Path partitionPath() { return this.partitionPath; } @Override public LinkedHashMap<String, String> partitionSpec() { return partitionSpec; } } }
CommitPolicyContextImpl
java
greenrobot__EventBus
EventBusTestJava/src/main/java/org/greenrobot/eventbus/EventBusGenericsTest.java
{ "start": 1181, "end": 1360 }
class ____<T extends Number> { @Subscribe public void onGenericEvent(T event) { trackEvent(event); } } public
GenericNumberEventSubscriber
java
quarkusio__quarkus
integration-tests/elytron-resteasy-reactive/src/main/java/io/quarkus/it/resteasy/reactive/elytron/RootResource.java
{ "start": 608, "end": 2537 }
class ____ { @Inject SecurityIdentity identity; @POST @Consumes(MediaType.TEXT_PLAIN) public String posts(String data, @Context SecurityContext sec) { if (data == null) { throw new RuntimeException("No post data"); } if (sec.getUserPrincipal().getName() == null) { throw new RuntimeException("Failed to get user principal"); } return "post success"; } @GET @Produces(MediaType.TEXT_PLAIN) public String approval(@Context SecurityContext sec) { if (sec.getUserPrincipal().getName() == null) { throw new RuntimeException("Failed to get user principal"); } return "get success"; } @GET @Path("/secure") @Authenticated public String getSecure() { return "secure"; } @GET @Path("/user") @RolesAllowed("user") public String user(@Context SecurityContext sec) { return sec.getUserPrincipal().getName(); } @GET @Path("/manager-permission") @PermissionsAllowed(value = "manager-permission", permission = ManagerPermission.class) public String managerPermission(@Context SecurityContext sec) { return sec.getUserPrincipal().getName(); } @GET @Path("/employee") @RolesAllowed("${employees-config-property}") public String employee(@Context SecurityContext sec) { return sec.getUserPrincipal().getName(); } @GET @Path("/attributes") @Authenticated public String getAttributes() { final Map<String, Object> attributes = identity.getAttributes(); if (attributes == null || attributes.isEmpty()) { throw new RuntimeException("No attributes were specified"); } return attributes.entrySet().stream() .map(e -> e.getKey() + "=" + e.getValue()) .collect(Collectors.joining(",")); } }
RootResource
java
quarkusio__quarkus
extensions/mongodb-client/deployment/src/test/java/io/quarkus/mongodb/customization/NamedCustomizerTest.java
{ "start": 1530, "end": 1838 }
class ____ implements MongoClientCustomizer { @Override public MongoClientSettings.Builder customize(MongoClientSettings.Builder builder) { return builder.applicationName("my-app"); } } @ApplicationScoped @MongoClientName("second") public static
MyCustomizer
java
spring-projects__spring-framework
spring-test/src/main/java/org/springframework/test/annotation/SystemProfileValueSource.java
{ "start": 1099, "end": 1795 }
class ____ implements ProfileValueSource { private static final SystemProfileValueSource INSTANCE = new SystemProfileValueSource(); /** * Obtain the canonical instance of this ProfileValueSource. */ public static SystemProfileValueSource getInstance() { return INSTANCE; } /** * Private constructor, enforcing the singleton pattern. */ private SystemProfileValueSource() { } /** * Get the <em>profile value</em> indicated by the specified key from the * system properties. * @see System#getProperty(String) */ @Override public String get(String key) { Assert.hasText(key, "'key' must not be empty"); return System.getProperty(key); } }
SystemProfileValueSource
java
spring-projects__spring-framework
spring-context/src/main/java/org/springframework/context/annotation/Configuration.java
{ "start": 17826, "end": 19403 }
class ____ well as for external calls to * this configuration's {@code @Bean} methods, for example, from another configuration class. * If this is not needed since each of this particular configuration's {@code @Bean} * methods is self-contained and designed as a plain factory method for container use, * switch this flag to {@code false} in order to avoid CGLIB subclass processing. * <p>Turning off bean method interception effectively processes {@code @Bean} * methods individually like when declared on non-{@code @Configuration} classes, * a.k.a. "@Bean Lite Mode" (see {@link Bean @Bean's javadoc}). It is therefore * behaviorally equivalent to removing the {@code @Configuration} stereotype. * @since 5.2 */ boolean proxyBeanMethods() default true; /** * Specify whether {@code @Bean} methods need to have unique method names, * raising an exception otherwise in order to prevent accidental overloading. * <p>The default is {@code true}, preventing accidental method overloads which * get interpreted as overloaded factory methods for the same bean definition * (as opposed to separate bean definitions with individual conditions etc). * Switch this flag to {@code false} in order to allow for method overloading * according to those semantics, accepting the risk for accidental overlaps. * @since 6.0 * @deprecated as of 7.0, always relying on {@code @Bean} unique methods, * just possibly with {@code Optional}/{@code ObjectProvider} arguments */ @Deprecated(since = "7.0") boolean enforceUniqueMethods() default true; }
as
java
apache__camel
components/camel-observation/src/test/java/org/apache/camel/observation/TwoServiceTest.java
{ "start": 1007, "end": 2607 }
class ____ extends CamelMicrometerObservationTestSupport { private static SpanTestData[] testdata = { new SpanTestData().setLabel("ServiceB server").setUri("direct://ServiceB").setOperation("ServiceB") .setParentId(1) .setKind(SpanKind.SERVER), new SpanTestData().setLabel("ServiceB server").setUri("direct://ServiceB").setOperation("ServiceB") .setParentId(2) .setKind(SpanKind.CLIENT), new SpanTestData().setLabel("ServiceA server").setUri("direct://ServiceA").setOperation("ServiceA") .setParentId(3) .setKind(SpanKind.SERVER), new SpanTestData().setLabel("ServiceA server").setUri("direct://ServiceA").setOperation("ServiceA") .setKind(SpanKind.CLIENT) }; TwoServiceTest() { super(testdata); } @Test void testRoute() { template.requestBody("direct:ServiceA", "Hello"); verify(); } @Override protected RoutesBuilder createRouteBuilder() { return new RouteBuilder() { @Override public void configure() { from("direct:ServiceA") .log("ServiceA has been called") .delay(simple("${random(1000,2000)}")) .to("direct:ServiceB"); from("direct:ServiceB") .log("ServiceB has been called") .delay(simple("${random(0,500)}")); } }; } }
TwoServiceTest
java
spring-projects__spring-boot
loader/spring-boot-loader/src/test/java/org/springframework/boot/loader/jar/ManifestInfoTests.java
{ "start": 907, "end": 1848 }
class ____ { @Test void noneReturnsNoDetails() { assertThat(ManifestInfo.NONE.getManifest()).isNull(); assertThat(ManifestInfo.NONE.isMultiRelease()).isFalse(); } @Test void getManifestReturnsManifest() { Manifest manifest = new Manifest(); ManifestInfo info = new ManifestInfo(manifest); assertThat(info.getManifest()).isSameAs(manifest); } @Test void isMultiReleaseWhenHasMultiReleaseAttributeReturnsTrue() { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(new Name("Multi-Release"), "true"); ManifestInfo info = new ManifestInfo(manifest); assertThat(info.isMultiRelease()).isTrue(); } @Test void isMultiReleaseWhenHasNoMultiReleaseAttributeReturnsFalse() { Manifest manifest = new Manifest(); manifest.getMainAttributes().put(new Name("Random-Release"), "true"); ManifestInfo info = new ManifestInfo(manifest); assertThat(info.isMultiRelease()).isFalse(); } }
ManifestInfoTests
java
quarkusio__quarkus
test-framework/maven/src/main/java/io/quarkus/maven/it/RunAndCheckMojoTestBase.java
{ "start": 714, "end": 7027 }
class ____ extends MojoTestBase { protected RunningInvoker running; protected File testDir; protected DevModeClient devModeClient = new DevModeClient(getPort()); private static final int DEFAULT_PORT = 8080; private static final int DEFAULT_MEMORY_IN_MB = 128; /** * Default to port 8080, but allow subtests to override. */ protected int getPort() { return DEFAULT_PORT; } /** * Default to quite constrained memory, but allow subclasses to override, for hungrier tests. */ protected int getAllowedHeapInMb() { return DEFAULT_MEMORY_IN_MB; } @AfterEach public void cleanup() { shutdownTheApp(); } public void shutdownTheApp() { if (running != null) { running.stop(); } devModeClient.awaitUntilServerDown(); } /** * Quarkus can be launched as `quarkus:dev` or `quarkus:test`. * In most cases it doesn't matter and dev mode is fine, but sometimes it's useful to cover test mode, * since it sometimes behaves differently. */ protected LaunchMode getDefaultLaunchMode() { return LaunchMode.DEVELOPMENT; } protected void run(boolean performCompile, String... options) throws FileNotFoundException, MavenInvocationException { run(performCompile, getDefaultLaunchMode(), options); } protected void run(boolean performCompile, LaunchMode mode, String... options) throws MavenInvocationException, FileNotFoundException { run(performCompile, mode, true, options); } protected void run(boolean performCompile, LaunchMode mode, boolean skipAnalytics, String... options) throws FileNotFoundException, MavenInvocationException { assertThat(testDir).isDirectory(); assertThatPortIsFree(); running = new RunningInvoker(testDir, false); final List<String> args = new ArrayList<>(3 + options.length); if (performCompile) { args.add("compile"); } args.add("quarkus:" + mode.getDefaultProfile()); if (skipAnalytics) { args.add("-Dquarkus.analytics.disabled=true"); } // If the test has set a different port, pass that on to the application if (getPort() != DEFAULT_PORT) { int port = getPort(); int testPort = getPort() + 1; args.add("-Dquarkus.http.port=" + port); args.add("-Dquarkus.http.test-port=" + testPort); } boolean hasDebugOptions = false; for (String option : options) { args.add(option); if (option.trim().startsWith("-Ddebug=") || option.trim().startsWith("-Dsuspend=")) { hasDebugOptions = true; } } if (!hasDebugOptions) { // if no explicit debug options have been specified, let's just disable debugging args.add("-Ddebug=false"); } //we need to limit the memory consumption, as we can have a lot of these processes //running at once, if they add default to 75% of total mem we can easily run out //of physical memory as they will consume way more than what they need instead of //just running GC args.add("-Djvm.args=-Xmx" + getAllowedHeapInMb() + "m"); running.execute(args, Map.of()); } private void assertThatPortIsFree() { try { // Call get(), which doesn't retry - otherwise, tests will go very slow devModeClient.get(); fail("The port " + getPort() + " appears to be in use before starting the test instance of Quarkus, so any tests will give unpredictable results."); } catch (IOException e) { // All good, we wanted this } } protected void runAndCheck(String... options) throws FileNotFoundException, MavenInvocationException { runAndCheck(true, options); } protected void runAndCheck(LaunchMode mode, String... options) throws FileNotFoundException, MavenInvocationException { runAndCheck(true, mode, options); } protected void runAndCheck(boolean performCompile, String... options) throws MavenInvocationException, FileNotFoundException { runAndCheck(performCompile, getDefaultLaunchMode(), options); } protected void runAndCheck(boolean performCompile, LaunchMode mode, String... options) throws FileNotFoundException, MavenInvocationException { run(performCompile, mode, options); String resp = devModeClient.getHttpResponse(); assertThat(resp).containsIgnoringCase("ready").containsIgnoringCase("application").containsIgnoringCase("org.acme") .containsIgnoringCase("1.0-SNAPSHOT"); String greeting = devModeClient.getHttpResponse("/app/hello"); assertThat(greeting).containsIgnoringCase("hello"); } protected void runAndExpectError() throws MavenInvocationException { assertThat(testDir).isDirectory(); running = new RunningInvoker(testDir, false); final Properties mvnRunProps = new Properties(); mvnRunProps.setProperty("debug", "false"); running.execute(Arrays.asList("compile", "quarkus:dev"), Map.of(), mvnRunProps); devModeClient.getHttpErrorResponse(); } protected void install(final File baseDir, final boolean performClean) throws Exception { final MavenProcessInvocationResult result = new RunningInvoker(baseDir, false) .execute(performClean ? List.of("clean", "install") : List.of("install"), Map.of()); final Process process = result.getProcess(); if (process == null) { if (result.getExecutionException() == null) { throw new IllegalStateException("Failed to build project"); } throw result.getExecutionException(); } process.waitFor(); } public String getHttpErrorResponse() { return devModeClient.getHttpErrorResponse(getBrokenReason()); } public String getHttpResponse() { return devModeClient.getHttpResponse(getBrokenReason()); } protected Supplier<String> getBrokenReason() { return () -> null; } }
RunAndCheckMojoTestBase
java
apache__logging-log4j2
log4j-core-test/src/test/java/org/apache/logging/log4j/core/appender/rolling/RollingAppenderSizeWithTimeTest.java
{ "start": 1494, "end": 3696 }
class ____ { private static final String CONFIG = "log4j-rolling-size-with-time.xml"; private static final String DIR = "target/rolling-size-test"; public static LoggerContextRule loggerContextRule = LoggerContextRule.createShutdownTimeoutLoggerContextRule(CONFIG); @Rule public RuleChain chain = loggerContextRule.withCleanFoldersRule(DIR); private Logger logger; @Before public void setUp() { this.logger = loggerContextRule.getLogger(RollingAppenderSizeWithTimeTest.class.getName()); } @Test public void testAppender() throws Exception { final List<String> messages = new ArrayList<>(); for (int i = 0; i < 5000; ++i) { final String message = "This is test message number " + i; messages.add(message); logger.debug(message); if (i % 100 == 0) { Thread.sleep(10); } } if (!loggerContextRule.getLoggerContext().stop(30, TimeUnit.SECONDS)) { System.err.println("Could not stop cleanly " + loggerContextRule + " for " + this); } final File dir = new File(DIR); assertTrue("Directory not created", dir.exists()); final File[] files = dir.listFiles(); assertNotNull(files); for (final File file : files) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try (final FileInputStream fis = new FileInputStream(file)) { try { IOUtils.copy(fis, baos); } catch (final Exception ex) { ex.printStackTrace(); fail("Unable to read " + file.getAbsolutePath()); } } final String text = new String(baos.toByteArray(), Charset.defaultCharset()); final String[] lines = text.split("[\\r\\n]+"); for (final String line : lines) { messages.remove(line); } } assertTrue("Log messages lost : " + messages.size(), messages.isEmpty()); assertTrue("Files not rolled : " + files.length, files.length > 2); } }
RollingAppenderSizeWithTimeTest
java
apache__camel
components/camel-flowable/src/test/java/org/apache/camel/component/flowable/FlowableRedeployChannelTest.java
{ "start": 1209, "end": 3539 }
class ____ extends CamelFlowableTestCase { @Test public void testUnregisterChannelModel() throws Exception { String deploymentId = deployProcessDefinition("process/start.bpmn20.xml"); try { eventRegistryEngineConfiguration.getEventRepositoryService().createDeployment() .addClasspathResource("channel/userChannel.channel") .addClasspathResource("event/userEvent.event") .deploy(); ObjectNode bodyNode = new ObjectMapper().createObjectNode(); bodyNode.put("name", "John Doe"); bodyNode.put("age", 23); Exchange exchange = context.getEndpoint("direct:start").createExchange(); exchange.getIn().setBody(bodyNode); template.send("direct:start", exchange); ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processDefinitionKey("camelProcess").singleResult(); assertNotNull(processInstance); assertEquals("John Doe", runtimeService.getVariable(processInstance.getId(), "name")); assertEquals(23, runtimeService.getVariable(processInstance.getId(), "age")); eventRegistryEngineConfiguration.getEventRepositoryService().createDeployment() .addClasspathResource("channel/userChannelUpdated.channel") .addClasspathResource("event/userEventUpdated.event") .deploy(); bodyNode = new ObjectMapper().createObjectNode(); bodyNode.put("name", "Jane Doe"); bodyNode.put("age", 28); bodyNode.put("address", "Main street 1"); assertEquals(null, context.hasEndpoint("direct:start")); assertEquals(1, runtimeService.createProcessInstanceQuery().processDefinitionKey("camelProcess").count()); exchange = context.getEndpoint("direct:startUpdated").createExchange(); exchange.getIn().setBody(bodyNode); template.send("direct:startUpdated", exchange); assertEquals(2, runtimeService.createProcessInstanceQuery().processDefinitionKey("camelProcess").count()); } finally { repositoryService.deleteDeployment(deploymentId, true); } } }
FlowableRedeployChannelTest
java
hibernate__hibernate-orm
hibernate-core/src/main/java/org/hibernate/Filter.java
{ "start": 1374, "end": 3712 }
interface ____ { /** * Get the name of this filter. * * @return This filter's name. */ String getName(); /** * Get the associated {@link FilterDefinition definition} of this * named filter. * * @return The filter definition * * @deprecated There is no plan to remove this operation, but its use * should be avoided since {@link FilterDefinition} is an * SPI type, and so this operation is a layer-breaker. */ @Deprecated(since = "6.2") FilterDefinition getFilterDefinition(); /** * Set the named parameter's value for this filter. * * @param name The parameter's name. * @param value The value to be applied. * @return This FilterImpl instance (for method chaining). */ Filter setParameter(String name, Object value); /** * Set the named parameter's value list for this filter. Used * in conjunction with IN-style filter criteria. * * @param name The parameter's name. * @param values The values to be expanded into an SQL IN list. * @return This FilterImpl instance (for method chaining). */ Filter setParameterList(String name, Collection<?> values); /** * Set the named parameter's value list for this filter. Used * in conjunction with IN-style filter criteria. * * @param name The parameter's name. * @param values The values to be expanded into an SQL IN list. * @return This FilterImpl instance (for method chaining). */ Filter setParameterList(String name, Object[] values); /** * Perform validation of the filter state. This is used to verify * the state of the filter after its enablement and before its use. * * @throws HibernateException If the state is not currently valid. */ void validate() throws HibernateException; /** * Get the associated {@link FilterDefinition autoEnabled} of this * named filter. * * @return The flag value */ boolean isAutoEnabled(); /** * Get the associated {@link FilterDefinition applyToLoadByKey} of this * named filter. * * @return The flag value */ boolean isAppliedToLoadByKey(); /** * Obtain the argument currently bound to the filter parameter * with the given name. * * @param name the name of the filter parameter * @return the value currently set * * @since 7 */ @Incubating Object getParameterValue(String name); }
Filter
java
apache__flink
flink-yarn-tests/src/test/java/org/apache/flink/yarn/util/TestHadoopModuleFactory.java
{ "start": 1256, "end": 1723 }
class ____ implements SecurityModuleFactory { public static Configuration hadoopConfiguration; @Override public SecurityModule createModule(SecurityConfiguration securityConfig) { if (hadoopConfiguration == null) { throw new IllegalStateException( "Cannot instantiate test module, hadoop config not set!"); } return new HadoopModule(securityConfig, hadoopConfiguration); } }
TestHadoopModuleFactory
java
quarkusio__quarkus
extensions/smallrye-graphql/deployment/src/test/java/io/quarkus/smallrye/graphql/deployment/ObjectScalarTest.java
{ "start": 1956, "end": 2079 }
class ____ { @Query public Object echo(Object input) { return input; } } }
ObjectApi
java
spring-projects__spring-boot
core/spring-boot-autoconfigure/src/test/java/org/springframework/boot/autoconfigure/condition/ConditionalOnPropertyTests.java
{ "start": 13971, "end": 14109 }
interface ____ { } @Configuration(proxyBeanMethods = false) @ConditionalOnMyFeatureWithAlias("my.feature") static
ConditionalOnMyFeature
java
quarkusio__quarkus
extensions/load-shedding/runtime/src/main/java/io/quarkus/load/shedding/runtime/LoadSheddingRuntimeConfig.java
{ "start": 374, "end": 1360 }
interface ____ { /** * Whether load shedding should be enabled. * Currently, this only applies to incoming HTTP requests. */ @WithDefault("true") boolean enabled(); /** * The maximum number of concurrent requests allowed. */ @WithDefault("1000") int maxLimit(); /** * The {@code alpha} factor of the Vegas overload detection algorithm. */ @WithDefault("3") int alphaFactor(); /** * The {@code beta} factor of the Vegas overload detection algorithm. */ @WithDefault("6") int betaFactor(); /** * The probe factor of the Vegas overload detection algorithm. */ @WithDefault("30.0") double probeFactor(); /** * The initial limit of concurrent requests allowed. */ @WithDefault("100") int initialLimit(); /** * Configuration of priority load shedding. */ PriorityLoadShedding priority(); @ConfigGroup
LoadSheddingRuntimeConfig
java
elastic__elasticsearch
x-pack/plugin/core/src/main/java/org/elasticsearch/xpack/core/action/SetUpgradeModeActionRequest.java
{ "start": 686, "end": 2242 }
class ____ extends AcknowledgedRequest<SetUpgradeModeActionRequest> implements ToXContentObject { private final boolean enabled; public SetUpgradeModeActionRequest(TimeValue masterNodeTimeout, TimeValue ackTimeout, boolean enabled) { super(masterNodeTimeout, ackTimeout); this.enabled = enabled; } public SetUpgradeModeActionRequest(StreamInput in) throws IOException { super(in); this.enabled = in.readBoolean(); } public boolean enabled() { return enabled; } @Override public void writeTo(StreamOutput out) throws IOException { super.writeTo(out); out.writeBoolean(enabled); } @Override public int hashCode() { return Objects.hash(masterNodeTimeout(), ackTimeout(), enabled); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || obj.getClass() != getClass()) { return false; } SetUpgradeModeActionRequest other = (SetUpgradeModeActionRequest) obj; return Objects.equals(masterNodeTimeout(), other.masterNodeTimeout()) && Objects.equals(ackTimeout(), other.ackTimeout()) && enabled == other.enabled(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field("enabled", enabled); builder.endObject(); return builder; } }
SetUpgradeModeActionRequest
java
apache__camel
dsl/camel-jbang/camel-jbang-core/src/main/java/org/apache/camel/dsl/jbang/core/commands/catalog/CatalogDoc.java
{ "start": 2538, "end": 13742 }
class ____ extends CamelCommand { @CommandLine.Parameters(description = "Name of kamelet, component, dataformat, or other Camel resource", arity = "1") String name; @CommandLine.Option(names = { "--camel-version" }, description = "To use a different Camel version than the default version") String camelVersion; @CommandLine.Option(names = { "--runtime" }, completionCandidates = RuntimeCompletionCandidates.class, converter = RuntimeTypeConverter.class, description = "Runtime (${COMPLETION-CANDIDATES})") RuntimeType runtime; @CommandLine.Option(names = { "--download" }, defaultValue = "true", description = "Whether to allow automatic downloading JAR dependencies (over the internet)") boolean download = true; @CommandLine.Option(names = { "--quarkus-version" }, description = "Quarkus Platform version", defaultValue = RuntimeType.QUARKUS_VERSION) String quarkusVersion; @CommandLine.Option(names = { "--quarkus-group-id" }, description = "Quarkus Platform Maven groupId", defaultValue = "io.quarkus.platform") String quarkusGroupId = "io.quarkus.platform"; @CommandLine.Option(names = { "--repo", "--repos" }, description = "Additional maven repositories for download on-demand (Use commas to separate multiple repositories)") String repos; @CommandLine.Option(names = { "--url" }, description = "Prints the link to the online documentation on the Camel website", defaultValue = "false") boolean url; @CommandLine.Option(names = { "--open-url" }, description = "Opens the online documentation form the Camel website in the web browser", defaultValue = "false") boolean openUrl; @CommandLine.Option(names = { "--filter" }, description = "Filter option listed in tables by name, description, or group") String filter; @CommandLine.Option(names = { "--header" }, description = "Whether to display component message headers", defaultValue = "false") boolean headers; @CommandLine.Option(names = { "--kamelets-version" }, description = "Apache Camel Kamelets version", defaultValue = RuntimeType.KAMELETS_VERSION) String kameletsVersion = RuntimeType.KAMELETS_VERSION; CamelCatalog catalog; public CatalogDoc(CamelJBangMain main) { super(main); } CamelCatalog loadCatalog() throws Exception { if (RuntimeType.springBoot == runtime) { return CatalogLoader.loadSpringBootCatalog(repos, camelVersion, download); } else if (RuntimeType.quarkus == runtime) { return CatalogLoader.loadQuarkusCatalog(repos, quarkusVersion, quarkusGroupId, download); } if (camelVersion == null) { return new DefaultCamelCatalog(true); } else { return CatalogLoader.loadCatalog(repos, camelVersion, download); } } @Override public Integer doCall() throws Exception { this.catalog = loadCatalog(); String prefix = StringHelper.before(name, ":"); if (prefix != null) { name = StringHelper.after(name, ":"); } // special for camel-main if ("main".equals(name)) { MainModel mm = catalog.mainModel(); if (mm != null) { docMain(mm); return 0; } } if (prefix == null || "kamelet".equals(prefix)) { KameletModel km = KameletCatalogHelper.loadKameletModel(name, kameletsVersion); if (km != null) { docKamelet(km); return 0; } } if (prefix == null || "component".equals(prefix)) { ComponentModel cm = catalog.componentModel(name); if (cm != null) { docComponent(cm); return 0; } } if (prefix == null || "dataformat".equals(prefix)) { DataFormatModel dm = catalog.dataFormatModel(name); if (dm != null) { docDataFormat(dm); return 0; } } if (prefix == null || "language".equals(prefix)) { LanguageModel lm = catalog.languageModel(name); if (lm != null) { docLanguage(lm); return 0; } } if (prefix == null || "other".equals(prefix)) { OtherModel om = catalog.otherModel(name); if (om != null) { docOther(om); return 0; } } if (prefix == null) { // guess if a kamelet List<String> suggestions; boolean kamelet = name.endsWith("-sink") || name.endsWith("-source") || name.endsWith("-action"); if (kamelet) { // kamelet names suggestions = SuggestSimilarHelper.didYouMean(KameletCatalogHelper.findKameletNames(kameletsVersion), name); } else { // assume its a component suggestions = SuggestSimilarHelper.didYouMean(findComponentNames(catalog), name); } if (!suggestions.isEmpty()) { String type = kamelet ? "kamelet" : "component"; printer().printf("Camel %s: %s not found. Did you mean? %s%n", type, name, String.join(", ", suggestions)); } else { printer().println("Camel resource: " + name + " not found"); } } else { List<String> suggestions = switch (prefix) { case "kamelet" -> SuggestSimilarHelper.didYouMean(KameletCatalogHelper.findKameletNames(kameletsVersion), name); case "component" -> SuggestSimilarHelper.didYouMean(findComponentNames(catalog), name); case "dataformat" -> SuggestSimilarHelper.didYouMean(catalog.findDataFormatNames(), name); case "language" -> SuggestSimilarHelper.didYouMean(catalog.findLanguageNames(), name); case "other" -> SuggestSimilarHelper.didYouMean(catalog.findOtherNames(), name); default -> List.of(); }; if (!suggestions.isEmpty()) { printer().printf("Camel %s: %s not found. Did you mean? %s%n", prefix, name, String.join(", ", suggestions)); } else { printer().printf("Camel %s: %s not found.%n", prefix, name); } } return 1; } private void docKamelet(KameletModel km) throws Exception { String link = websiteLink("kamelet", name, kameletsVersion); if (openUrl) { if (link != null) { Desktop.getDesktop().browse(new URI(link)); } return; } if (url) { if (link != null) { printer().println(link); } return; } printer().printf("Kamelet Name: %s%n", km.name); printer().printf("Kamelet Type: %s%n", km.type); printer().println("Support Level: " + km.supportLevel); printer().println(""); printer().printf("%s%n", km.description); printer().println(""); if (km.dependencies != null && !km.dependencies.isEmpty()) { printer().println(""); for (String dep : km.dependencies) { MavenGav gav = MavenGav.parseGav(dep); if ("camel-core".equals(gav.getArtifactId())) { // camel-core is implied so skip continue; } printer().println(" <dependency>"); printer().println(" <groupId>" + gav.getGroupId() + "</groupId>"); printer().println(" <artifactId>" + gav.getArtifactId() + "</artifactId>"); String v = gav.getVersion(); if (v == null && "org.apache.camel".equals(gav.getGroupId())) { v = catalog.getCatalogVersion(); } if (v != null) { printer().println(" <version>" + v + "</version>"); } if (gav.getScope() != null) { printer().println(" <scope>" + gav.getScope() + "</scope>"); } printer().println(" </dependency>"); } printer().println(""); } if (km.properties != null && !km.properties.isEmpty()) { var filtered = filterKameletOptions(filter, km.properties.values()); int total1 = km.properties.size(); var total2 = filtered.size(); if (total1 == total2) { printer().printf("The %s kamelet supports (total: %s) options, which are listed below.%n%n", km.name, total1); } else { printer().printf("The %s kamelet supports (total: %s match-filter: %s) options, which are listed below.%n%n", km.name, total1, total2); } printer().println(AsciiTable.getTable(AsciiTable.FANCY_ASCII, filtered, Arrays.asList( new Column().header("NAME").dataAlign(HorizontalAlign.LEFT).minWidth(20) .maxWidth(35, OverflowBehaviour.NEWLINE) .with(r -> r.name), new Column().header("DESCRIPTION").dataAlign(HorizontalAlign.LEFT).maxWidth(80, OverflowBehaviour.NEWLINE) .with(this::getDescription), new Column().header("DEFAULT").dataAlign(HorizontalAlign.LEFT).maxWidth(25, OverflowBehaviour.NEWLINE) .with(r -> r.defaultValue), new Column().header("TYPE").dataAlign(HorizontalAlign.LEFT).maxWidth(25, OverflowBehaviour.NEWLINE) .with(r -> r.type), new Column().header("EXAMPLE").dataAlign(HorizontalAlign.LEFT).maxWidth(40, OverflowBehaviour.NEWLINE) .with(r -> r.example)))); printer().println(""); } if (link != null) { printer().println(link); printer().println(""); } } private void docMain(MainModel mm) throws Exception { String link = websiteLink("other", name, catalog.getCatalogVersion()); if (openUrl) { if (link != null) { Desktop.getDesktop().browse(new URI(link)); } return; } if (url) { if (link != null) { printer().println(link); } return; } printer().printf("Name: %s%n", "main"); printer().printf("Since: %s%n", "3.0"); printer().println(""); printer().printf("%s%n", "This module is used for running Camel standalone via a main
CatalogDoc
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/auth/delegation/DelegationOperations.java
{ "start": 1112, "end": 1173 }
interface ____ extends AWSPolicyProvider { }
DelegationOperations
java
apache__camel
components/camel-spring-parent/camel-spring-xml/src/test/java/org/apache/camel/spring/processor/SpringRouteNodePrefixIdTest.java
{ "start": 1042, "end": 1314 }
class ____ extends RouteNodePrefixIdTest { @Override protected CamelContext createCamelContext() throws Exception { return createSpringCamelContext(this, "org/apache/camel/spring/processor/SpringRouteNodePrefixIdTest.xml"); } }
SpringRouteNodePrefixIdTest
java
apache__dubbo
dubbo-remoting/dubbo-remoting-api/src/main/java/org/apache/dubbo/remoting/exchange/Exchangers.java
{ "start": 1293, "end": 4580 }
class ____ { private Exchangers() {} public static ExchangeServer bind(String url, Replier<?> replier) throws RemotingException { return bind(URL.valueOf(url), replier); } public static ExchangeServer bind(URL url, Replier<?> replier) throws RemotingException { return bind(url, new ChannelHandlerAdapter(), replier); } public static ExchangeServer bind(String url, ChannelHandler handler, Replier<?> replier) throws RemotingException { return bind(URL.valueOf(url), handler, replier); } public static ExchangeServer bind(URL url, ChannelHandler handler, Replier<?> replier) throws RemotingException { return bind(url, new ExchangeHandlerDispatcher(url.getOrDefaultFrameworkModel(), replier, handler)); } public static ExchangeServer bind(String url, ExchangeHandler handler) throws RemotingException { return bind(URL.valueOf(url), handler); } public static ExchangeServer bind(URL url, ExchangeHandler handler) throws RemotingException { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handler == null) { throw new IllegalArgumentException("handler == null"); } url = url.addParameterIfAbsent(Constants.CODEC_KEY, "exchange"); return getExchanger(url).bind(url, handler); } public static ExchangeClient connect(String url) throws RemotingException { return connect(URL.valueOf(url)); } public static ExchangeClient connect(URL url) throws RemotingException { return connect(url, new ChannelHandlerAdapter(), null); } public static ExchangeClient connect(String url, Replier<?> replier) throws RemotingException { return connect(URL.valueOf(url), new ChannelHandlerAdapter(), replier); } public static ExchangeClient connect(URL url, Replier<?> replier) throws RemotingException { return connect(url, new ChannelHandlerAdapter(), replier); } public static ExchangeClient connect(String url, ChannelHandler handler, Replier<?> replier) throws RemotingException { return connect(URL.valueOf(url), handler, replier); } public static ExchangeClient connect(URL url, ChannelHandler handler, Replier<?> replier) throws RemotingException { return connect(url, new ExchangeHandlerDispatcher(url.getOrDefaultFrameworkModel(), replier, handler)); } public static ExchangeClient connect(String url, ExchangeHandler handler) throws RemotingException { return connect(URL.valueOf(url), handler); } public static ExchangeClient connect(URL url, ExchangeHandler handler) throws RemotingException { if (url == null) { throw new IllegalArgumentException("url == null"); } if (handler == null) { throw new IllegalArgumentException("handler == null"); } return getExchanger(url).connect(url, handler); } public static Exchanger getExchanger(URL url) { String type = url.getParameter(Constants.EXCHANGER_KEY, Constants.DEFAULT_EXCHANGER); return url.getOrDefaultFrameworkModel() .getExtensionLoader(Exchanger.class) .getExtension(type); } }
Exchangers
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/PlatformHttpEndpointBuilderFactory.java
{ "start": 1473, "end": 1609 }
interface ____ { /** * Builder for endpoint for the Platform HTTP component. */ public
PlatformHttpEndpointBuilderFactory
java
google__dagger
javatests/dagger/internal/codegen/ScopingValidationTest.java
{ "start": 17347, "end": 18445 }
interface ____ {", " SimpleType.A type();", "}"); CompilerTests.daggerCompiler( type, simpleScope, simpleScoped, singletonScopedA, singletonScopedB, scopeless) .compile( subject -> { subject.hasErrorCount(0); subject.hasWarningCount(0); }); } // Tests the following component hierarchy: // // @ScopeA // ComponentA // [SimpleType getSimpleType()] // / \ // / \ // @ScopeB @ScopeB // ComponentB1 ComponentB2 // \ [SimpleType getSimpleType()] // \ / // \ / // @ScopeC // ComponentC // [SimpleType getSimpleType()] @Test public void componentWithScopeCanDependOnMultipleScopedComponentsEvenDoingADiamond() { Source type = CompilerTests.javaSource( "test.SimpleType", "package test;", "", "import javax.inject.Inject;", "", "
SimpleScopedComponent
java
apache__hadoop
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestRollingUpgradeDowngrade.java
{ "start": 1515, "end": 4465 }
class ____ { /** * Downgrade option is already obsolete. It should throw exception. * @throws Exception */ @Test @Timeout(value = 300) public void testDowngrade() throws Exception { Assertions.assertThrows(IllegalArgumentException.class, () -> { final Configuration conf = new HdfsConfiguration(); MiniQJMHACluster cluster = null; final Path foo = new Path("/foo"); final Path bar = new Path("/bar"); try { cluster = new MiniQJMHACluster.Builder(conf).build(); MiniDFSCluster dfsCluster = cluster.getDfsCluster(); dfsCluster.waitActive(); // let NN1 tail editlog every 1s dfsCluster.getConfiguration(1).setInt( DFSConfigKeys.DFS_HA_TAILEDITS_PERIOD_KEY, 1); dfsCluster.restartNameNode(1); dfsCluster.transitionToActive(0); DistributedFileSystem dfs = dfsCluster.getFileSystem(0); dfs.mkdirs(foo); // start rolling upgrade RollingUpgradeInfo info = dfs .rollingUpgrade(RollingUpgradeAction.PREPARE); Assertions.assertTrue(info.isStarted()); dfs.mkdirs(bar); TestRollingUpgrade.queryForPreparation(dfs); dfs.close(); dfsCluster.restartNameNode(0, true, "-rollingUpgrade", "downgrade"); // Once downgraded, there should be no more fsimage for rollbacks. Assertions.assertFalse(dfsCluster.getNamesystem(0).getFSImage() .hasRollbackFSImage()); // shutdown NN1 dfsCluster.shutdownNameNode(1); dfsCluster.transitionToActive(0); dfs = dfsCluster.getFileSystem(0); Assertions.assertTrue(dfs.exists(foo)); Assertions.assertTrue(dfs.exists(bar)); } finally { if (cluster != null) { cluster.shutdown(); } } }); } /** * Ensure that restart namenode with downgrade option should throw exception * because it has been obsolete. */ @Test public void testRejectNewFsImage() throws IOException { Assertions.assertThrows(IllegalArgumentException.class, () -> { final Configuration conf = new Configuration(); MiniDFSCluster cluster = null; try { cluster = new MiniDFSCluster.Builder(conf).numDataNodes(0).build(); cluster.waitActive(); DistributedFileSystem fs = cluster.getFileSystem(); fs.setSafeMode(SafeModeAction.ENTER); fs.saveNamespace(); fs.setSafeMode(SafeModeAction.LEAVE); NNStorage storage = spy(cluster.getNameNode().getFSImage().getStorage()); int futureVersion = NameNodeLayoutVersion.CURRENT_LAYOUT_VERSION - 1; doReturn(futureVersion).when(storage).getServiceLayoutVersion(); storage.writeAll(); cluster.restartNameNode(0, true, "-rollingUpgrade", "downgrade"); } finally { if (cluster != null) { cluster.shutdown(); } } }); } }
TestRollingUpgradeDowngrade
java
netty__netty
handler/src/main/java/io/netty/handler/timeout/ReadTimeoutHandler.java
{ "start": 2137, "end": 3236 }
class ____ extends IdleStateHandler { private boolean closed; /** * Creates a new instance. * * @param timeoutSeconds * read timeout in seconds */ public ReadTimeoutHandler(int timeoutSeconds) { this(timeoutSeconds, TimeUnit.SECONDS); } /** * Creates a new instance. * * @param timeout * read timeout * @param unit * the {@link TimeUnit} of {@code timeout} */ public ReadTimeoutHandler(long timeout, TimeUnit unit) { super(timeout, 0, 0, unit); } @Override protected final void channelIdle(ChannelHandlerContext ctx, IdleStateEvent evt) throws Exception { assert evt.state() == IdleState.READER_IDLE; readTimedOut(ctx); } /** * Is called when a read timeout was detected. */ protected void readTimedOut(ChannelHandlerContext ctx) throws Exception { if (!closed) { ctx.fireExceptionCaught(ReadTimeoutException.INSTANCE); ctx.close(); closed = true; } } }
ReadTimeoutHandler
java
google__dagger
javatests/dagger/internal/codegen/ComponentProcessorTest.java
{ "start": 49469, "end": 50107 }
class ____", " extends LocalInjectMemberNoConstructor {", " @Inject", " ParentInjectMemberWithConstructor() {}", " }", "", " private ComponentProcessorTestClasses() {}", "}"); Source component = CompilerTests.javaSource( "test.TestComponent", "package test;", "", "import dagger.Component;", "import dagger.internal.codegen.ComponentProcessorTestClasses;", "", "@Component(modules = TestModule.class)", "
ParentInjectMemberWithConstructor
java
mybatis__mybatis-3
src/test/java/org/apache/ibatis/reflection/MetaObjectTest.java
{ "start": 1471, "end": 10723 }
class ____ { @Test void shouldGetAndSetField() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); meta.setValue("richField", "foo"); assertEquals("foo", meta.getValue("richField")); } @Test void shouldGetAndSetNestedField() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); meta.setValue("richType.richField", "foo"); assertEquals("foo", meta.getValue("richType.richField")); } @Test void shouldGetAndSetProperty() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); meta.setValue("richProperty", "foo"); assertEquals("foo", meta.getValue("richProperty")); } @Test void shouldGetAndSetNestedProperty() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); meta.setValue("richType.richProperty", "foo"); assertEquals("foo", meta.getValue("richType.richProperty")); } @Test void shouldGetAndSetMapPair() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); meta.setValue("richMap.key", "foo"); assertEquals("foo", meta.getValue("richMap.key")); } @Test void shouldGetAndSetMapPairUsingArraySyntax() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); meta.setValue("richMap[key]", "foo"); assertEquals("foo", meta.getValue("richMap[key]")); } @Test void shouldGetAndSetNestedMapPair() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); meta.setValue("richType.richMap.key", "foo"); assertEquals("foo", meta.getValue("richType.richMap.key")); } @Test void shouldGetAndSetNestedMapPairUsingArraySyntax() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); meta.setValue("richType.richMap[key]", "foo"); assertEquals("foo", meta.getValue("richType.richMap[key]")); } @Test void shouldGetAndSetListItem() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); meta.setValue("richList[0]", "foo"); assertEquals("foo", meta.getValue("richList[0]")); } @Test void shouldGetAndSetNestedListItem() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); meta.setValue("richType.richList[0]", "foo"); assertEquals("foo", meta.getValue("richType.richList[0]")); } @Test void shouldGetReadablePropertyNames() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); String[] readables = meta.getGetterNames(); assertEquals(5, readables.length); for (String readable : readables) { assertTrue(meta.hasGetter(readable)); assertTrue(meta.hasGetter("richType." + readable)); } assertTrue(meta.hasGetter("richType")); } @Test void shouldGetWriteablePropertyNames() { RichType rich = new RichType(); MetaObject meta = SystemMetaObject.forObject(rich); String[] writeables = meta.getSetterNames(); assertEquals(5, writeables.length); for (String writeable : writeables) { assertTrue(meta.hasSetter(writeable)); assertTrue(meta.hasSetter("richType." + writeable)); } assertTrue(meta.hasSetter("richType")); } @Test void shouldSetPropertyOfNullNestedProperty() { MetaObject richWithNull = SystemMetaObject.forObject(new RichType()); richWithNull.setValue("richType.richProperty", "foo"); assertEquals("foo", richWithNull.getValue("richType.richProperty")); } @Test void shouldSetPropertyOfNullNestedPropertyWithNull() { MetaObject richWithNull = SystemMetaObject.forObject(new RichType()); richWithNull.setValue("richType.richProperty", null); assertNull(richWithNull.getValue("richType.richProperty")); } @Test void shouldGetPropertyOfNullNestedProperty() { MetaObject richWithNull = SystemMetaObject.forObject(new RichType()); assertNull(richWithNull.getValue("richType.richProperty")); } @Test void shouldVerifyHasReadablePropertiesReturnedByGetReadablePropertyNames() { MetaObject object = SystemMetaObject.forObject(new Author()); for (String readable : object.getGetterNames()) { assertTrue(object.hasGetter(readable)); } } @Test void shouldVerifyHasWriteablePropertiesReturnedByGetWriteablePropertyNames() { MetaObject object = SystemMetaObject.forObject(new Author()); for (String writeable : object.getSetterNames()) { assertTrue(object.hasSetter(writeable)); } } @Test void shouldSetAndGetProperties() { MetaObject object = SystemMetaObject.forObject(new Author()); object.setValue("email", "test"); assertEquals("test", object.getValue("email")); } @Test void shouldVerifyPropertyTypes() { MetaObject object = SystemMetaObject.forObject(new Author()); assertEquals(6, object.getSetterNames().length); assertEquals(int.class, object.getGetterType("id")); assertEquals(String.class, object.getGetterType("username")); assertEquals(String.class, object.getGetterType("password")); assertEquals(String.class, object.getGetterType("email")); assertEquals(String.class, object.getGetterType("bio")); assertEquals(Section.class, object.getGetterType("favouriteSection")); } @Test void shouldDemonstrateDeeplyNestedMapProperties() { HashMap<String, String> map = new HashMap<>(); MetaObject metaMap = SystemMetaObject.forObject(map); assertTrue(metaMap.hasSetter("id")); assertTrue(metaMap.hasSetter("name.first")); assertTrue(metaMap.hasSetter("address.street")); assertFalse(metaMap.hasGetter("id")); assertFalse(metaMap.hasGetter("name.first")); assertFalse(metaMap.hasGetter("address.street")); metaMap.setValue("id", "100"); metaMap.setValue("name.first", "Clinton"); metaMap.setValue("name.last", "Begin"); metaMap.setValue("address.street", "1 Some Street"); metaMap.setValue("address.city", "This City"); metaMap.setValue("address.province", "A Province"); metaMap.setValue("address.postal_code", "1A3 4B6"); assertTrue(metaMap.hasGetter("id")); assertTrue(metaMap.hasGetter("name.first")); assertTrue(metaMap.hasGetter("address.street")); assertEquals(3, metaMap.getGetterNames().length); assertEquals(3, metaMap.getSetterNames().length); @SuppressWarnings("unchecked") Map<String, String> name = (Map<String, String>) metaMap.getValue("name"); @SuppressWarnings("unchecked") Map<String, String> address = (Map<String, String>) metaMap.getValue("address"); assertEquals("Clinton", name.get("first")); assertEquals("1 Some Street", address.get("street")); } @Test void shouldDemonstrateNullValueInMap() { HashMap<String, String> map = new HashMap<>(); MetaObject metaMap = SystemMetaObject.forObject(map); assertFalse(metaMap.hasGetter("phone.home")); metaMap.setValue("phone", null); assertTrue(metaMap.hasGetter("phone")); // hasGetter returns true if the parent exists and is null. assertTrue(metaMap.hasGetter("phone.home")); assertTrue(metaMap.hasGetter("phone.home.ext")); assertNull(metaMap.getValue("phone")); assertNull(metaMap.getValue("phone.home")); assertNull(metaMap.getValue("phone.home.ext")); metaMap.setValue("phone.office", "789"); assertFalse(metaMap.hasGetter("phone.home")); assertFalse(metaMap.hasGetter("phone.home.ext")); assertEquals("789", metaMap.getValue("phone.office")); assertNotNull(metaMap.getValue("phone")); assertNull(metaMap.getValue("phone.home")); } @Test void shouldNotUseObjectWrapperFactoryByDefault() { MetaObject meta = SystemMetaObject.forObject(new Author()); assertNotEquals(CustomBeanWrapper.class, meta.getObjectWrapper().getClass()); } @Test void shouldUseObjectWrapperFactoryWhenSet() { MetaObject meta = MetaObject.forObject(new Author(), SystemMetaObject.DEFAULT_OBJECT_FACTORY, new CustomBeanWrapperFactory(), new DefaultReflectorFactory()); assertEquals(CustomBeanWrapper.class, meta.getObjectWrapper().getClass()); // Make sure the old default factory is in place and still works meta = SystemMetaObject.forObject(new Author()); assertNotEquals(CustomBeanWrapper.class, meta.getObjectWrapper().getClass()); } @Test void shouldMethodHasGetterReturnTrueWhenListElementSet() { List<Object> param1 = new ArrayList<>(); param1.add("firstParam"); param1.add(222); param1.add(new Date()); Map<String, Object> parametersEmulation = new HashMap<>(); parametersEmulation.put("param1", param1); parametersEmulation.put("filterParams", param1); MetaObject meta = SystemMetaObject.forObject(parametersEmulation); assertEquals(param1.get(0), meta.getValue("filterParams[0]")); assertEquals(param1.get(1), meta.getValue("filterParams[1]")); assertEquals(param1.get(2), meta.getValue("filterParams[2]")); assertTrue(meta.hasGetter("filterParams[0]")); assertTrue(meta.hasGetter("filterParams[1]")); assertTrue(meta.hasGetter("filterParams[2]")); } }
MetaObjectTest
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-server-webmvc/src/main/java/org/springframework/cloud/gateway/server/mvc/filter/FrameworkRetryFilterFunctions.java
{ "start": 3975, "end": 5856 }
class ____ implements RetryPolicy { private final RetryFilterFunctions.RetryConfig config; private int attemptCount = 0; CompositeRetryPolicy(RetryFilterFunctions.RetryConfig config) { this.config = config; } @Override public boolean shouldRetry(Throwable throwable) { // If no throwable, don't retry if (throwable == null) { return false; } // Check if we've exceeded max attempts // Note: config.getRetries() represents max attempts (including initial // attempt) // attemptCount tracks the number of attempts made so far (0 = first attempt, // 1 = second attempt, etc.) // shouldRetry is called after each failed attempt, so: // - First failure: attemptCount = 0, we can retry (will become attempt 1) // - Second failure: attemptCount = 1, we can retry (will become attempt 2) // - Third failure: attemptCount = 2, we can retry (will become attempt 3) // - After third failure: attemptCount = 3, we've reached max attempts, stop // So if retries=3, we allow attempts 0, 1, 2 (3 total attempts) if (attemptCount >= config.getRetries()) { return false; } boolean shouldRetry = false; // Check if it's an HTTP status retry case if (throwable instanceof RetryFilterFunctions.RetryException retryException) { shouldRetry = isRetryableStatusCode(retryException.getResponse().statusCode(), config) && isRetryableMethod(retryException.getRequest().method(), config); } else { // Check exception-based retry shouldRetry = config.getExceptions() .stream() .anyMatch(exceptionClass -> exceptionClass.isInstance(throwable)); } // If we should retry based on exception/status, increment counter // The check above ensures we won't exceed max attempts if (shouldRetry) { attemptCount++; return true; } return false; } } }
CompositeRetryPolicy
java
apache__camel
components/camel-jpa/src/main/java/org/apache/camel/component/jpa/JpaComponent.java
{ "start": 4003, "end": 5434 }
class ____). */ public void setAliases(Map<String, Class<?>> aliases) { this.aliases = aliases; } public Map<String, Class<?>> getAliases() { return aliases; } ExecutorService getOrCreatePollingConsumerExecutorService() { lock.lock(); try { if (pollingConsumerExecutorService == null) { LOG.debug("Creating thread pool for JpaPollingConsumer to support polling using timeout"); pollingConsumerExecutorService = getCamelContext().getExecutorServiceManager().newDefaultThreadPool(this, "JpaPollingConsumer"); } return pollingConsumerExecutorService; } finally { lock.unlock(); } } // Implementation methods //------------------------------------------------------------------------- @Override protected Endpoint createEndpoint(String uri, String path, Map<String, Object> options) throws Exception { JpaEndpoint endpoint = new JpaEndpoint(uri, this); endpoint.setJoinTransaction(isJoinTransaction()); endpoint.setSharedEntityManager(isSharedEntityManager()); Map<String, Object> params = PropertiesHelper.extractProperties(options, "parameters.", true); if (!params.isEmpty()) { endpoint.setParameters(params); } // lets interpret the next string as an alias or
name
java
ReactiveX__RxJava
src/main/java/io/reactivex/rxjava3/core/Observable.java
{ "start": 8603, "end": 377733 }
class ____ loaded. * @return the default 'island' size or capacity-increment hint */ @CheckReturnValue public static int bufferSize() { return Flowable.bufferSize(); } /** * Combines a collection of source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of * the returned {@code ObservableSource}s each time an item is received from any of the returned {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * If the provided iterable of {@code ObservableSource}s is empty, the resulting sequence completes immediately without emitting * any items and without any calls to the combiner function. * * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the common base type of source values * @param <R> * the result type * @param sources * the collection of source {@code ObservableSource}s * @param combiner * the aggregation function used to combine the items emitted by the returned {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T, @NonNull R> Observable<R> combineLatest( @NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, @NonNull Function<? super Object[], ? extends R> combiner) { return combineLatest(sources, combiner, bufferSize()); } /** * Combines an {@link Iterable} of source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of * the returned {@code ObservableSource}s each time an item is received from any of the returned {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * If the provided {@code Iterable} of {@code ObservableSource}s is empty, the resulting sequence completes immediately without emitting * any items and without any calls to the combiner function. * * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the common base type of source values * @param <R> * the result type * @param sources * the collection of source {@code ObservableSource}s * @param combiner * the aggregation function used to combine the items emitted by the returned {@code ObservableSource}s * @param bufferSize * the expected number of row combination items to be buffered internally * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code combiner} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T, @NonNull R> Observable<R> combineLatest( @NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, @NonNull Function<? super Object[], ? extends R> combiner, int bufferSize) { Objects.requireNonNull(sources, "sources is null"); Objects.requireNonNull(combiner, "combiner is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); // the queue holds a pair of values so we need to double the capacity int s = bufferSize << 1; return RxJavaPlugins.onAssembly(new ObservableCombineLatest<>(null, sources, combiner, s, false)); } /** * Combines an array of source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of * the {@code ObservableSource}s each time an item is received from any of the returned {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * If the provided array of {@code ObservableSource}s is empty, the resulting sequence completes immediately without emitting * any items and without any calls to the combiner function. * * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatestArray} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the common base type of source values * @param <R> * the result type * @param sources * the collection of source {@code ObservableSource}s * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T, @NonNull R> Observable<R> combineLatestArray( @NonNull ObservableSource<? extends T>[] sources, @NonNull Function<? super Object[], ? extends R> combiner) { return combineLatestArray(sources, combiner, bufferSize()); } /** * Combines an array of source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of * the {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * If the provided array of {@code ObservableSource}s is empty, the resulting sequence completes immediately without emitting * any items and without any calls to the combiner function. * * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatestArray} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the common base type of source values * @param <R> * the result type * @param sources * the collection of source {@code ObservableSource}s * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @param bufferSize * the expected number of row combination items to be buffered internally * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code combiner} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T, @NonNull R> Observable<R> combineLatestArray( @NonNull ObservableSource<? extends T>[] sources, @NonNull Function<? super Object[], ? extends R> combiner, int bufferSize) { Objects.requireNonNull(sources, "sources is null"); if (sources.length == 0) { return empty(); } Objects.requireNonNull(combiner, "combiner is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); // the queue holds a pair of values so we need to double the capacity int s = bufferSize << 1; return RxJavaPlugins.onAssembly(new ObservableCombineLatest<>(sources, null, combiner, s, false)); } /** * Combines two source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of the * {@code ObservableSource}s each time an item is received from either of the {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the element type of the first source * @param <T2> the element type of the second source * @param <R> the combined output type * @param source1 * the first source {@code ObservableSource} * @param source2 * the second source {@code ObservableSource} * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull R> Observable<R> combineLatest( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull BiFunction<? super T1, ? super T2, ? extends R> combiner) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(combiner, "combiner is null"); return combineLatestArray(new ObservableSource[] { source1, source2 }, Functions.toFunction(combiner), bufferSize()); } /** * Combines three source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of the * {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the element type of the first source * @param <T2> the element type of the second source * @param <T3> the element type of the third source * @param <R> the combined output type * @param source1 * the first source {@code ObservableSource} * @param source2 * the second source {@code ObservableSource} * @param source3 * the third source {@code ObservableSource} * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull R> Observable<R> combineLatest( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull Function3<? super T1, ? super T2, ? super T3, ? extends R> combiner) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(combiner, "combiner is null"); return combineLatestArray(new ObservableSource[] { source1, source2, source3 }, Functions.toFunction(combiner), bufferSize()); } /** * Combines four source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of the * {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the element type of the first source * @param <T2> the element type of the second source * @param <T3> the element type of the third source * @param <T4> the element type of the fourth source * @param <R> the combined output type * @param source1 * the first source {@code ObservableSource} * @param source2 * the second source {@code ObservableSource} * @param source3 * the third source {@code ObservableSource} * @param source4 * the fourth source {@code ObservableSource} * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull R> Observable<R> combineLatest( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull Function4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> combiner) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(combiner, "combiner is null"); return combineLatestArray(new ObservableSource[] { source1, source2, source3, source4 }, Functions.toFunction(combiner), bufferSize()); } /** * Combines five source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of the * {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the element type of the first source * @param <T2> the element type of the second source * @param <T3> the element type of the third source * @param <T4> the element type of the fourth source * @param <T5> the element type of the fifth source * @param <R> the combined output type * @param source1 * the first source {@code ObservableSource} * @param source2 * the second source {@code ObservableSource} * @param source3 * the third source {@code ObservableSource} * @param source4 * the fourth source {@code ObservableSource} * @param source5 * the fifth source {@code ObservableSource} * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull R> Observable<R> combineLatest( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull ObservableSource<? extends T5> source5, @NonNull Function5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> combiner) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(combiner, "combiner is null"); return combineLatestArray(new ObservableSource[] { source1, source2, source3, source4, source5 }, Functions.toFunction(combiner), bufferSize()); } /** * Combines six source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of the * {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the element type of the first source * @param <T2> the element type of the second source * @param <T3> the element type of the third source * @param <T4> the element type of the fourth source * @param <T5> the element type of the fifth source * @param <T6> the element type of the sixth source * @param <R> the combined output type * @param source1 * the first source {@code ObservableSource} * @param source2 * the second source {@code ObservableSource} * @param source3 * the third source {@code ObservableSource} * @param source4 * the fourth source {@code ObservableSource} * @param source5 * the fifth source {@code ObservableSource} * @param source6 * the sixth source {@code ObservableSource} * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull R> Observable<R> combineLatest( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull ObservableSource<? extends T5> source5, @NonNull ObservableSource<? extends T6> source6, @NonNull Function6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> combiner) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(combiner, "combiner is null"); return combineLatestArray(new ObservableSource[] { source1, source2, source3, source4, source5, source6 }, Functions.toFunction(combiner), bufferSize()); } /** * Combines seven source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of the * {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the element type of the first source * @param <T2> the element type of the second source * @param <T3> the element type of the third source * @param <T4> the element type of the fourth source * @param <T5> the element type of the fifth source * @param <T6> the element type of the sixth source * @param <T7> the element type of the seventh source * @param <R> the combined output type * @param source1 * the first source {@code ObservableSource} * @param source2 * the second source {@code ObservableSource} * @param source3 * the third source {@code ObservableSource} * @param source4 * the fourth source {@code ObservableSource} * @param source5 * the fifth source {@code ObservableSource} * @param source6 * the sixth source {@code ObservableSource} * @param source7 * the seventh source {@code ObservableSource} * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6}, * {@code source7} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull T7, @NonNull R> Observable<R> combineLatest( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull ObservableSource<? extends T5> source5, @NonNull ObservableSource<? extends T6> source6, @NonNull ObservableSource<? extends T7> source7, @NonNull Function7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> combiner) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(source7, "source7 is null"); Objects.requireNonNull(combiner, "combiner is null"); return combineLatestArray(new ObservableSource[] { source1, source2, source3, source4, source5, source6, source7 }, Functions.toFunction(combiner), bufferSize()); } /** * Combines eight source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of the * {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the element type of the first source * @param <T2> the element type of the second source * @param <T3> the element type of the third source * @param <T4> the element type of the fourth source * @param <T5> the element type of the fifth source * @param <T6> the element type of the sixth source * @param <T7> the element type of the seventh source * @param <T8> the element type of the eighth source * @param <R> the combined output type * @param source1 * the first source {@code ObservableSource} * @param source2 * the second source {@code ObservableSource} * @param source3 * the third source {@code ObservableSource} * @param source4 * the fourth source {@code ObservableSource} * @param source5 * the fifth source {@code ObservableSource} * @param source6 * the sixth source {@code ObservableSource} * @param source7 * the seventh source {@code ObservableSource} * @param source8 * the eighth source {@code ObservableSource} * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6}, * {@code source7}, {@code source8} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull T7, @NonNull T8, @NonNull R> Observable<R> combineLatest( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull ObservableSource<? extends T5> source5, @NonNull ObservableSource<? extends T6> source6, @NonNull ObservableSource<? extends T7> source7, @NonNull ObservableSource<? extends T8> source8, @NonNull Function8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> combiner) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(source7, "source7 is null"); Objects.requireNonNull(source8, "source8 is null"); Objects.requireNonNull(combiner, "combiner is null"); return combineLatestArray(new ObservableSource[] { source1, source2, source3, source4, source5, source6, source7, source8 }, Functions.toFunction(combiner), bufferSize()); } /** * Combines nine source {@link ObservableSource}s by emitting an item that aggregates the latest values of each of the * {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatest.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the element type of the first source * @param <T2> the element type of the second source * @param <T3> the element type of the third source * @param <T4> the element type of the fourth source * @param <T5> the element type of the fifth source * @param <T6> the element type of the sixth source * @param <T7> the element type of the seventh source * @param <T8> the element type of the eighth source * @param <T9> the element type of the ninth source * @param <R> the combined output type * @param source1 * the first source {@code ObservableSource} * @param source2 * the second source {@code ObservableSource} * @param source3 * the third source {@code ObservableSource} * @param source4 * the fourth source {@code ObservableSource} * @param source5 * the fifth source {@code ObservableSource} * @param source6 * the sixth source {@code ObservableSource} * @param source7 * the seventh source {@code ObservableSource} * @param source8 * the eighth source {@code ObservableSource} * @param source9 * the ninth source {@code ObservableSource} * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6}, * {@code source7}, {@code source8}, {@code source9} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @SuppressWarnings("unchecked") @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull T7, @NonNull T8, @NonNull T9, @NonNull R> Observable<R> combineLatest( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull ObservableSource<? extends T5> source5, @NonNull ObservableSource<? extends T6> source6, @NonNull ObservableSource<? extends T7> source7, @NonNull ObservableSource<? extends T8> source8, @NonNull ObservableSource<? extends T9> source9, @NonNull Function9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> combiner) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(source7, "source7 is null"); Objects.requireNonNull(source8, "source8 is null"); Objects.requireNonNull(source9, "source9 is null"); Objects.requireNonNull(combiner, "combiner is null"); return combineLatestArray(new ObservableSource[] { source1, source2, source3, source4, source5, source6, source7, source8, source9 }, Functions.toFunction(combiner), bufferSize()); } /** * Combines an array of {@link ObservableSource}s by emitting an item that aggregates the latest values of each of * the {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatestDelayError.v3.png" alt=""> * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * If the provided array of {@code ObservableSource}s is empty, the resulting sequence completes immediately without emitting * any items and without any calls to the combiner function. * * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatestArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the common base type of source values * @param <R> * the result type * @param sources * the collection of source {@code ObservableSource}s * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T, @NonNull R> Observable<R> combineLatestArrayDelayError( @NonNull ObservableSource<? extends T>[] sources, @NonNull Function<? super Object[], ? extends R> combiner) { return combineLatestArrayDelayError(sources, combiner, bufferSize()); } /** * Combines an array of {@link ObservableSource}s by emitting an item that aggregates the latest values of each of * the {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function and delays any error from the sources until * all source {@code ObservableSource}s terminate. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * If the provided array of {@code ObservableSource}s is empty, the resulting sequence completes immediately without emitting * any items and without any calls to the combiner function. * * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatestDelayError.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatestArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the common base type of source values * @param <R> * the result type * @param sources * the collection of source {@code ObservableSource}s * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @param bufferSize * the expected number of row combination items to be buffered internally * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code combiner} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T, @NonNull R> Observable<R> combineLatestArrayDelayError(@NonNull ObservableSource<? extends T>[] sources, @NonNull Function<? super Object[], ? extends R> combiner, int bufferSize) { Objects.requireNonNull(sources, "sources is null"); Objects.requireNonNull(combiner, "combiner is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); if (sources.length == 0) { return empty(); } // the queue holds a pair of values so we need to double the capacity int s = bufferSize << 1; return RxJavaPlugins.onAssembly(new ObservableCombineLatest<>(sources, null, combiner, s, true)); } /** * Combines an {@link Iterable} of {@link ObservableSource}s by emitting an item that aggregates the latest values of each of * the {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function and delays any error from the sources until * all source {@code ObservableSource}s terminate. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * If the provided iterable of {@code ObservableSource}s is empty, the resulting sequence completes immediately without emitting * any items and without any calls to the combiner function. * * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatestDelayError.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatestDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the common base type of source values * @param <R> * the result type * @param sources * the {@code Iterable} of source {@code ObservableSource}s * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code combiner} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T, @NonNull R> Observable<R> combineLatestDelayError(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, @NonNull Function<? super Object[], ? extends R> combiner) { return combineLatestDelayError(sources, combiner, bufferSize()); } /** * Combines an {@link Iterable} of {@link ObservableSource}s by emitting an item that aggregates the latest values of each of * the {@code ObservableSource}s each time an item is received from any of the {@code ObservableSource}s, where this * aggregation is defined by a specified function and delays any error from the sources until * all source {@code ObservableSource}s terminate. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * <p> * If any of the sources never produces an item but only terminates (normally or with an error), the * resulting sequence terminates immediately (normally or with all the errors accumulated till that point). * If that input source is also synchronous, other sources after it will not be subscribed to. * <p> * If the provided iterable of {@code ObservableSource}s is empty, the resulting sequence completes immediately without emitting * any items and without any calls to the combiner function. * * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/combineLatestDelayError.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code combineLatestDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the common base type of source values * @param <R> * the result type * @param sources * the collection of source {@code ObservableSource}s * @param combiner * the aggregation function used to combine the items emitted by the {@code ObservableSource}s * @param bufferSize * the expected number of row combination items to be buffered internally * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code combiner} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/combinelatest.html">ReactiveX operators documentation: CombineLatest</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T, @NonNull R> Observable<R> combineLatestDelayError(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, @NonNull Function<? super Object[], ? extends R> combiner, int bufferSize) { Objects.requireNonNull(sources, "sources is null"); Objects.requireNonNull(combiner, "combiner is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); // the queue holds a pair of values so we need to double the capacity int s = bufferSize << 1; return RxJavaPlugins.onAssembly(new ObservableCombineLatest<>(null, sources, combiner, s, true)); } /** * Concatenates elements of each {@link ObservableSource} provided via an {@link Iterable} sequence into a single sequence * of elements without interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concat.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the common value type of the sources * @param sources the {@code Iterable} sequence of {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> concat(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources) { Objects.requireNonNull(sources, "sources is null"); return fromIterable(sources).concatMapDelayError((Function)Functions.identity(), false, bufferSize()); } /** * Returns an {@code Observable} that emits the items emitted by each of the {@link ObservableSource}s emitted by the * {@code ObservableSource}, one after the other, without interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concat.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * an {@code ObservableSource} that emits {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> concat(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources) { return concat(sources, bufferSize()); } /** * Returns an {@code Observable} that emits the items emitted by each of the {@link ObservableSource}s emitted by the outer * {@code ObservableSource}, one after the other, without interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concat.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * an {@code ObservableSource} that emits {@code ObservableSource}s * @param bufferSize * the number of inner {@code ObservableSource}s expected to be buffered. * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> concat(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources, int bufferSize) { Objects.requireNonNull(sources, "sources is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); return RxJavaPlugins.onAssembly(new ObservableConcatMap(sources, Functions.identity(), bufferSize, ErrorMode.IMMEDIATE)); } /** * Returns an {@code Observable} that emits the items emitted by two {@link ObservableSource}s, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concat.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param source1 * an {@code ObservableSource} to be concatenated * @param source2 * an {@code ObservableSource} to be concatenated * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1} or {@code source2} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> concat(@NonNull ObservableSource<? extends T> source1, ObservableSource<? extends T> source2) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); return concatArray(source1, source2); } /** * Returns an {@code Observable} that emits the items emitted by three {@link ObservableSource}s, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concat.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param source1 * an {@code ObservableSource} to be concatenated * @param source2 * an {@code ObservableSource} to be concatenated * @param source3 * an {@code ObservableSource} to be concatenated * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code source3} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> concat( @NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2, @NonNull ObservableSource<? extends T> source3) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); return concatArray(source1, source2, source3); } /** * Returns an {@code Observable} that emits the items emitted by four {@link ObservableSource}s, one after the other, without * interleaving them. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concat.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concat} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param source1 * an {@code ObservableSource} to be concatenated * @param source2 * an {@code ObservableSource} to be concatenated * @param source3 * an {@code ObservableSource} to be concatenated * @param source4 * an {@code ObservableSource} to be concatenated * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3} or {@code source4} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/concat.html">ReactiveX operators documentation: Concat</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> concat( @NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2, @NonNull ObservableSource<? extends T> source3, @NonNull ObservableSource<? extends T> source4) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); return concatArray(source1, source2, source3, source4); } /** * Concatenates a variable number of {@link ObservableSource} sources. * <p> * Note: named this way because of overload conflict with {@code concat(ObservableSource<ObservableSource>)} * <p> * <img width="640" height="290" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArray.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatArray} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param sources the array of sources * @param <T> the common base value type * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Observable<T> concatArray(@NonNull ObservableSource<? extends T>... sources) { Objects.requireNonNull(sources, "sources is null"); if (sources.length == 0) { return empty(); } if (sources.length == 1) { return wrap((ObservableSource<T>)sources[0]); } return RxJavaPlugins.onAssembly(new ObservableConcatMap(fromArray(sources), Functions.identity(), bufferSize(), ErrorMode.BOUNDARY)); } /** * Concatenates a variable number of {@link ObservableSource} sources and delays errors from any of them * till all terminate. * <p> * <img width="640" height="290" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArray.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param sources the array of sources * @param <T> the common base value type * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Observable<T> concatArrayDelayError(@NonNull ObservableSource<? extends T>... sources) { Objects.requireNonNull(sources, "sources is null"); if (sources.length == 0) { return empty(); } if (sources.length == 1) { @SuppressWarnings("unchecked") Observable<T> source = (Observable<T>)wrap(sources[0]); return source; } return concatDelayError(fromArray(sources)); } /** * Concatenates an array of {@link ObservableSource}s eagerly into a single stream of values. * <p> * <img width="640" height="411" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArrayEager.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * {@code ObservableSource}s. The operator buffers the values emitted by these {@code ObservableSource}s and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources an array of {@code ObservableSource}s that need to be eagerly concatenated * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @since 2.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SafeVarargs @NonNull public static <@NonNull T> Observable<T> concatArrayEager(@NonNull ObservableSource<? extends T>... sources) { return concatArrayEager(bufferSize(), bufferSize(), sources); } /** * Concatenates an array of {@link ObservableSource}s eagerly into a single stream of values. * <p> * <img width="640" height="495" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArrayEager.nn.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * {@code ObservableSource}s. The operator buffers the values emitted by these {@code ObservableSource}s and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources an array of {@code ObservableSource}s that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrent subscriptions at a time, {@link Integer#MAX_VALUE} * is interpreted as indication to subscribe to all sources at once * @param bufferSize the number of elements expected from each {@code ObservableSource} to be buffered * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} or {@code bufferSize} is non-positive * @since 2.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Observable<T> concatArrayEager(int maxConcurrency, int bufferSize, @NonNull ObservableSource<? extends T>... sources) { return fromArray(sources).concatMapEagerDelayError((Function)Functions.identity(), false, maxConcurrency, bufferSize); } /** * Concatenates an array of {@link ObservableSource}s eagerly into a single stream of values * and delaying any errors until all sources terminate. * <p> * <img width="640" height="354" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArrayEagerDelayError.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * {@code ObservableSource}s. The operator buffers the values emitted by these {@code ObservableSource}s * and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources an array of {@code ObservableSource}s that need to be eagerly concatenated * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @since 2.2.1 - experimental */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SafeVarargs @NonNull public static <@NonNull T> Observable<T> concatArrayEagerDelayError(@NonNull ObservableSource<? extends T>... sources) { return concatArrayEagerDelayError(bufferSize(), bufferSize(), sources); } /** * Concatenates an array of {@link ObservableSource}s eagerly into a single stream of values * and delaying any errors until all sources terminate. * <p> * <img width="640" height="460" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatArrayEagerDelayError.nn.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * {@code ObservableSource}s. The operator buffers the values emitted by these {@code ObservableSource}s * and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources an array of {@code ObservableSource}s that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrent subscriptions at a time, {@link Integer#MAX_VALUE} * is interpreted as indication to subscribe to all sources at once * @param bufferSize the number of elements expected from each {@code ObservableSource} to be buffered * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} or {@code bufferSize} is non-positive * @since 2.2.1 - experimental */ @SuppressWarnings({ "rawtypes", "unchecked" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Observable<T> concatArrayEagerDelayError(int maxConcurrency, int bufferSize, @NonNull ObservableSource<? extends T>... sources) { return fromArray(sources).concatMapEagerDelayError((Function)Functions.identity(), true, maxConcurrency, bufferSize); } /** * Concatenates the {@link Iterable} sequence of {@link ObservableSource}s into a single {@code Observable} sequence * by subscribing to each {@code ObservableSource}, one after the other, one at a time and delays any errors till * the all inner {@code ObservableSource}s terminate. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatDelayError.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources the {@code Iterable} sequence of {@code ObservableSource}s * @return the new {@code Observable} with the concatenating behavior * @throws NullPointerException if {@code sources} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> concatDelayError(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources) { Objects.requireNonNull(sources, "sources is null"); return concatDelayError(fromIterable(sources)); } /** * Concatenates the {@link ObservableSource} sequence of {@code ObservableSource}s into a single {@code Observable} sequence * by subscribing to each inner {@code ObservableSource}, one after the other, one at a time and delays any errors till the * all inner and the outer {@code ObservableSource}s terminate. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatDelayError.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources the {@code ObservableSource} sequence of {@code ObservableSource}s * @return the new {@code Observable} with the concatenating behavior * @throws NullPointerException if {@code sources} is {@code null} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> concatDelayError(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources) { return concatDelayError(sources, bufferSize(), true); } /** * Concatenates the {@link ObservableSource} sequence of {@code ObservableSource}s into a single sequence by subscribing to each inner {@code ObservableSource}, * one after the other, one at a time and delays any errors till the all inner and the outer {@code ObservableSource}s terminate. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/concatDelayError.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code concatDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources the {@code ObservableSource} sequence of {@code ObservableSource}s * @param bufferSize the number of inner {@code ObservableSource}s expected to be buffered * @param tillTheEnd if {@code true}, exceptions from the outer and all inner {@code ObservableSource}s are delayed to the end * if {@code false}, exception from the outer {@code ObservableSource} is delayed till the active {@code ObservableSource} terminates * @return the new {@code Observable} with the concatenating behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive */ @SuppressWarnings({ "rawtypes", "unchecked" }) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> concatDelayError(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources, int bufferSize, boolean tillTheEnd) { Objects.requireNonNull(sources, "sources is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize is null"); return RxJavaPlugins.onAssembly(new ObservableConcatMap(sources, Functions.identity(), bufferSize, tillTheEnd ? ErrorMode.END : ErrorMode.BOUNDARY)); } /** * Concatenates a sequence of {@link ObservableSource}s eagerly into a single stream of values. * <p> * <img width="640" height="422" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.concatEager.i.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * {@code ObservableSource}s. The operator buffers the values emitted by these {@code ObservableSource}s and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code ObservableSource}s that need to be eagerly concatenated * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @since 2.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> concatEager(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources) { return concatEager(sources, bufferSize(), bufferSize()); } /** * Concatenates a sequence of {@link ObservableSource}s eagerly into a single stream of values and * runs a limited number of inner sequences at once. * <p> * <img width="640" height="379" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.concatEager.in.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * {@code ObservableSource}s. The operator buffers the values emitted by these {@code ObservableSource}s and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code ObservableSource}s that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrently running inner {@code ObservableSource}s; {@link Integer#MAX_VALUE} * is interpreted as all inner {@code ObservableSource}s can be active at the same time * @param bufferSize the number of elements expected from each inner {@code ObservableSource} to be buffered * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} or {@code bufferSize} is non-positive * @since 2.0 */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> concatEager(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, int maxConcurrency, int bufferSize) { return fromIterable(sources).concatMapEagerDelayError((Function)Functions.identity(), false, maxConcurrency, bufferSize); } /** * Concatenates an {@link ObservableSource} sequence of {@code ObservableSource}s eagerly into a single stream of values. * <p> * <img width="640" height="495" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.concatEager.o.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source {@code ObservableSource}s as they are observed. The operator buffers the values emitted by these * {@code ObservableSource}s and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code ObservableSource}s that need to be eagerly concatenated * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @since 2.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> concatEager(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources) { return concatEager(sources, bufferSize(), bufferSize()); } /** * Concatenates an {@link ObservableSource} sequence of {@code ObservableSource}s eagerly into a single stream of values * and runs a limited number of inner sequences at once. * * <p> * <img width="640" height="442" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.concatEager.on.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source {@code ObservableSource}s as they are observed. The operator buffers the values emitted by these * {@code ObservableSource}s and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code ObservableSource}s that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrently running inner {@code ObservableSource}s; {@link Integer#MAX_VALUE} * is interpreted as all inner {@code ObservableSource}s can be active at the same time * @param bufferSize the number of inner {@code ObservableSource} expected to be buffered * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} or {@code bufferSize} is non-positive * @since 2.0 */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> concatEager(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources, int maxConcurrency, int bufferSize) { return wrap(sources).concatMapEager((Function)Functions.identity(), maxConcurrency, bufferSize); } /** * Concatenates a sequence of {@link ObservableSource}s eagerly into a single stream of values, * delaying errors until all the inner sequences terminate. * <p> * <img width="640" height="428" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.concatEagerDelayError.i.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * {@code ObservableSource}s. The operator buffers the values emitted by these {@code ObservableSource}s and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code ObservableSource}s that need to be eagerly concatenated * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @since 3.0.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> concatEagerDelayError(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources) { return concatEagerDelayError(sources, bufferSize(), bufferSize()); } /** * Concatenates a sequence of {@link ObservableSource}s eagerly into a single stream of values, * delaying errors until all the inner sequences terminate and runs a limited number of inner * sequences at once. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.concatEagerDelayError.in.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * {@code ObservableSource}s. The operator buffers the values emitted by these {@code ObservableSource}s and then drains them * in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code ObservableSource}s that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrently running inner {@code ObservableSource}s; {@link Integer#MAX_VALUE} * is interpreted as all inner {@code ObservableSource}s can be active at the same time * @param bufferSize the number of elements expected from each inner {@code ObservableSource} to be buffered * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} or {@code bufferSize} is non-positive * @since 3.0.0 */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> concatEagerDelayError(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, int maxConcurrency, int bufferSize) { return fromIterable(sources).concatMapEagerDelayError((Function)Functions.identity(), true, maxConcurrency, bufferSize); } /** * Concatenates an {@link ObservableSource} sequence of {@code ObservableSource}s eagerly into a single stream of values, * delaying errors until all the inner and the outer sequence terminate. * <p> * <img width="640" height="496" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.concatEagerDelayError.o.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source {@code ObservableSource}s as they are observed. The operator buffers the values emitted by these * {@code ObservableSource}s and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code ObservableSource}s that need to be eagerly concatenated * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @since 3.0.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> concatEagerDelayError(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources) { return concatEagerDelayError(sources, bufferSize(), bufferSize()); } /** * Concatenates an {@link ObservableSource} sequence of {@code ObservableSource}s eagerly into a single stream of values, * delaying errors until all the inner and the outer sequence terminate and runs a limited number of inner sequences at once. * <p> * <img width="640" height="421" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.concatEagerDelayError.on.png" alt=""> * <p> * Eager concatenation means that once a subscriber subscribes, this operator subscribes to all of the * emitted source {@code ObservableSource}s as they are observed. The operator buffers the values emitted by these * {@code ObservableSource}s and then drains them in order, each one after the previous one completes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This method does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type * @param sources a sequence of {@code ObservableSource}s that need to be eagerly concatenated * @param maxConcurrency the maximum number of concurrently running inner {@code ObservableSource}s; {@link Integer#MAX_VALUE} * is interpreted as all inner {@code ObservableSource}s can be active at the same time * @param bufferSize the number of inner {@code ObservableSource} expected to be buffered * @return the new {@code Observable} instance with the specified concatenation behavior * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} or {@code bufferSize} is non-positive * @since 3.0.0 */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> concatEagerDelayError(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources, int maxConcurrency, int bufferSize) { return wrap(sources).concatMapEagerDelayError((Function)Functions.identity(), true, maxConcurrency, bufferSize); } /** * Provides an API (via a cold {@code Observable}) that bridges the reactive world with the callback-style world. * <p> * Example: * <pre><code> * Observable.&lt;Event&gt;create(emitter -&gt; { * Callback listener = new Callback() { * &#64;Override * public void onEvent(Event e) { * emitter.onNext(e); * if (e.isLast()) { * emitter.onComplete(); * } * } * * &#64;Override * public void onFailure(Exception e) { * emitter.onError(e); * } * }; * * AutoCloseable c = api.someMethod(listener); * * emitter.setCancellable(c::close); * * }); * </code></pre> * <p> * Whenever an {@link Observer} subscribes to the returned {@code Observable}, the provided * {@link ObservableOnSubscribe} callback is invoked with a fresh instance of an {@link ObservableEmitter} * that will interact only with that specific {@code Observer}. If this {@code Observer} * disposes the flow (making {@link ObservableEmitter#isDisposed} return {@code true}), * other observers subscribed to the same returned {@code Observable} are not affected. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/create.v3.png" alt=""> * <p> * You should call the {@code ObservableEmitter}'s {@code onNext}, {@code onError} and {@code onComplete} methods in a serialized fashion. The * rest of its methods are thread-safe. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code create} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the element type * @param source the emitter that is called when an {@code Observer} subscribes to the returned {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source} is {@code null} * @see ObservableOnSubscribe * @see ObservableEmitter * @see Cancellable */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> create(@NonNull ObservableOnSubscribe<T> source) { Objects.requireNonNull(source, "source is null"); return RxJavaPlugins.onAssembly(new ObservableCreate<>(source)); } /** * Returns an {@code Observable} that calls an {@link ObservableSource} factory to create an {@code ObservableSource} for each new {@link Observer} * that subscribes. That is, for each subscriber, the actual {@code ObservableSource} that subscriber observes is * determined by the factory function. * <p> * <img width="640" height="340" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/defer.v3.png" alt=""> * <p> * The {@code defer} operator allows you to defer or delay emitting items from an {@code ObservableSource} until such time as an * {@code Observer} subscribes to the {@code ObservableSource}. This allows an {@code Observer} to easily obtain updates or a * refreshed version of the sequence. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code defer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param supplier * the {@code ObservableSource} factory function to invoke for each {@code Observer} that subscribes to the * resulting {@code Observable} * @param <T> * the type of the items emitted by the {@code ObservableSource} * @return the new {@code Observable} instance * @throws NullPointerException if {@code supplier} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/defer.html">ReactiveX operators documentation: Defer</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> defer(@NonNull Supplier<? extends @NonNull ObservableSource<? extends T>> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return RxJavaPlugins.onAssembly(new ObservableDefer<>(supplier)); } /** * Returns an {@code Observable} that emits no items to the {@link Observer} and immediately invokes its * {@link Observer#onComplete onComplete} method. * <p> * <img width="640" height="190" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/empty.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code empty} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the type of the items (ostensibly) emitted by the {@code Observable} * @return the shared {@code Observable} instance * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Empty</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @NonNull public static <@NonNull T> Observable<T> empty() { return RxJavaPlugins.onAssembly((Observable<T>) ObservableEmpty.INSTANCE); } /** * Returns an {@code Observable} that invokes an {@link Observer}'s {@link Observer#onError onError} method when the * {@code Observer} subscribes to it. * <p> * <img width="640" height="221" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/error.supplier.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param supplier * a {@link Supplier} factory to return a {@link Throwable} for each individual {@code Observer} * @param <T> * the type of the items (ostensibly) emitted by the {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code supplier} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> error(@NonNull Supplier<? extends @NonNull Throwable> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return RxJavaPlugins.onAssembly(new ObservableError<>(supplier)); } /** * Returns an {@code Observable} that invokes an {@link Observer}'s {@link Observer#onError onError} method when the * {@code Observer} subscribes to it. * <p> * <img width="640" height="221" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/error.item.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code error} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param throwable * the particular {@link Throwable} to pass to {@link Observer#onError onError} * @param <T> * the type of the items (ostensibly) emitted by the {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code throwable} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Throw</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> error(@NonNull Throwable throwable) { Objects.requireNonNull(throwable, "throwable is null"); return error(Functions.justSupplier(throwable)); } /** * Returns an {@code Observable} instance that runs the given {@link Action} for each {@link Observer} and * emits either its exception or simply completes. * <p> * <img width="640" height="287" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.fromAction.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromAction} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd> If the {@code Action} throws an exception, the respective {@link Throwable} is * delivered to the downstream via {@link Observer#onError(Throwable)}, * except when the downstream has canceled the resulting {@code Observable} source. * In this latter case, the {@code Throwable} is delivered to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. * </dd> * </dl> * @param <T> the target type * @param action the {@code Action} to run for each {@code Observer} * @return the new {@code Observable} instance * @throws NullPointerException if {@code action} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromAction(@NonNull Action action) { Objects.requireNonNull(action, "action is null"); return RxJavaPlugins.onAssembly(new ObservableFromAction<>(action)); } /** * Converts an array into an {@link ObservableSource} that emits the items in the array. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/from.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromArray} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param items * the array of elements * @param <T> * the type of items in the array and the type of items to be emitted by the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code items} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Observable<T> fromArray(@NonNull T... items) { Objects.requireNonNull(items, "items is null"); if (items.length == 0) { return empty(); } if (items.length == 1) { return just(items[0]); } return RxJavaPlugins.onAssembly(new ObservableFromArray<>(items)); } /** * Returns an {@code Observable} that, when an observer subscribes to it, invokes a function you specify and then * emits the value returned from that function. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromCallable.v3.png" alt=""> * <p> * This allows you to defer the execution of the function you specify until an observer subscribes to the * {@code Observable}. That is to say, it makes the function "lazy." * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCallable} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd> If the {@link Callable} throws an exception, the respective {@link Throwable} is * delivered to the downstream via {@link Observer#onError(Throwable)}, * except when the downstream has disposed the current {@code Observable} source. * In this latter case, the {@code Throwable} is delivered to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} as an {@link UndeliverableException}. * </dd> * </dl> * @param callable * a function, the execution of which should be deferred; {@code fromCallable} will invoke this * function only when an observer subscribes to the {@code Observable} that {@code fromCallable} returns * @param <T> * the type of the item returned by the {@code Callable} and emitted by the {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code callable} is {@code null} * @see #defer(Supplier) * @see #fromSupplier(Supplier) * @since 2.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromCallable(@NonNull Callable<? extends T> callable) { Objects.requireNonNull(callable, "callable is null"); return RxJavaPlugins.onAssembly(new ObservableFromCallable<>(callable)); } /** * Wraps a {@link CompletableSource} into an {@code Observable}. * <p> * <img width="640" height="278" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.fromCompletable.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromCompletable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the target type * @param completableSource the {@code CompletableSource} to convert from * @return the new {@code Observable} instance * @throws NullPointerException if {@code completableSource} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromCompletable(@NonNull CompletableSource completableSource) { Objects.requireNonNull(completableSource, "completableSource is null"); return RxJavaPlugins.onAssembly(new ObservableFromCompletable<>(completableSource)); } /** * Converts a {@link Future} into an {@code Observable}. * <p> * <img width="640" height="284" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromFuture.noarg.png" alt=""> * <p> * The operator calls {@link Future#get()}, which is a blocking method, on the subscription thread. * It is recommended applying {@link #subscribeOn(Scheduler)} to move this blocking wait to a * background thread, and if the {@link Scheduler} supports it, interrupt the wait when the flow * is disposed. * <p> * Unlike 1.x, disposing the {@code Observable} won't cancel the future. If necessary, one can use composition to achieve the * cancellation effect: {@code futureObservableSource.doOnDispose(() -> future.cancel(true));}. * <p> * Also note that this operator will consume a {@link CompletionStage}-based {@code Future} subclass (such as * {@link CompletableFuture}) in a blocking manner as well. Use the {@link #fromCompletionStage(CompletionStage)} * operator to convert and consume such sources in a non-blocking fashion instead. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromFuture} does not operate by default on a particular {@code Scheduler}.</dd> * </dl> * * @param future * the source {@code Future} * @param <T> * the type of object that the {@code Future} returns, and also the type of item to be emitted by * the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code future} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> * @see #fromCompletionStage(CompletionStage) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromFuture(@NonNull Future<? extends T> future) { Objects.requireNonNull(future, "future is null"); return RxJavaPlugins.onAssembly(new ObservableFromFuture<>(future, 0L, null)); } /** * Converts a {@link Future} into an {@code Observable}, with a timeout on the {@code Future}. * <p> * <img width="640" height="287" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromFuture.timeout.png" alt=""> * <p> * The operator calls {@link Future#get(long, TimeUnit)}, which is a blocking method, on the subscription thread. * It is recommended applying {@link #subscribeOn(Scheduler)} to move this blocking wait to a * background thread, and if the {@link Scheduler} supports it, interrupt the wait when the flow * is disposed. * <p> * Unlike 1.x, disposing the {@code Observable} won't cancel the future. If necessary, one can use composition to achieve the * cancellation effect: {@code futureObservableSource.doOnDispose(() -> future.cancel(true));}. * <p> * Also note that this operator will consume a {@link CompletionStage}-based {@code Future} subclass (such as * {@link CompletableFuture}) in a blocking manner as well. Use the {@link #fromCompletionStage(CompletionStage)} * operator to convert and consume such sources in a non-blocking fashion instead. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromFuture} does not operate by default on a particular {@code Scheduler}.</dd> * </dl> * * @param future * the source {@code Future} * @param timeout * the maximum time to wait before calling {@code get} * @param unit * the {@link TimeUnit} of the {@code timeout} argument * @param <T> * the type of object that the {@code Future} returns, and also the type of item to be emitted by * the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code future} or {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> * @see #fromCompletionStage(CompletionStage) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromFuture(@NonNull Future<? extends T> future, long timeout, @NonNull TimeUnit unit) { Objects.requireNonNull(future, "future is null"); Objects.requireNonNull(unit, "unit is null"); return RxJavaPlugins.onAssembly(new ObservableFromFuture<>(future, timeout, unit)); } /** * Converts an {@link Iterable} sequence into an {@code Observable} that emits the items in the sequence. * <p> * <img width="640" height="187" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromIterable.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromIterable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param source * the source {@code Iterable} sequence * @param <T> * the type of items in the {@code Iterable} sequence and the type of items to be emitted by the * resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/from.html">ReactiveX operators documentation: From</a> * @see #fromStream(Stream) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromIterable(@NonNull Iterable<? extends T> source) { Objects.requireNonNull(source, "source is null"); return RxJavaPlugins.onAssembly(new ObservableFromIterable<>(source)); } /** * Returns an {@code Observable} instance that when subscribed to, subscribes to the {@link MaybeSource} instance and * emits {@code onSuccess} as a single item or forwards any {@code onComplete} or * {@code onError} signal. * <p> * <img width="640" height="226" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.fromMaybe.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromMaybe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type of the {@code MaybeSource} element * @param maybe the {@code MaybeSource} instance to subscribe to, not {@code null} * @return the new {@code Observable} instance * @throws NullPointerException if {@code maybe} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromMaybe(@NonNull MaybeSource<T> maybe) { Objects.requireNonNull(maybe, "maybe is null"); return RxJavaPlugins.onAssembly(new MaybeToObservable<>(maybe)); } /** * Converts an arbitrary <em>Reactive Streams</em> {@link Publisher} into an {@code Observable}. * <p> * <img width="640" height="344" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/fromPublisher.o.png" alt=""> * <p> * The {@code Publisher} must follow the * <a href="https://github.com/reactive-streams/reactive-streams-jvm#reactive-streams">Reactive-Streams specification</a>. * Violating the specification may result in undefined behavior. * <p> * If possible, use {@link #create(ObservableOnSubscribe)} to create a * source-like {@code Observable} instead. * <p> * Note that even though {@code Publisher} appears to be a functional interface, it * is not recommended to implement it through a lambda as the specification requires * state management that is not achievable with a stateless lambda. * <dl> * <dt><b>Backpressure:</b></dt> * <dd>The source {@code publisher} is consumed in an unbounded fashion without applying any * backpressure to it.</dd> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromPublisher} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type of the flow * @param publisher the {@code Publisher} to convert * @return the new {@code Observable} instance * @throws NullPointerException if {@code publisher} is {@code null} * @see #create(ObservableOnSubscribe) */ @BackpressureSupport(BackpressureKind.UNBOUNDED_IN) @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromPublisher(@NonNull Publisher<? extends T> publisher) { Objects.requireNonNull(publisher, "publisher is null"); return RxJavaPlugins.onAssembly(new ObservableFromPublisher<>(publisher)); } /** * Returns an {@code Observable} instance that runs the given {@link Runnable} for each {@link Observer} and * emits either its unchecked exception or simply completes. * <p> * <img width="640" height="286" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.fromRunnable.png" alt=""> * <p> * If the code to be wrapped needs to throw a checked or more broader {@link Throwable} exception, that * exception has to be converted to an unchecked exception by the wrapped code itself. Alternatively, * use the {@link #fromAction(Action)} method which allows the wrapped code to throw any {@code Throwable} * exception and will signal it to observers as-is. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromRunnable} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd> If the {@code Runnable} throws an exception, the respective {@code Throwable} is * delivered to the downstream via {@link Observer#onError(Throwable)}, * except when the downstream has canceled the resulting {@code Observable} source. * In this latter case, the {@code Throwable} is delivered to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} as an {@link io.reactivex.rxjava3.exceptions.UndeliverableException UndeliverableException}. * </dd> * </dl> * @param <T> the target type * @param run the {@code Runnable} to run for each {@code Observer} * @return the new {@code Observable} instance * @throws NullPointerException if {@code run} is {@code null} * @since 3.0.0 * @see #fromAction(Action) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromRunnable(@NonNull Runnable run) { Objects.requireNonNull(run, "run is null"); return RxJavaPlugins.onAssembly(new ObservableFromRunnable<>(run)); } /** * Returns an {@code Observable} instance that when subscribed to, subscribes to the {@link SingleSource} instance and * emits {@code onSuccess} as a single item or forwards the {@code onError} signal. * <p> * <img width="640" height="341" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.fromSingle.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromSingle} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type of the {@code SingleSource} element * @param source the {@code SingleSource} instance to subscribe to, not {@code null} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source} is {@code null} * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromSingle(@NonNull SingleSource<T> source) { Objects.requireNonNull(source, "source is null"); return RxJavaPlugins.onAssembly(new SingleToObservable<>(source)); } /** * Returns an {@code Observable} that, when an observer subscribes to it, invokes a supplier function you specify and then * emits the value returned from that function. * <p> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.fromSupplier.v3.png" alt=""> * <p> * This allows you to defer the execution of the function you specify until an observer subscribes to the * {@code Observable}. That is to say, it makes the function "lazy." * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code fromSupplier} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd> If the {@link Supplier} throws an exception, the respective {@link Throwable} is * delivered to the downstream via {@link Observer#onError(Throwable)}, * except when the downstream has disposed the current {@code Observable} source. * In this latter case, the {@code Throwable} is delivered to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} as an {@link UndeliverableException}. * </dd> * </dl> * @param supplier * a function, the execution of which should be deferred; {@code fromSupplier} will invoke this * function only when an observer subscribes to the {@code Observable} that {@code fromSupplier} returns * @param <T> * the type of the item emitted by the {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code supplier} is {@code null} * @see #defer(Supplier) * @see #fromCallable(Callable) * @since 3.0.0 */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> fromSupplier(@NonNull Supplier<? extends T> supplier) { Objects.requireNonNull(supplier, "supplier is null"); return RxJavaPlugins.onAssembly(new ObservableFromSupplier<>(supplier)); } /** * Returns a cold, synchronous and stateless generator of values. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/generate.2.v3.png" alt=""> * <p> * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, * never concurrently and only while the function body is executing. Calling them from multiple threads * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code generate} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the generated value type * @param generator the {@link Consumer} called in a loop after a downstream {@link Observer} has * subscribed. The callback then should call {@code onNext}, {@code onError} or * {@code onComplete} to signal a value or a terminal event. Signaling multiple {@code onNext} * in a call will make the operator signal {@link IllegalStateException}. * @return the new {@code Observable} instance * @throws NullPointerException if {@code generator} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> generate(@NonNull Consumer<Emitter<T>> generator) { Objects.requireNonNull(generator, "generator is null"); return generate(Functions.nullSupplier(), ObservableInternalHelper.simpleGenerator(generator), Functions.emptyConsumer()); } /** * Returns a cold, synchronous and stateful generator of values. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/generate.2.v3.png" alt=""> * <p> * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, * never concurrently and only while the function body is executing. Calling them from multiple threads * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code generate} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <S> the type of the per-{@link Observer} state * @param <T> the generated value type * @param initialState the {@link Supplier} to generate the initial state for each {@code Observer} * @param generator the {@link BiConsumer} called in a loop after a downstream {@code Observer} has * subscribed. The callback then should call {@code onNext}, {@code onError} or * {@code onComplete} to signal a value or a terminal event. Signaling multiple {@code onNext} * in a call will make the operator signal {@link IllegalStateException}. * @return the new {@code Observable} instance * @throws NullPointerException if {@code initialState} or {@code generator} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T, @NonNull S> Observable<T> generate(@NonNull Supplier<S> initialState, @NonNull BiConsumer<S, Emitter<T>> generator) { Objects.requireNonNull(generator, "generator is null"); return generate(initialState, ObservableInternalHelper.simpleBiGenerator(generator), Functions.emptyConsumer()); } /** * Returns a cold, synchronous and stateful generator of values. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/generate.2.v3.png" alt=""> * <p> * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, * never concurrently and only while the function body is executing. Calling them from multiple threads * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code generate} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <S> the type of the per-{@link Observer} state * @param <T> the generated value type * @param initialState the {@link Supplier} to generate the initial state for each {@code Observer} * @param generator the {@link BiConsumer} called in a loop after a downstream {@code Observer} has * subscribed. The callback then should call {@code onNext}, {@code onError} or * {@code onComplete} to signal a value or a terminal event. Signaling multiple {@code onNext} * in a call will make the operator signal {@link IllegalStateException}. * @param disposeState the {@link Consumer} that is called with the current state when the generator * terminates the sequence or it gets disposed * @return the new {@code Observable} instance * @throws NullPointerException if {@code initialState}, {@code generator} or {@code disposeState} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T, @NonNull S> Observable<T> generate( @NonNull Supplier<S> initialState, @NonNull BiConsumer<S, Emitter<T>> generator, @NonNull Consumer<? super S> disposeState) { Objects.requireNonNull(generator, "generator is null"); return generate(initialState, ObservableInternalHelper.simpleBiGenerator(generator), disposeState); } /** * Returns a cold, synchronous and stateful generator of values. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/generate.2.v3.png" alt=""> * <p> * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, * never concurrently and only while the function body is executing. Calling them from multiple threads * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code generate} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <S> the type of the per-{@link Observer} state * @param <T> the generated value type * @param initialState the {@link Supplier} to generate the initial state for each {@code Observer} * @param generator the {@link BiConsumer} called in a loop after a downstream {@code Observer} has * subscribed. The callback then should call {@code onNext}, {@code onError} or * {@code onComplete} to signal a value or a terminal event and should return a (new) state for * the next invocation. Signaling multiple {@code onNext} * in a call will make the operator signal {@link IllegalStateException}. * @return the new {@code Observable} instance * @throws NullPointerException if {@code initialState} or {@code generator} is {@code null} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T, @NonNull S> Observable<T> generate(@NonNull Supplier<S> initialState, @NonNull BiFunction<S, Emitter<T>, S> generator) { return generate(initialState, generator, Functions.emptyConsumer()); } /** * Returns a cold, synchronous and stateful generator of values. * <p> * <img width="640" height="315" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/generate.2.v3.png" alt=""> * <p> * Note that the {@link Emitter#onNext}, {@link Emitter#onError} and * {@link Emitter#onComplete} methods provided to the function via the {@link Emitter} instance should be called synchronously, * never concurrently and only while the function body is executing. Calling them from multiple threads * or outside the function call is not supported and leads to an undefined behavior. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code generate} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <S> the type of the per-{@link Observer} state * @param <T> the generated value type * @param initialState the {@link Supplier} to generate the initial state for each {@code Observer} * @param generator the {@link BiConsumer} called in a loop after a downstream {@code Observer} has * subscribed. The callback then should call {@code onNext}, {@code onError} or * {@code onComplete} to signal a value or a terminal event and should return a (new) state for * the next invocation. Signaling multiple {@code onNext} * in a call will make the operator signal {@link IllegalStateException}. * @param disposeState the {@link Consumer} that is called with the current state when the generator * terminates the sequence or it gets disposed * @return the new {@code Observable} instance * @throws NullPointerException if {@code initialState}, {@code generator} or {@code disposeState} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T, @NonNull S> Observable<T> generate(@NonNull Supplier<S> initialState, @NonNull BiFunction<S, Emitter<T>, S> generator, @NonNull Consumer<? super S> disposeState) { Objects.requireNonNull(initialState, "initialState is null"); Objects.requireNonNull(generator, "generator is null"); Objects.requireNonNull(disposeState, "disposeState is null"); return RxJavaPlugins.onAssembly(new ObservableGenerate<>(initialState, generator, disposeState)); } /** * Returns an {@code Observable} that emits a {@code 0L} after the {@code initialDelay} and ever increasing numbers * after each {@code period} of time thereafter. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timer.p.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code interval} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param initialDelay * the initial delay time to wait before emitting the first value of 0L * @param period * the period of time between emissions of the subsequent numbers * @param unit * the time unit for both {@code initialDelay} and {@code period} * @return the new {@code Observable} instance * @see <a href="http://reactivex.io/documentation/operators/interval.html">ReactiveX operators documentation: Interval</a> * @throws NullPointerException if {@code unit} is {@code null} * @since 1.0.12 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public static Observable<Long> interval(long initialDelay, long period, @NonNull TimeUnit unit) { return interval(initialDelay, period, unit, Schedulers.computation()); } /** * Returns an {@code Observable} that emits a {@code 0L} after the {@code initialDelay} and ever increasing numbers * after each {@code period} of time thereafter, on a specified {@link Scheduler}. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timer.ps.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@code Scheduler} this operator will use.</dd> * </dl> * * @param initialDelay * the initial delay time to wait before emitting the first value of 0L * @param period * the period of time between emissions of the subsequent numbers * @param unit * the time unit for both {@code initialDelay} and {@code period} * @param scheduler * the {@code Scheduler} on which the waiting happens and items are emitted * @return the new {@code Observable} instance * @see <a href="http://reactivex.io/documentation/operators/interval.html">ReactiveX operators documentation: Interval</a> * @since 1.0.12 * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public static Observable<Long> interval(long initialDelay, long period, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new ObservableInterval(Math.max(0L, initialDelay), Math.max(0L, period), unit, scheduler)); } /** * Returns an {@code Observable} that emits a sequential number every specified interval of time. * <p> * <img width="640" height="195" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/interval.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code interval} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param period * the period size in time units (see below) * @param unit * time units to use for the interval size * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/interval.html">ReactiveX operators documentation: Interval</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public static Observable<Long> interval(long period, @NonNull TimeUnit unit) { return interval(period, period, unit, Schedulers.computation()); } /** * Returns an {@code Observable} that emits a sequential number every specified interval of time, on a * specified {@link Scheduler}. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/interval.s.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@code Scheduler} this operator will use.</dd> * </dl> * * @param period * the period size in time units (see below) * @param unit * time units to use for the interval size * @param scheduler * the {@code Scheduler} to use for scheduling the items * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/interval.html">ReactiveX operators documentation: Interval</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @NonNull public static Observable<Long> interval(long period, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { return interval(period, period, unit, scheduler); } /** * Signals a range of long values, the first after some initial delay and the rest periodically after. * <p> * The sequence completes immediately after the last value (start + count - 1) has been reached. * <p> * <img width="640" height="195" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/intervalRange.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code intervalRange} by default operates on the {@link Schedulers#computation() computation} {@link Scheduler}.</dd> * </dl> * @param start that start value of the range * @param count the number of values to emit in total, if zero, the operator emits an {@code onComplete} after the initial delay. * @param initialDelay the initial delay before signaling the first value (the start) * @param period the period between subsequent values * @param unit the unit of measure of the {@code initialDelay} and {@code period} amounts * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} is {@code null} * @throws IllegalArgumentException * if {@code count} is negative, or if {@code start} + {@code count} &minus; 1 exceeds * {@link Long#MAX_VALUE} * @see #range(int, int) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.COMPUTATION) public static Observable<Long> intervalRange(long start, long count, long initialDelay, long period, @NonNull TimeUnit unit) { return intervalRange(start, count, initialDelay, period, unit, Schedulers.computation()); } /** * Signals a range of long values, the first after some initial delay and the rest periodically after. * <p> * The sequence completes immediately after the last value (start + count - 1) has been reached. * <p> * <img width="640" height="195" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/intervalRange.s.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>you provide the {@link Scheduler}.</dd> * </dl> * @param start that start value of the range * @param count the number of values to emit in total, if zero, the operator emits an {@code onComplete} after the initial delay. * @param initialDelay the initial delay before signaling the first value (the start) * @param period the period between subsequent values * @param unit the unit of measure of the {@code initialDelay} and {@code period} amounts * @param scheduler the target scheduler where the values and terminal signals will be emitted * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @throws IllegalArgumentException * if {@code count} is negative, or if {@code start} + {@code count} &minus; 1 exceeds * {@link Long#MAX_VALUE} */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.CUSTOM) public static Observable<Long> intervalRange(long start, long count, long initialDelay, long period, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { if (count < 0) { throw new IllegalArgumentException("count >= 0 required but it was " + count); } if (count == 0L) { return Observable.<Long>empty().delay(initialDelay, unit, scheduler); } long end = start + (count - 1); if (start > 0 && end < 0) { throw new IllegalArgumentException("Overflow! start + count is bigger than Long.MAX_VALUE"); } Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new ObservableIntervalRange(start, end, Math.max(0L, initialDelay), Math.max(0L, period), unit, scheduler)); } /** * Returns an {@code Observable} that signals the given (constant reference) item and then completes. * <p> * <img width="640" height="290" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.item.png" alt=""> * <p> * Note that the item is taken and re-emitted as is and not computed by any means by {@code just}. Use {@link #fromCallable(Callable)} * to generate a single item on demand (when {@link Observer}s subscribe to it). * <p> * See the multi-parameter overloads of {@code just} to emit more than one (constant reference) items one after the other. * Use {@link #fromArray(Object...)} to emit an arbitrary number of items that are known upfront. * <p> * To emit the items of an {@link Iterable} sequence (such as a {@link java.util.List}), use {@link #fromIterable(Iterable)}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item * the item to emit * @param <T> * the type of that item * @return the new {@code Observable} instance * @throws NullPointerException if {@code item} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> * @see #just(Object, Object) * @see #fromCallable(Callable) * @see #fromArray(Object...) * @see #fromIterable(Iterable) */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> just(@NonNull T item) { Objects.requireNonNull(item, "item is null"); return RxJavaPlugins.onAssembly(new ObservableJust<>(item)); } /** * Converts two items into an {@code Observable} that emits those items. * <p> * <img width="640" height="186" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.2.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item1 * first item * @param item2 * second item * @param <T> * the type of these items * @return the new {@code Observable} instance * @throws NullPointerException if {@code item1} or {@code item2} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> just(@NonNull T item1, @NonNull T item2) { Objects.requireNonNull(item1, "item1 is null"); Objects.requireNonNull(item2, "item2 is null"); return fromArray(item1, item2); } /** * Converts three items into an {@code Observable} that emits those items. * <p> * <img width="640" height="186" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.3.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item1 * first item * @param item2 * second item * @param item3 * third item * @param <T> * the type of these items * @return the new {@code Observable} instance * @throws NullPointerException if {@code item1}, {@code item2} or {@code item3} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> just(@NonNull T item1, @NonNull T item2, @NonNull T item3) { Objects.requireNonNull(item1, "item1 is null"); Objects.requireNonNull(item2, "item2 is null"); Objects.requireNonNull(item3, "item3 is null"); return fromArray(item1, item2, item3); } /** * Converts four items into an {@code Observable} that emits those items. * <p> * <img width="640" height="186" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.4.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item1 * first item * @param item2 * second item * @param item3 * third item * @param item4 * fourth item * @param <T> * the type of these items * @return the new {@code Observable} instance * @throws NullPointerException if {@code item1}, {@code item2}, {@code item3} or {@code item4} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> just(@NonNull T item1, @NonNull T item2, @NonNull T item3, @NonNull T item4) { Objects.requireNonNull(item1, "item1 is null"); Objects.requireNonNull(item2, "item2 is null"); Objects.requireNonNull(item3, "item3 is null"); Objects.requireNonNull(item4, "item4 is null"); return fromArray(item1, item2, item3, item4); } /** * Converts five items into an {@code Observable} that emits those items. * <p> * <img width="640" height="186" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.5.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item1 * first item * @param item2 * second item * @param item3 * third item * @param item4 * fourth item * @param item5 * fifth item * @param <T> * the type of these items * @return the new {@code Observable} instance * @throws NullPointerException if {@code item1}, {@code item2}, {@code item3}, * {@code item4} or {@code item5} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> just(@NonNull T item1, @NonNull T item2, @NonNull T item3, @NonNull T item4, @NonNull T item5) { Objects.requireNonNull(item1, "item1 is null"); Objects.requireNonNull(item2, "item2 is null"); Objects.requireNonNull(item3, "item3 is null"); Objects.requireNonNull(item4, "item4 is null"); Objects.requireNonNull(item5, "item5 is null"); return fromArray(item1, item2, item3, item4, item5); } /** * Converts six items into an {@code Observable} that emits those items. * <p> * <img width="640" height="186" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.6.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item1 * first item * @param item2 * second item * @param item3 * third item * @param item4 * fourth item * @param item5 * fifth item * @param item6 * sixth item * @param <T> * the type of these items * @return the new {@code Observable} instance * @throws NullPointerException if {@code item1}, {@code item2}, {@code item3}, * {@code item4}, {@code item5} or {@code item6} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> just(@NonNull T item1, @NonNull T item2, @NonNull T item3, @NonNull T item4, @NonNull T item5, @NonNull T item6) { Objects.requireNonNull(item1, "item1 is null"); Objects.requireNonNull(item2, "item2 is null"); Objects.requireNonNull(item3, "item3 is null"); Objects.requireNonNull(item4, "item4 is null"); Objects.requireNonNull(item5, "item5 is null"); Objects.requireNonNull(item6, "item6 is null"); return fromArray(item1, item2, item3, item4, item5, item6); } /** * Converts seven items into an {@code Observable} that emits those items. * <p> * <img width="640" height="186" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.7.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item1 * first item * @param item2 * second item * @param item3 * third item * @param item4 * fourth item * @param item5 * fifth item * @param item6 * sixth item * @param item7 * seventh item * @param <T> * the type of these items * @return the new {@code Observable} instance * @throws NullPointerException if {@code item1}, {@code item2}, {@code item3}, * {@code item4}, {@code item5}, {@code item6} * or {@code item7} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> just(@NonNull T item1, @NonNull T item2, @NonNull T item3, @NonNull T item4, @NonNull T item5, @NonNull T item6, @NonNull T item7) { Objects.requireNonNull(item1, "item1 is null"); Objects.requireNonNull(item2, "item2 is null"); Objects.requireNonNull(item3, "item3 is null"); Objects.requireNonNull(item4, "item4 is null"); Objects.requireNonNull(item5, "item5 is null"); Objects.requireNonNull(item6, "item6 is null"); Objects.requireNonNull(item7, "item7 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7); } /** * Converts eight items into an {@code Observable} that emits those items. * <p> * <img width="640" height="186" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.8.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item1 * first item * @param item2 * second item * @param item3 * third item * @param item4 * fourth item * @param item5 * fifth item * @param item6 * sixth item * @param item7 * seventh item * @param item8 * eighth item * @param <T> * the type of these items * @return the new {@code Observable} instance * @throws NullPointerException if {@code item1}, {@code item2}, {@code item3}, * {@code item4}, {@code item5}, {@code item6} * {@code item7} or {@code item8} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> just(@NonNull T item1, @NonNull T item2, @NonNull T item3, @NonNull T item4, @NonNull T item5, @NonNull T item6, @NonNull T item7, @NonNull T item8) { Objects.requireNonNull(item1, "item1 is null"); Objects.requireNonNull(item2, "item2 is null"); Objects.requireNonNull(item3, "item3 is null"); Objects.requireNonNull(item4, "item4 is null"); Objects.requireNonNull(item5, "item5 is null"); Objects.requireNonNull(item6, "item6 is null"); Objects.requireNonNull(item7, "item7 is null"); Objects.requireNonNull(item8, "item8 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7, item8); } /** * Converts nine items into an {@code Observable} that emits those items. * <p> * <img width="640" height="186" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.9.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item1 * first item * @param item2 * second item * @param item3 * third item * @param item4 * fourth item * @param item5 * fifth item * @param item6 * sixth item * @param item7 * seventh item * @param item8 * eighth item * @param item9 * ninth item * @param <T> * the type of these items * @return the new {@code Observable} instance * @throws NullPointerException if {@code item1}, {@code item2}, {@code item3}, * {@code item4}, {@code item5}, {@code item6} * {@code item7}, {@code item8} or {@code item9} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> just(@NonNull T item1, @NonNull T item2, @NonNull T item3, @NonNull T item4, @NonNull T item5, @NonNull T item6, @NonNull T item7, @NonNull T item8, @NonNull T item9) { Objects.requireNonNull(item1, "item1 is null"); Objects.requireNonNull(item2, "item2 is null"); Objects.requireNonNull(item3, "item3 is null"); Objects.requireNonNull(item4, "item4 is null"); Objects.requireNonNull(item5, "item5 is null"); Objects.requireNonNull(item6, "item6 is null"); Objects.requireNonNull(item7, "item7 is null"); Objects.requireNonNull(item8, "item8 is null"); Objects.requireNonNull(item9, "item9 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7, item8, item9); } /** * Converts ten items into an {@code Observable} that emits those items. * <p> * <img width="640" height="186" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/just.10.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code just} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param item1 * first item * @param item2 * second item * @param item3 * third item * @param item4 * fourth item * @param item5 * fifth item * @param item6 * sixth item * @param item7 * seventh item * @param item8 * eighth item * @param item9 * ninth item * @param item10 * tenth item * @param <T> * the type of these items * @return the new {@code Observable} instance * @throws NullPointerException if {@code item1}, {@code item2}, {@code item3}, * {@code item4}, {@code item5}, {@code item6} * {@code item7}, {@code item8}, {@code item9} * or {@code item10} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/just.html">ReactiveX operators documentation: Just</a> */ @CheckReturnValue @NonNull @SchedulerSupport(SchedulerSupport.NONE) public static <@NonNull T> Observable<T> just(@NonNull T item1, @NonNull T item2, @NonNull T item3, @NonNull T item4, @NonNull T item5, @NonNull T item6, @NonNull T item7, @NonNull T item8, @NonNull T item9, @NonNull T item10) { Objects.requireNonNull(item1, "item1 is null"); Objects.requireNonNull(item2, "item2 is null"); Objects.requireNonNull(item3, "item3 is null"); Objects.requireNonNull(item4, "item4 is null"); Objects.requireNonNull(item5, "item5 is null"); Objects.requireNonNull(item6, "item6 is null"); Objects.requireNonNull(item7, "item7 is null"); Objects.requireNonNull(item8, "item8 is null"); Objects.requireNonNull(item9, "item9 is null"); Objects.requireNonNull(item10, "item10 is null"); return fromArray(item1, item2, item3, item4, item5, item6, item7, item8, item9, item10); } /** * Flattens an {@link Iterable} of {@link ObservableSource}s into one {@code Observable}, without any transformation, while limiting the * number of concurrent subscriptions to these {@code ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.v3.png" alt=""> * <p> * You can combine the items emitted by multiple {@code ObservableSource}s so that they appear as a single {@code ObservableSource}, by * using the {@code merge} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the returned {@code ObservableSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable, int, int)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common element base type * @param sources * the {@code Iterable} of {@code ObservableSource}s * @param maxConcurrency * the maximum number of {@code ObservableSource}s that may be subscribed to concurrently * @param bufferSize * the number of items expected from each inner {@code ObservableSource} to be buffered * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException * if {@code maxConcurrency} or {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeDelayError(Iterable, int, int) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> merge(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, int maxConcurrency, int bufferSize) { return fromIterable(sources).flatMap((Function)Functions.identity(), false, maxConcurrency, bufferSize); } /** * Flattens an array of {@link ObservableSource}s into one {@code Observable}, without any transformation, while limiting the * number of concurrent subscriptions to these {@code ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.v3.png" alt=""> * <p> * You can combine the items emitted by multiple {@code ObservableSource}s so that they appear as a single {@code ObservableSource}, by * using the {@code merge} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeArray} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the {@code ObservableSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeArrayDelayError(int, int, ObservableSource...)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common element base type * @param sources * the array of {@code ObservableSource}s * @param maxConcurrency * the maximum number of {@code ObservableSource}s that may be subscribed to concurrently * @param bufferSize * the number of items expected from each inner {@code ObservableSource} to be buffered * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException * if {@code maxConcurrency} or {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeArrayDelayError(int, int, ObservableSource...) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Observable<T> mergeArray(int maxConcurrency, int bufferSize, @NonNull ObservableSource<? extends T>... sources) { return fromArray(sources).flatMap((Function)Functions.identity(), false, maxConcurrency, bufferSize); } /** * Flattens an {@link Iterable} of {@link ObservableSource}s into one {@code Observable}, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.v3.png" alt=""> * <p> * You can combine the items emitted by multiple {@code ObservableSource}s so that they appear as a single {@code ObservableSource}, by * using the {@code merge} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the returned {@code ObservableSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common element base type * @param sources * the {@code Iterable} of {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeDelayError(Iterable) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> merge(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources) { return fromIterable(sources).flatMap((Function)Functions.identity()); } /** * Flattens an {@link Iterable} of {@link ObservableSource}s into one {@code Observable}, without any transformation, while limiting the * number of concurrent subscriptions to these {@code ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.v3.png" alt=""> * <p> * You can combine the items emitted by multiple {@code ObservableSource}s so that they appear as a single {@code ObservableSource}, by * using the {@code merge} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the returned {@code ObservableSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(Iterable, int)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common element base type * @param sources * the {@code Iterable} of {@code ObservableSource}s * @param maxConcurrency * the maximum number of {@code ObservableSource}s that may be subscribed to concurrently * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException * if {@code maxConcurrency} is less than or equal to 0 * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeDelayError(Iterable, int) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> merge(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, int maxConcurrency) { return fromIterable(sources).flatMap((Function)Functions.identity(), maxConcurrency); } /** * Flattens an {@link ObservableSource} that emits {@code ObservableSource}s into a single {@code Observable} that emits the items emitted by * those {@code ObservableSource}s, without any transformation. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.oo.v3.png" alt=""> * <p> * You can combine the items emitted by multiple {@code ObservableSource}s so that they appear as a single {@code ObservableSource}, by * using the {@code merge} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the returned {@code ObservableSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common element base type * @param sources * an {@code ObservableSource} that emits {@code ObservableSource}s * @return the new {@code Observable} instance * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @throws NullPointerException if {@code sources} is {@code null} * @see #mergeDelayError(ObservableSource) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) @NonNull public static <@NonNull T> Observable<T> merge(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources) { Objects.requireNonNull(sources, "sources is null"); return RxJavaPlugins.onAssembly(new ObservableFlatMap(sources, Functions.identity(), false, Integer.MAX_VALUE, bufferSize())); } /** * Flattens an {@link ObservableSource} that emits {@code ObservableSource}s into a single {@code Observable} that emits the items emitted by * those {@code ObservableSource}s, without any transformation, while limiting the maximum number of concurrent * subscriptions to these {@code ObservableSource}s. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.oo.v3.png" alt=""> * <p> * You can combine the items emitted by multiple {@code ObservableSource}s so that they appear as a single {@code ObservableSource}, by * using the {@code merge} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the returned {@code ObservableSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(ObservableSource, int)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common element base type * @param sources * an {@code ObservableSource} that emits {@code ObservableSource}s * @param maxConcurrency * the maximum number of {@code ObservableSource}s that may be subscribed to concurrently * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException * if {@code maxConcurrency} is non-positive * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @since 1.1.0 * @see #mergeDelayError(ObservableSource, int) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> merge(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources, int maxConcurrency) { Objects.requireNonNull(sources, "sources is null"); ObjectHelper.verifyPositive(maxConcurrency, "maxConcurrency"); return RxJavaPlugins.onAssembly(new ObservableFlatMap(sources, Functions.identity(), false, maxConcurrency, bufferSize())); } /** * Flattens two {@link ObservableSource}s into a single {@code Observable}, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.v3.png" alt=""> * <p> * You can combine items emitted by multiple {@code ObservableSource}s so that they appear as a single {@code ObservableSource}, by * using the {@code merge} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the {@code ObservableSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(ObservableSource, ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common element base type * @param source1 * an {@code ObservableSource} to be merged * @param source2 * an {@code ObservableSource} to be merged * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1} or {@code source2} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeDelayError(ObservableSource, ObservableSource) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> merge(@NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); return fromArray(source1, source2).flatMap((Function)Functions.identity(), false, 2); } /** * Flattens three {@link ObservableSource}s into a single {@code Observable}, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.v3.png" alt=""> * <p> * You can combine items emitted by multiple {@code ObservableSource}s so that they appear as a single {@code ObservableSource}, by * using the {@code merge} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the {@code ObservableSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(ObservableSource, ObservableSource, ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common element base type * @param source1 * an {@code ObservableSource} to be merged * @param source2 * an {@code ObservableSource} to be merged * @param source3 * an {@code ObservableSource} to be merged * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code source3} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeDelayError(ObservableSource, ObservableSource, ObservableSource) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> merge( @NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2, @NonNull ObservableSource<? extends T> source3) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); return fromArray(source1, source2, source3).flatMap((Function)Functions.identity(), false, 3); } /** * Flattens four {@link ObservableSource}s into a single {@code Observable}, without any transformation. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.v3.png" alt=""> * <p> * You can combine items emitted by multiple {@code ObservableSource}s so that they appear as a single {@code ObservableSource}, by * using the {@code merge} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code merge} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the {@code ObservableSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeDelayError(ObservableSource, ObservableSource, ObservableSource, ObservableSource)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common element base type * @param source1 * an {@code ObservableSource} to be merged * @param source2 * an {@code ObservableSource} to be merged * @param source3 * an {@code ObservableSource} to be merged * @param source4 * an {@code ObservableSource} to be merged * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3} or {@code source4} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeDelayError(ObservableSource, ObservableSource, ObservableSource, ObservableSource) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> merge( @NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2, @NonNull ObservableSource<? extends T> source3, @NonNull ObservableSource<? extends T> source4) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); return fromArray(source1, source2, source3, source4).flatMap((Function)Functions.identity(), false, 4); } /** * Flattens an array of {@link ObservableSource}s into one {@code Observable}, without any transformation. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/merge.io.v3.png" alt=""> * <p> * You can combine items emitted by multiple {@code ObservableSource}s so that they appear as a single {@code ObservableSource}, by * using the {@code merge} method. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeArray} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If any of the {@code ObservableSource}s signal a {@link Throwable} via {@code onError}, the resulting * {@code Observable} terminates with that {@code Throwable} and all other source {@code ObservableSource}s are disposed. * If more than one {@code ObservableSource} signals an error, the resulting {@code Observable} may terminate with the * first one's error or, depending on the concurrency of the sources, may terminate with a * {@link CompositeException} containing two or more of the various error signals. * {@code Throwable}s that didn't make into the composite will be sent (individually) to the global error handler via * {@link RxJavaPlugins#onError(Throwable)} method as {@link UndeliverableException} errors. Similarly, {@code Throwable}s * signaled by source(s) after the returned {@code Observable} has been disposed or terminated with a * (composite) error will be sent to the same global error handler. * Use {@link #mergeArrayDelayError(ObservableSource...)} to merge sources and terminate only when all source {@code ObservableSource}s * have completed or failed with an error. * </dd> * </dl> * * @param <T> the common element base type * @param sources * the array of {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @see #mergeArrayDelayError(ObservableSource...) */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Observable<T> mergeArray(@NonNull ObservableSource<? extends T>... sources) { return fromArray(sources).flatMap((Function)Functions.identity(), sources.length); } /** * Flattens an {@link Iterable} of {@link ObservableSource}s into one {@code Observable}, in a way that allows an {@link Observer} to receive all * successfully emitted items from each of the returned {@code ObservableSource}s without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(ObservableSource)} except that if any of the merged {@code ObservableSource}s notify of an * error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged {@code ObservableSource}s have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.v3.png" alt=""> * <p> * Even if multiple merged {@code ObservableSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its {@code Observer}s once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * the {@code Iterable} of {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> mergeDelayError(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources) { return fromIterable(sources).flatMap((Function)Functions.identity(), true); } /** * Flattens an {@link Iterable} of {@link ObservableSource}s into one {@code Observable}, in a way that allows an {@link Observer} to receive all * successfully emitted items from each of the returned {@code ObservableSource}s without being interrupted by an error * notification from one of them, while limiting the number of concurrent subscriptions to these {@code ObservableSource}s. * <p> * This behaves like {@link #merge(ObservableSource)} except that if any of the merged {@code ObservableSource}s notify of an * error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged {@code ObservableSource}s have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.v3.png" alt=""> * <p> * Even if multiple merged {@code ObservableSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its {@code Observer}s once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * the {@code Iterable} of {@code ObservableSource}s * @param maxConcurrency * the maximum number of {@code ObservableSource}s that may be subscribed to concurrently * @param bufferSize * the number of items expected from each inner {@code ObservableSource} to be buffered * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} or {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> mergeDelayError(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, int maxConcurrency, int bufferSize) { return fromIterable(sources).flatMap((Function)Functions.identity(), true, maxConcurrency, bufferSize); } /** * Flattens an array of {@link ObservableSource}s into one {@code Observable}, in a way that allows an {@link Observer} to receive all * successfully emitted items from each of the {@code ObservableSource}s without being interrupted by an error * notification from one of them, while limiting the number of concurrent subscriptions to these {@code ObservableSource}s. * <p> * This behaves like {@link #merge(ObservableSource)} except that if any of the merged {@code ObservableSource}s notify of an * error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged {@code ObservableSource}s have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.v3.png" alt=""> * <p> * Even if multiple merged {@code ObservableSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its {@code Observer}s once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * the array of {@code ObservableSource}s * @param maxConcurrency * the maximum number of {@code ObservableSource}s that may be subscribed to concurrently * @param bufferSize * the number of items expected from each inner {@code ObservableSource} to be buffered * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} or {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Observable<T> mergeArrayDelayError(int maxConcurrency, int bufferSize, @NonNull ObservableSource<? extends T>... sources) { return fromArray(sources).flatMap((Function)Functions.identity(), true, maxConcurrency, bufferSize); } /** * Flattens an {@link Iterable} of {@link ObservableSource}s into one {@code Observable}, in a way that allows an {@link Observer} to receive all * successfully emitted items from each of the returned {@code ObservableSource}s without being interrupted by an error * notification from one of them, while limiting the number of concurrent subscriptions to these {@code ObservableSource}s. * <p> * This behaves like {@link #merge(ObservableSource)} except that if any of the merged {@code ObservableSource}s notify of an * error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged {@code ObservableSource}s have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.v3.png" alt=""> * <p> * Even if multiple merged {@code ObservableSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its {@code Observer}s once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * the {@code Iterable} of {@code ObservableSource}s * @param maxConcurrency * the maximum number of {@code ObservableSource}s that may be subscribed to concurrently * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} is non-positive * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> mergeDelayError(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, int maxConcurrency) { return fromIterable(sources).flatMap((Function)Functions.identity(), true, maxConcurrency); } /** * Flattens an {@link ObservableSource} that emits {@code ObservableSource}s into one {@code Observable}, in a way that allows an {@link Observer} to * receive all successfully emitted items from all of the emitted {@code ObservableSource}s without being interrupted by * an error notification from one of them. * <p> * This behaves like {@link #merge(ObservableSource)} except that if any of the merged {@code ObservableSource}s notify of an * error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged {@code ObservableSource}s have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.v3.png" alt=""> * <p> * Even if multiple merged {@code ObservableSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its {@code Observer}s once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * an {@code ObservableSource} that emits {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings({ "unchecked", "rawtypes" }) @NonNull public static <@NonNull T> Observable<T> mergeDelayError(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources) { Objects.requireNonNull(sources, "sources is null"); return RxJavaPlugins.onAssembly(new ObservableFlatMap(sources, Functions.identity(), true, Integer.MAX_VALUE, bufferSize())); } /** * Flattens an {@link ObservableSource} that emits {@code ObservableSource}s into one {@code Observable}, in a way that allows an {@link Observer} to * receive all successfully emitted items from all of the emitted {@code ObservableSource}s without being interrupted by * an error notification from one of them, while limiting the * number of concurrent subscriptions to these {@code ObservableSource}s. * <p> * This behaves like {@link #merge(ObservableSource)} except that if any of the merged {@code ObservableSource}s notify of an * error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged {@code ObservableSource}s have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.v3.png" alt=""> * <p> * Even if multiple merged {@code ObservableSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its {@code Observer}s once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * an {@code ObservableSource} that emits {@code ObservableSource}s * @param maxConcurrency * the maximum number of {@code ObservableSource}s that may be subscribed to concurrently * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code maxConcurrency} is non-positive * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> * @since 2.0 */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> mergeDelayError(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources, int maxConcurrency) { Objects.requireNonNull(sources, "sources is null"); ObjectHelper.verifyPositive(maxConcurrency, "maxConcurrency"); return RxJavaPlugins.onAssembly(new ObservableFlatMap(sources, Functions.identity(), true, maxConcurrency, bufferSize())); } /** * Flattens two {@link ObservableSource}s into one {@code Observable}, in a way that allows an {@link Observer} to receive all * successfully emitted items from each of the {@code ObservableSource}s without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(ObservableSource, ObservableSource)} except that if any of the merged {@code ObservableSource}s * notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from * propagating that error notification until all of the merged {@code ObservableSource}s have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.v3.png" alt=""> * <p> * Even if both merged {@code ObservableSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its {@code Observer}s once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param source1 * an {@code ObservableSource} to be merged * @param source2 * an {@code ObservableSource} to be merged * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1} or {@code source2} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> mergeDelayError( @NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); return fromArray(source1, source2).flatMap((Function)Functions.identity(), true, 2); } /** * Flattens three {@link ObservableSource}s into one {@code Observable}, in a way that allows an {@link Observer} to receive all * successfully emitted items from all of the {@code ObservableSource}s without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(ObservableSource, ObservableSource, ObservableSource)} except that if any of the merged * {@code ObservableSource}s notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain * from propagating that error notification until all of the merged {@code ObservableSource}s have finished emitting * items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.v3.png" alt=""> * <p> * Even if multiple merged {@code ObservableSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its {@code Observer}s once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param source1 * an {@code ObservableSource} to be merged * @param source2 * an {@code ObservableSource} to be merged * @param source3 * an {@code ObservableSource} to be merged * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code source3} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> mergeDelayError( @NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2, @NonNull ObservableSource<? extends T> source3) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); return fromArray(source1, source2, source3).flatMap((Function)Functions.identity(), true, 3); } /** * Flattens four {@link ObservableSource}s into one {@code Observable}, in a way that allows an {@link Observer} to receive all * successfully emitted items from all of the {@code ObservableSource}s without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(ObservableSource, ObservableSource, ObservableSource, ObservableSource)} except that if any of * the merged {@code ObservableSource}s notify of an error via {@link Observer#onError onError}, {@code mergeDelayError} * will refrain from propagating that error notification until all of the merged {@code ObservableSource}s have finished * emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.v3.png" alt=""> * <p> * Even if multiple merged {@code ObservableSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its {@code Observer}s once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param source1 * an {@code ObservableSource} to be merged * @param source2 * an {@code ObservableSource} to be merged * @param source3 * an {@code ObservableSource} to be merged * @param source4 * an {@code ObservableSource} to be merged * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3} or {@code source4} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> mergeDelayError( @NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2, @NonNull ObservableSource<? extends T> source3, @NonNull ObservableSource<? extends T> source4) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); return fromArray(source1, source2, source3, source4).flatMap((Function)Functions.identity(), true, 4); } /** * Flattens an array of {@link ObservableSource}s into one {@code Observable}, in a way that allows an {@link Observer} to receive all * successfully emitted items from each of the {@code ObservableSource}s without being interrupted by an error * notification from one of them. * <p> * This behaves like {@link #merge(ObservableSource)} except that if any of the merged {@code ObservableSource}s notify of an * error via {@link Observer#onError onError}, {@code mergeDelayError} will refrain from propagating that * error notification until all of the merged {@code ObservableSource}s have finished emitting items. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/mergeDelayError.v3.png" alt=""> * <p> * Even if multiple merged {@code ObservableSource}s send {@code onError} notifications, {@code mergeDelayError} will only * invoke the {@code onError} method of its {@code Observer}s once. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code mergeArrayDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element base type * @param sources * the array of {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/merge.html">ReactiveX operators documentation: Merge</a> */ @SuppressWarnings({ "unchecked", "rawtypes" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull @SafeVarargs public static <@NonNull T> Observable<T> mergeArrayDelayError(@NonNull ObservableSource<? extends T>... sources) { return fromArray(sources).flatMap((Function)Functions.identity(), true, sources.length); } /** * Returns an {@code Observable} that never sends any items or notifications to an {@link Observer}. * <p> * <img width="640" height="185" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/never.v3.png" alt=""> * <p> * The returned {@code Observable} is useful primarily for testing purposes. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code never} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> * the type of items (not) emitted by the {@code Observable} * @return the shared {@code Observable} instance * @see <a href="http://reactivex.io/documentation/operators/empty-never-throw.html">ReactiveX operators documentation: Never</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SuppressWarnings("unchecked") @NonNull public static <@NonNull T> Observable<T> never() { return RxJavaPlugins.onAssembly((Observable<T>) ObservableNever.INSTANCE); } /** * Returns an {@code Observable} that emits a sequence of {@link Integer}s within a specified range. * <p> * <img width="640" height="195" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/range.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code range} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param start * the value of the first {@code Integer} in the sequence * @param count * the number of sequential {@code Integer}s to generate * @return the new {@code Observable} instance * @throws IllegalArgumentException * if {@code count} is negative, or if {@code start} + {@code count} &minus; 1 exceeds * {@link Integer#MAX_VALUE} * @see <a href="http://reactivex.io/documentation/operators/range.html">ReactiveX operators documentation: Range</a> * @see #rangeLong(long, long) * @see #intervalRange(long, long, long, long, TimeUnit) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static Observable<Integer> range(int start, int count) { if (count < 0) { throw new IllegalArgumentException("count >= 0 required but it was " + count); } if (count == 0) { return empty(); } if (count == 1) { return just(start); } if ((long)start + (count - 1) > Integer.MAX_VALUE) { throw new IllegalArgumentException("Integer overflow"); } return RxJavaPlugins.onAssembly(new ObservableRange(start, count)); } /** * Returns an {@code Observable} that emits a sequence of {@link Long}s within a specified range. * <p> * <img width="640" height="195" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/rangeLong.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code rangeLong} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param start * the value of the first {@code Long} in the sequence * @param count * the number of sequential {@code Long}s to generate * @return the new {@code Observable} instance * @throws IllegalArgumentException * if {@code count} is negative, or if {@code start} + {@code count} &minus; 1 exceeds * {@link Long#MAX_VALUE} * @see <a href="http://reactivex.io/documentation/operators/range.html">ReactiveX operators documentation: Range</a> * @see #intervalRange(long, long, long, long, TimeUnit) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static Observable<Long> rangeLong(long start, long count) { if (count < 0) { throw new IllegalArgumentException("count >= 0 required but it was " + count); } if (count == 0) { return empty(); } if (count == 1) { return just(start); } long end = start + (count - 1); if (start > 0 && end < 0) { throw new IllegalArgumentException("Overflow! start + count is bigger than Long.MAX_VALUE"); } return RxJavaPlugins.onAssembly(new ObservableRangeLong(start, count)); } /** * Returns a {@link Single} that emits a {@link Boolean} value that indicates whether two {@link ObservableSource} sequences are the * same by comparing the items emitted by each {@code ObservableSource} pairwise. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sequenceEqual.2.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequenceEqual} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param source1 * the first {@code ObservableSource} to compare * @param source2 * the second {@code ObservableSource} to compare * @param <T> * the type of items emitted by each {@code ObservableSource} * @return the new {@code Single} instance * @throws NullPointerException if {@code source1} or {@code source2} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Single<Boolean> sequenceEqual(@NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2) { return sequenceEqual(source1, source2, ObjectHelper.equalsPredicate(), bufferSize()); } /** * Returns a {@link Single} that emits a {@link Boolean} value that indicates whether two {@link ObservableSource} sequences are the * same by comparing the items emitted by each {@code ObservableSource} pairwise based on the results of a specified * equality function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sequenceEqual.2.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequenceEqual} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param source1 * the first {@code ObservableSource} to compare * @param source2 * the second {@code ObservableSource} to compare * @param isEqual * a function used to compare items emitted by each {@code ObservableSource} * @param <T> * the type of items emitted by each {@code ObservableSource} * @return the new {@code Single} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code isEqual} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Single<Boolean> sequenceEqual( @NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2, @NonNull BiPredicate<? super T, ? super T> isEqual) { return sequenceEqual(source1, source2, isEqual, bufferSize()); } /** * Returns a {@link Single} that emits a {@link Boolean} value that indicates whether two {@link ObservableSource} sequences are the * same by comparing the items emitted by each {@code ObservableSource} pairwise based on the results of a specified * equality function. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sequenceEqual.2.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequenceEqual} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param source1 * the first {@code ObservableSource} to compare * @param source2 * the second {@code ObservableSource} to compare * @param isEqual * a function used to compare items emitted by each {@code ObservableSource} * @param bufferSize * the number of items expected from the first and second source {@code ObservableSource} to be buffered * @param <T> * the type of items emitted by each {@code ObservableSource} * @return the new {@code Single} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code isEqual} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Single<Boolean> sequenceEqual( @NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2, @NonNull BiPredicate<? super T, ? super T> isEqual, int bufferSize) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(isEqual, "isEqual is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); return RxJavaPlugins.onAssembly(new ObservableSequenceEqualSingle<>(source1, source2, isEqual, bufferSize)); } /** * Returns a {@link Single} that emits a {@link Boolean} value that indicates whether two {@link ObservableSource} sequences are the * same by comparing the items emitted by each {@code ObservableSource} pairwise. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/sequenceEqual.2.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code sequenceEqual} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param source1 * the first {@code ObservableSource} to compare * @param source2 * the second {@code ObservableSource} to compare * @param bufferSize * the number of items expected from the first and second source {@code ObservableSource} to be buffered * @param <T> * the type of items emitted by each {@code ObservableSource} * @return the new {@code Single} instance * @throws NullPointerException if {@code source1} or {@code source2} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/sequenceequal.html">ReactiveX operators documentation: SequenceEqual</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Single<Boolean> sequenceEqual(@NonNull ObservableSource<? extends T> source1, @NonNull ObservableSource<? extends T> source2, int bufferSize) { return sequenceEqual(source1, source2, ObjectHelper.equalsPredicate(), bufferSize); } /** * Converts an {@link ObservableSource} that emits {@code ObservableSource}s into an {@code Observable} that emits the items emitted by the * most recently emitted of those {@code ObservableSource}s. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchDo.v3.png" alt=""> * <p> * {@code switchOnNext} subscribes to an {@code ObservableSource} that emits {@code ObservableSource}s. Each time it observes one of * these emitted {@code ObservableSource}s, the {@code ObservableSource} returned by {@code switchOnNext} begins emitting the items * emitted by that {@code ObservableSource}. When a new inner {@code ObservableSource} is emitted, {@code switchOnNext} stops emitting items * from the earlier-emitted {@code ObservableSource} and begins emitting items from the new one. * <p> * The resulting {@code Observable} completes if both the outer {@code ObservableSource} and the last inner {@code ObservableSource}, if any, complete. * If the outer {@code ObservableSource} signals an {@code onError}, the inner {@code ObservableSource} is disposed and the error delivered in-sequence. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchOnNext} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the item type * @param sources * the {@code ObservableSource} that emits {@code ObservableSource}s * @param bufferSize * the expected number of items to cache from the inner {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/switch.html">ReactiveX operators documentation: Switch</a> */ @SuppressWarnings({ "rawtypes", "unchecked" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> switchOnNext(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources, int bufferSize) { Objects.requireNonNull(sources, "sources is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); return RxJavaPlugins.onAssembly(new ObservableSwitchMap(sources, Functions.identity(), bufferSize, false)); } /** * Converts an {@link ObservableSource} that emits {@code ObservableSource}s into an {@code Observable} that emits the items emitted by the * most recently emitted of those {@code ObservableSource}s. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchDo.v3.png" alt=""> * <p> * {@code switchOnNext} subscribes to an {@code ObservableSource} that emits {@code ObservableSource}s. Each time it observes one of * these emitted {@code ObservableSource}s, the {@code ObservableSource} returned by {@code switchOnNext} begins emitting the items * emitted by that {@code ObservableSource}. When a new inner {@code ObservableSource} is emitted, {@code switchOnNext} stops emitting items * from the earlier-emitted {@code ObservableSource} and begins emitting items from the new one. * <p> * The resulting {@code Observable} completes if both the outer {@code ObservableSource} and the last inner {@code ObservableSource}, if any, complete. * If the outer {@code ObservableSource} signals an {@code onError}, the inner {@code ObservableSource} is disposed and the error delivered in-sequence. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchOnNext} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the item type * @param sources * the {@code ObservableSource} that emits {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/switch.html">ReactiveX operators documentation: Switch</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> switchOnNext(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources) { return switchOnNext(sources, bufferSize()); } /** * Converts an {@link ObservableSource} that emits {@code ObservableSource}s into an {@code Observable} that emits the items emitted by the * most recently emitted of those {@code ObservableSource}s and delays any exception until all {@code ObservableSource}s terminate. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchOnNextDelayError.v3.png" alt=""> * <p> * {@code switchOnNext} subscribes to an {@code ObservableSource} that emits {@code ObservableSource}s. Each time it observes one of * these emitted {@code ObservableSource}s, the {@code ObservableSource} returned by {@code switchOnNext} begins emitting the items * emitted by that {@code ObservableSource}. When a new inner {@code ObservableSource} is emitted, {@code switchOnNext} stops emitting items * from the earlier-emitted {@code ObservableSource} and begins emitting items from the new one. * <p> * The resulting {@code Observable} completes if both the main {@code ObservableSource} and the last inner {@code ObservableSource}, if any, complete. * If the main {@code ObservableSource} signals an {@code onError}, the termination of the last inner {@code ObservableSource} will emit that error as is * or wrapped into a {@link CompositeException} along with the other possible errors the former inner {@code ObservableSource}s signaled. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchOnNextDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the item type * @param sources * the {@code ObservableSource} that emits {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/switch.html">ReactiveX operators documentation: Switch</a> * @since 2.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> switchOnNextDelayError(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources) { return switchOnNextDelayError(sources, bufferSize()); } /** * Converts an {@link ObservableSource} that emits {@code ObservableSource}s into an {@code Observable} that emits the items emitted by the * most recently emitted of those {@code ObservableSource}s and delays any exception until all {@code ObservableSource}s terminate. * <p> * <img width="640" height="370" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/switchOnNextDelayError.v3.png" alt=""> * <p> * {@code switchOnNext} subscribes to an {@code ObservableSource} that emits {@code ObservableSource}s. Each time it observes one of * these emitted {@code ObservableSource}s, the {@code ObservableSource} returned by {@code switchOnNext} begins emitting the items * emitted by that {@code ObservableSource}. When a new inner {@code ObservableSource} is emitted, {@code switchOnNext} stops emitting items * from the earlier-emitted {@code ObservableSource} and begins emitting items from the new one. * <p> * The resulting {@code Observable} completes if both the main {@code ObservableSource} and the last inner {@code ObservableSource}, if any, complete. * If the main {@code ObservableSource} signals an {@code onError}, the termination of the last inner {@code ObservableSource} will emit that error as is * or wrapped into a {@link CompositeException} along with the other possible errors the former inner {@code ObservableSource}s signaled. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code switchOnNextDelayError} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the item type * @param sources * the {@code ObservableSource} that emits {@code ObservableSource}s * @param bufferSize * the expected number of items to cache from the inner {@code ObservableSource}s * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/switch.html">ReactiveX operators documentation: Switch</a> * @since 2.0 */ @SuppressWarnings({ "rawtypes", "unchecked" }) @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> switchOnNextDelayError(@NonNull ObservableSource<? extends ObservableSource<? extends T>> sources, int bufferSize) { Objects.requireNonNull(sources, "sources is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); return RxJavaPlugins.onAssembly(new ObservableSwitchMap(sources, Functions.identity(), bufferSize, true)); } /** * Returns an {@code Observable} that emits {@code 0L} after a specified delay, and then completes. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timer.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code timer} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param delay * the initial delay before emitting a single {@code 0L} * @param unit * time units to use for {@code delay} * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public static Observable<Long> timer(long delay, @NonNull TimeUnit unit) { return timer(delay, unit, Schedulers.computation()); } /** * Returns an {@code Observable} that emits {@code 0L} after a specified delay, on a specified {@link Scheduler}, and then * completes. * <p> * <img width="640" height="200" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/timer.s.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@code Scheduler} this operator will use.</dd> * </dl> * * @param delay * the initial delay before emitting a single 0L * @param unit * time units to use for {@code delay} * @param scheduler * the {@code Scheduler} to use for scheduling the item * @throws NullPointerException * if {@code unit} or {@code scheduler} is {@code null} * @return the new {@code Observable} instance * @see <a href="http://reactivex.io/documentation/operators/timer.html">ReactiveX operators documentation: Timer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @NonNull public static Observable<Long> timer(long delay, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); return RxJavaPlugins.onAssembly(new ObservableTimer(Math.max(delay, 0L), unit, scheduler)); } /** * Create an {@code Observable} by wrapping an {@link ObservableSource} <em>which has to be implemented according * to the {@code Observable} specification derived from the <b>Reactive Streams</b> specification by handling * disposal correctly; no safeguards are provided by the {@code Observable} itself</em>. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code unsafeCreate} by default doesn't operate on any particular {@link Scheduler}.</dd> * </dl> * @param <T> the value type emitted * @param onSubscribe the {@code ObservableSource} instance to wrap * @return the new {@code Observable} instance * @throws NullPointerException if {@code onSubscribe} is {@code null} * @throws IllegalArgumentException if the {@code onSubscribe} is already an {@code Observable}, use * {@link #wrap(ObservableSource)} in this case * @see #wrap(ObservableSource) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> unsafeCreate(@NonNull ObservableSource<T> onSubscribe) { Objects.requireNonNull(onSubscribe, "onSubscribe is null"); if (onSubscribe instanceof Observable) { throw new IllegalArgumentException("unsafeCreate(Observable) should be upgraded"); } return RxJavaPlugins.onAssembly(new ObservableFromUnsafeSource<>(onSubscribe)); } /** * Constructs an {@code Observable} that creates a dependent resource object, an {@link ObservableSource} with * that resource and calls the provided {@code resourceDisposer} function if this inner source terminates or the * downstream disposes the flow. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/using.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the element type of the generated {@code Observable} * @param <D> the type of the resource associated with the output sequence * @param resourceSupplier * the factory function to create a resource object that depends on the {@code ObservableSource} * @param sourceSupplier * the factory function to create an {@code ObservableSource} * @param resourceCleanup * the function that will dispose of the resource * @return the new {@code Observable} instance * @throws NullPointerException if {@code resourceSupplier}, {@code sourceSupplier} or {@code resourceCleanup} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/using.html">ReactiveX operators documentation: Using</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T, @NonNull D> Observable<T> using( @NonNull Supplier<? extends D> resourceSupplier, @NonNull Function<? super D, ? extends ObservableSource<? extends T>> sourceSupplier, @NonNull Consumer<? super D> resourceCleanup) { return using(resourceSupplier, sourceSupplier, resourceCleanup, true); } /** * Constructs an {@code Observable} that creates a dependent resource object, an {@link ObservableSource} with * that resource and calls the provided {@code disposer} function if this inner source terminates or the * downstream disposes the flow; doing it before these end-states have been reached if {@code eager == true}, after otherwise. * <p> * <img width="640" height="400" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/using.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code using} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the element type of the generated {@code ObservableSource} * @param <D> the type of the resource associated with the output sequence * @param resourceSupplier * the factory function to create a resource object that depends on the {@code ObservableSource} * @param sourceSupplier * the factory function to create an {@code ObservableSource} * @param resourceCleanup * the function that will dispose of the resource * @param eager * If {@code true}, the resource disposal will happen either on a {@code dispose()} call before the upstream is disposed * or just before the emission of a terminal event ({@code onComplete} or {@code onError}). * If {@code false}, the resource disposal will happen either on a {@code dispose()} call after the upstream is disposed * or just after the emission of a terminal event ({@code onComplete} or {@code onError}). * @return the new {@code Observable} instance * @throws NullPointerException if {@code resourceSupplier}, {@code sourceSupplier} and {@code resourceCleanup} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/using.html">ReactiveX operators documentation: Using</a> * @since 2.0 */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T, @NonNull D> Observable<T> using( @NonNull Supplier<? extends D> resourceSupplier, @NonNull Function<? super D, ? extends ObservableSource<? extends T>> sourceSupplier, @NonNull Consumer<? super D> resourceCleanup, boolean eager) { Objects.requireNonNull(resourceSupplier, "resourceSupplier is null"); Objects.requireNonNull(sourceSupplier, "sourceSupplier is null"); Objects.requireNonNull(resourceCleanup, "resourceCleanup is null"); return RxJavaPlugins.onAssembly(new ObservableUsing<T, D>(resourceSupplier, sourceSupplier, resourceCleanup, eager)); } /** * Wraps an {@link ObservableSource} into an {@code Observable} if not already an {@code Observable}. * * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code wrap} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the value type * @param source the {@code ObservableSource} instance to wrap or cast to {@code Observable} * @return the new {@code Observable} instance or the same as the source * @throws NullPointerException if {@code source} is {@code null} */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T> Observable<T> wrap(@NonNull ObservableSource<T> source) { Objects.requireNonNull(source, "source is null"); if (source instanceof Observable) { return RxJavaPlugins.onAssembly((Observable<T>)source); } return RxJavaPlugins.onAssembly(new ObservableFromUnsafeSource<>(source)); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * items emitted, in sequence, by an {@link Iterable} of other {@link ObservableSource}s. * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by each of the {@code ObservableSource}s; * the second item emitted by the resulting {@code Observable} will be the result of the function applied to the second * item emitted by each of those {@code ObservableSource}s; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@code onNext} as many times as * the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(Arrays.asList(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2)), (a) -&gt; a)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common value type * @param <R> the zipped result type * @param sources * an {@code Iterable} of source {@code ObservableSource}s * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results in * an item that will be emitted by the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T, @NonNull R> Observable<R> zip(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, @NonNull Function<? super Object[], ? extends R> zipper) { Objects.requireNonNull(zipper, "zipper is null"); Objects.requireNonNull(sources, "sources is null"); return RxJavaPlugins.onAssembly(new ObservableZip<>(null, sources, zipper, bufferSize(), false)); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * items emitted, in sequence, by an {@link Iterable} of other {@link ObservableSource}s. * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by each of the {@code ObservableSource}s; * the second item emitted by the resulting {@code Observable} will be the result of the function applied to the second * item emitted by each of those {@code ObservableSource}s; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@code onNext} as many times as * the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(Arrays.asList(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2)), (a) -&gt; a)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zipIterable.o.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * * @param sources * an {@code Iterable} of source {@code ObservableSource}s * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results in * an item that will be emitted by the resulting {@code Observable} * @param delayError * delay errors signaled by any of the {@code ObservableSource} until all {@code ObservableSource}s terminate * @param bufferSize * the number of elements expected from each source {@code ObservableSource} to be buffered * @param <T> the common source value type * @param <R> the zipped result type * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code zipper} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T, @NonNull R> Observable<R> zip(@NonNull Iterable<@NonNull ? extends ObservableSource<? extends T>> sources, @NonNull Function<? super Object[], ? extends R> zipper, boolean delayError, int bufferSize) { Objects.requireNonNull(zipper, "zipper is null"); Objects.requireNonNull(sources, "sources is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); return RxJavaPlugins.onAssembly(new ObservableZip<>(null, sources, zipper, bufferSize, delayError)); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * two items emitted, in sequence, by two other {@link ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by {@code o1} and the first item * emitted by {@code o2}; the second item emitted by the resulting {@code Observable} will be the result of the function * applied to the second item emitted by {@code o1} and the second item emitted by {@code o2}; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest * items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2), (a, b) -&gt; a + b)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <R> the zipped result type * @param source1 * the first source {@code ObservableSource} * @param source2 * a second source {@code ObservableSource} * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results * in an item that will be emitted by the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T1, @NonNull T2, @NonNull R> Observable<R> zip( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull BiFunction<? super T1, ? super T2, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), false, bufferSize(), source1, source2); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * two items emitted, in sequence, by two other {@link ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by {@code o1} and the first item * emitted by {@code o2}; the second item emitted by the resulting {@code Observable} will be the result of the function * applied to the second item emitted by {@code o1} and the second item emitted by {@code o2}; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest * items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2), (a, b) -&gt; a + b)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <R> the zipped result type * @param source1 * the first source {@code ObservableSource} * @param source2 * a second source {@code ObservableSource} * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results * in an item that will be emitted by the resulting {@code Observable} * @param delayError delay errors from any of the {@code ObservableSource}s till the other terminates * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T1, @NonNull T2, @NonNull R> Observable<R> zip( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull BiFunction<? super T1, ? super T2, ? extends R> zipper, boolean delayError) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), delayError, bufferSize(), source1, source2); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * two items emitted, in sequence, by two other {@link ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by {@code o1} and the first item * emitted by {@code o2}; the second item emitted by the resulting {@code Observable} will be the result of the function * applied to the second item emitted by {@code o1} and the second item emitted by {@code o2}; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest * items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2), (a, b) -&gt; a + b)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <R> the zipped result type * @param source1 * the first source {@code ObservableSource} * @param source2 * a second source {@code ObservableSource} * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results * in an item that will be emitted by the resulting {@code Observable} * @param delayError delay errors from any of the {@code ObservableSource}s till the other terminates * @param bufferSize the number of elements expected from each source {@code ObservableSource} to be buffered * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2} or {@code zipper} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T1, @NonNull T2, @NonNull R> Observable<R> zip( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull BiFunction<? super T1, ? super T2, ? extends R> zipper, boolean delayError, int bufferSize) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), delayError, bufferSize, source1, source2); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * three items emitted, in sequence, by three other {@link ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by {@code o1}, the first item * emitted by {@code o2}, and the first item emitted by {@code o3}; the second item emitted by the resulting * {@code Observable} will be the result of the function applied to the second item emitted by {@code o1}, the * second item emitted by {@code o2}, and the second item emitted by {@code o3}; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest * items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2), ..., (a, b, c) -&gt; a + b)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <R> the zipped result type * @param source1 * the first source {@code ObservableSource} * @param source2 * a second source {@code ObservableSource} * @param source3 * a third source {@code ObservableSource} * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results in * an item that will be emitted by the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull R> Observable<R> zip( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull Function3<? super T1, ? super T2, ? super T3, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), false, bufferSize(), source1, source2, source3); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * four items emitted, in sequence, by four other {@link ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by {@code o1}, the first item * emitted by {@code o2}, the first item emitted by {@code o3}, and the first item emitted by {@code 04}; * the second item emitted by the resulting {@code Observable} will be the result of the function applied to the second * item emitted by each of those {@code ObservableSource}s; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest * items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2), ..., (a, b, c, d) -&gt; a + b)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <R> the zipped result type * @param source1 * the first source {@code ObservableSource} * @param source2 * a second source {@code ObservableSource} * @param source3 * a third source {@code ObservableSource} * @param source4 * a fourth source {@code ObservableSource} * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results in * an item that will be emitted by the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull R> Observable<R> zip( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull Function4<? super T1, ? super T2, ? super T3, ? super T4, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), false, bufferSize(), source1, source2, source3, source4); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * five items emitted, in sequence, by five other {@link ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by {@code o1}, the first item * emitted by {@code o2}, the first item emitted by {@code o3}, the first item emitted by {@code o4}, and * the first item emitted by {@code o5}; the second item emitted by the resulting {@code Observable} will be the result of * the function applied to the second item emitted by each of those {@code ObservableSource}s; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest * items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2), ..., (a, b, c, d, e) -&gt; a + b)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <T5> the value type of the fifth source * @param <R> the zipped result type * @param source1 * the first source {@code ObservableSource} * @param source2 * a second source {@code ObservableSource} * @param source3 * a third source {@code ObservableSource} * @param source4 * a fourth source {@code ObservableSource} * @param source5 * a fifth source {@code ObservableSource} * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results in * an item that will be emitted by the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull R> Observable<R> zip( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull ObservableSource<? extends T5> source5, @NonNull Function5<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), false, bufferSize(), source1, source2, source3, source4, source5); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * six items emitted, in sequence, by six other {@link ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by each source {@code ObservableSource}, the * second item emitted by the resulting {@code Observable} will be the result of the function applied to the second item * emitted by each of those {@code ObservableSource}s, and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest * items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2), ..., (a, b, c, d, e, f) -&gt; a + b)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <T5> the value type of the fifth source * @param <T6> the value type of the sixth source * @param <R> the zipped result type * @param source1 * the first source {@code ObservableSource} * @param source2 * a second source {@code ObservableSource} * @param source3 * a third source {@code ObservableSource} * @param source4 * a fourth source {@code ObservableSource} * @param source5 * a fifth source {@code ObservableSource} * @param source6 * a sixth source {@code ObservableSource} * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results in * an item that will be emitted by the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull R> Observable<R> zip( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull ObservableSource<? extends T5> source5, @NonNull ObservableSource<? extends T6> source6, @NonNull Function6<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), false, bufferSize(), source1, source2, source3, source4, source5, source6); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * seven items emitted, in sequence, by seven other {@link ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by each source {@code ObservableSource}, the * second item emitted by the resulting {@code Observable} will be the result of the function applied to the second item * emitted by each of those {@code ObservableSource}s, and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest * items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2), ..., (a, b, c, d, e, f, g) -&gt; a + b)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <T5> the value type of the fifth source * @param <T6> the value type of the sixth source * @param <T7> the value type of the seventh source * @param <R> the zipped result type * @param source1 * the first source {@code ObservableSource} * @param source2 * a second source {@code ObservableSource} * @param source3 * a third source {@code ObservableSource} * @param source4 * a fourth source {@code ObservableSource} * @param source5 * a fifth source {@code ObservableSource} * @param source6 * a sixth source {@code ObservableSource} * @param source7 * a seventh source {@code ObservableSource} * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results in * an item that will be emitted by the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6}, * {@code source7} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull T7, @NonNull R> Observable<R> zip( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull ObservableSource<? extends T5> source5, @NonNull ObservableSource<? extends T6> source6, @NonNull ObservableSource<? extends T7> source7, @NonNull Function7<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(source7, "source7 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), false, bufferSize(), source1, source2, source3, source4, source5, source6, source7); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * eight items emitted, in sequence, by eight other {@link ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by each source {@code ObservableSource}, the * second item emitted by the resulting {@code Observable} will be the result of the function applied to the second item * emitted by each of those {@code ObservableSource}s, and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest * items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2), ..., (a, b, c, d, e, f, g, h) -&gt; a + b)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <T5> the value type of the fifth source * @param <T6> the value type of the sixth source * @param <T7> the value type of the seventh source * @param <T8> the value type of the eighth source * @param <R> the zipped result type * @param source1 * the first source {@code ObservableSource} * @param source2 * a second source {@code ObservableSource} * @param source3 * a third source {@code ObservableSource} * @param source4 * a fourth source {@code ObservableSource} * @param source5 * a fifth source {@code ObservableSource} * @param source6 * a sixth source {@code ObservableSource} * @param source7 * a seventh source {@code ObservableSource} * @param source8 * an eighth source {@code ObservableSource} * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results in * an item that will be emitted by the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6}, * {@code source7}, {@code source8} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull T7, @NonNull T8, @NonNull R> Observable<R> zip( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull ObservableSource<? extends T5> source5, @NonNull ObservableSource<? extends T6> source6, @NonNull ObservableSource<? extends T7> source7, @NonNull ObservableSource<? extends T8> source8, @NonNull Function8<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(source7, "source7 is null"); Objects.requireNonNull(source8, "source8 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), false, bufferSize(), source1, source2, source3, source4, source5, source6, source7, source8); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * nine items emitted, in sequence, by nine other {@link ObservableSource}s. * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zip.v3.png" alt=""> * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by each source {@code ObservableSource}, the * second item emitted by the resulting {@code Observable} will be the result of the function applied to the second item * emitted by each of those {@code ObservableSource}s, and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@link Observer#onNext onNext} * as many times as the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest * items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2), ..., (a, b, c, d, e, f, g, h, i) -&gt; a + b)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zip} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T1> the value type of the first source * @param <T2> the value type of the second source * @param <T3> the value type of the third source * @param <T4> the value type of the fourth source * @param <T5> the value type of the fifth source * @param <T6> the value type of the sixth source * @param <T7> the value type of the seventh source * @param <T8> the value type of the eighth source * @param <T9> the value type of the ninth source * @param <R> the zipped result type * @param source1 * the first source {@code ObservableSource} * @param source2 * a second source {@code ObservableSource} * @param source3 * a third source {@code ObservableSource} * @param source4 * a fourth source {@code ObservableSource} * @param source5 * a fifth source {@code ObservableSource} * @param source6 * a sixth source {@code ObservableSource} * @param source7 * a seventh source {@code ObservableSource} * @param source8 * an eighth source {@code ObservableSource} * @param source9 * a ninth source {@code ObservableSource} * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results in * an item that will be emitted by the resulting {@code Observable} * @return the new {@code Observable} instance * @throws NullPointerException if {@code source1}, {@code source2}, {@code source3}, * {@code source4}, {@code source5}, {@code source6}, * {@code source7}, {@code source8}, {@code source9} or {@code zipper} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public static <@NonNull T1, @NonNull T2, @NonNull T3, @NonNull T4, @NonNull T5, @NonNull T6, @NonNull T7, @NonNull T8, @NonNull T9, @NonNull R> Observable<R> zip( @NonNull ObservableSource<? extends T1> source1, @NonNull ObservableSource<? extends T2> source2, @NonNull ObservableSource<? extends T3> source3, @NonNull ObservableSource<? extends T4> source4, @NonNull ObservableSource<? extends T5> source5, @NonNull ObservableSource<? extends T6> source6, @NonNull ObservableSource<? extends T7> source7, @NonNull ObservableSource<? extends T8> source8, @NonNull ObservableSource<? extends T9> source9, @NonNull Function9<? super T1, ? super T2, ? super T3, ? super T4, ? super T5, ? super T6, ? super T7, ? super T8, ? super T9, ? extends R> zipper) { Objects.requireNonNull(source1, "source1 is null"); Objects.requireNonNull(source2, "source2 is null"); Objects.requireNonNull(source3, "source3 is null"); Objects.requireNonNull(source4, "source4 is null"); Objects.requireNonNull(source5, "source5 is null"); Objects.requireNonNull(source6, "source6 is null"); Objects.requireNonNull(source7, "source7 is null"); Objects.requireNonNull(source8, "source8 is null"); Objects.requireNonNull(source9, "source9 is null"); Objects.requireNonNull(zipper, "zipper is null"); return zipArray(Functions.toFunction(zipper), false, bufferSize(), source1, source2, source3, source4, source5, source6, source7, source8, source9); } /** * Returns an {@code Observable} that emits the results of a specified combiner function applied to combinations of * items emitted, in sequence, by an array of other {@link ObservableSource}s. * <p> * {@code zip} applies this function in strict sequence, so the first item emitted by the resulting {@code Observable} * will be the result of the function applied to the first item emitted by each of the {@code ObservableSource}s; * the second item emitted by the resulting {@code Observable} will be the result of the function applied to the second * item emitted by each of those {@code ObservableSource}s; and so forth. * <p> * The resulting {@code Observable<R>} returned from {@code zip} will invoke {@code onNext} as many times as * the number of {@code onNext} invocations of the {@code ObservableSource} that emits the fewest items. * <p> * The operator subscribes to its sources in order they are specified and completes eagerly if * one of the sources is shorter than the rest while disposing the other sources. Therefore, it * is possible those other sources will never be able to run to completion (and thus not calling * {@code doOnComplete()}). This can also happen if the sources are exactly the same length; if * source A completes and B has been consumed and is about to complete, the operator detects A won't * be sending further values and it will dispose B immediately. For example: * <pre><code>zip(new ObservableSource[]{range(1, 5).doOnComplete(action1), range(6, 5).doOnComplete(action2)}, (a) -&gt; * a)</code></pre> * {@code action1} will be called but {@code action2} won't. * <br>To work around this termination property, * use {@link #doOnDispose(Action)} as well or use {@code using()} to do cleanup in case of completion * or a dispose() call. * <p> * Note on method signature: since Java doesn't allow creating a generic array with {@code new T[]}, the * implementation of this operator has to create an {@code Object[]} instead. Unfortunately, a * {@code Function<Integer[], R>} passed to the method would trigger a {@link ClassCastException}. * * <p> * <img width="640" height="380" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/zipArray.o.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code zipArray} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <T> the common element type * @param <R> the result type * @param sources * an array of source {@code ObservableSource}s * @param zipper * a function that, when applied to an item emitted by each of the {@code ObservableSource}s, results in * an item that will be emitted by the resulting {@code Observable} * @param delayError * delay errors signaled by any of the {@code ObservableSource} until all {@code ObservableSource}s terminate * @param bufferSize * the number of elements expected from each source {@code ObservableSource} to be buffered * @return the new {@code Observable} instance * @throws NullPointerException if {@code sources} or {@code zipper} is {@code null} * @throws IllegalArgumentException if {@code bufferSize} is non-positive * @see <a href="http://reactivex.io/documentation/operators/zip.html">ReactiveX operators documentation: Zip</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @SafeVarargs @NonNull public static <@NonNull T, @NonNull R> Observable<R> zipArray( @NonNull Function<? super Object[], ? extends R> zipper, boolean delayError, int bufferSize, @NonNull ObservableSource<? extends T>... sources) { Objects.requireNonNull(sources, "sources is null"); if (sources.length == 0) { return empty(); } Objects.requireNonNull(zipper, "zipper is null"); ObjectHelper.verifyPositive(bufferSize, "bufferSize"); return RxJavaPlugins.onAssembly(new ObservableZip<>(sources, null, zipper, bufferSize, delayError)); } // *************************************************************************************************** // Instance operators // *************************************************************************************************** /** * Returns a {@link Single} that emits a {@link Boolean} that indicates whether all of the items emitted by the current * {@code Observable} satisfy a condition. * <p> * <img width="640" height="265" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/all.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code all} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * a function that evaluates an item and returns a {@code Boolean} * @return the new {@code Single} instance * @throws NullPointerException if {@code predicate} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/all.html">ReactiveX operators documentation: All</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Single<Boolean> all(@NonNull Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return RxJavaPlugins.onAssembly(new ObservableAllSingle<>(this, predicate)); } /** * Mirrors the current {@code Observable} or the other {@link ObservableSource} provided of which the first either emits an item or sends a termination * notification. * <p> * <img width="640" height="448" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Observable.ambWith.png" alt=""> * <p> * When the current {@code Observable} signals an item or terminates first, the subscription to the other * {@code ObservableSource} is disposed. If the other {@code ObservableSource} signals an item or terminates first, * the subscription to the current {@code Observable} is disposed. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code ambWith} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd> * If the losing {@code ObservableSource} signals an error, the error is routed to the global * error handler via {@link RxJavaPlugins#onError(Throwable)}. * </dd> * </dl> * * @param other * an {@code ObservableSource} competing to react first. A subscription to this provided source will occur after * subscribing to the current source. * @return the new {@code Observable} instance * @throws NullPointerException if {@code other} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/amb.html">ReactiveX operators documentation: Amb</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Observable<T> ambWith(@NonNull ObservableSource<? extends T> other) { Objects.requireNonNull(other, "other is null"); return ambArray(this, other); } /** * Returns a {@link Single} that emits {@code true} if any item emitted by the current {@code Observable} satisfies a * specified condition, otherwise {@code false}. <em>Note:</em> this always emits {@code false} if the * current {@code Observable} is empty. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/any.2.v3.png" alt=""> * <p> * In Rx.Net this is the {@code any} {@link Observer} but we renamed it in RxJava to better match Java naming * idioms. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code any} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param predicate * the condition to test items emitted by the current {@code Observable} * @return the new {@code Single} instance * @throws NullPointerException if {@code predicate} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/contains.html">ReactiveX operators documentation: Contains</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Single<Boolean> any(@NonNull Predicate<? super T> predicate) { Objects.requireNonNull(predicate, "predicate is null"); return RxJavaPlugins.onAssembly(new ObservableAnySingle<>(this, predicate)); } /** * Returns the first item emitted by the current {@code Observable}, or throws * {@link NoSuchElementException} if it emits no items. * <p> * <img width="640" height="413" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingFirst.o.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingFirst} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the source signals an error, the operator wraps a checked {@link Exception} * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and * {@link Error}s are rethrown as they are.</dd> * </dl> * * @return the first item emitted by the current {@code Observable} * @throws NoSuchElementException * if the current {@code Observable} emits no items * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX documentation: First</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final T blockingFirst() { BlockingFirstObserver<T> observer = new BlockingFirstObserver<>(); subscribe(observer); T v = observer.blockingGet(); if (v != null) { return v; } throw new NoSuchElementException(); } /** * Returns the first item emitted by the current {@code Observable}, or a default value if it emits no * items. * <p> * <img width="640" height="329" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingFirst.o.default.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingFirst} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the source signals an error, the operator wraps a checked {@link Exception} * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and * {@link Error}s are rethrown as they are.</dd> * </dl> * * @param defaultItem * a default value to return if the current {@code Observable} emits no items * @return the first item emitted by the current {@code Observable}, or the default value if it emits no * items * @throws NullPointerException if {@code defaultItem} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX documentation: First</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final T blockingFirst(@NonNull T defaultItem) { Objects.requireNonNull(defaultItem, "defaultItem is null"); BlockingFirstObserver<T> observer = new BlockingFirstObserver<>(); subscribe(observer); T v = observer.blockingGet(); return v != null ? v : defaultItem; } /** * Consumes the current {@code Observable} in a blocking fashion and invokes the given * {@link Consumer} with each upstream item on the <em>current thread</em> until the * upstream terminates. * <p> * <img width="640" height="330" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingForEach.o.v3.png" alt=""> * <p> * <em>Note:</em> the method will only return if the upstream terminates or the current * thread is interrupted. * <p> * This method executes the {@code Consumer} on the current thread while * {@link #subscribe(Consumer)} executes the consumer on the original caller thread of the * sequence. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingForEach} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the source signals an error, the operator wraps a checked {@link Exception} * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and * {@link Error}s are rethrown as they are.</dd> * </dl> * * @param onNext * the {@code Consumer} to invoke for each item emitted by the {@code Observable} * @throws NullPointerException if {@code onNext} is {@code null} * @throws RuntimeException * if an error occurs * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX documentation: Subscribe</a> * @see #subscribe(Consumer) * @see #blockingForEach(Consumer, int) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingForEach(@NonNull Consumer<? super T> onNext) { blockingForEach(onNext, bufferSize()); } /** * Consumes the current {@code Observable} in a blocking fashion and invokes the given * {@link Consumer} with each upstream item on the <em>current thread</em> until the * upstream terminates. * <p> * <img width="640" height="330" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingForEach.o.v3.png" alt=""> * <p> * <em>Note:</em> the method will only return if the upstream terminates or the current * thread is interrupted. * <p> * This method executes the {@code Consumer} on the current thread while * {@link #subscribe(Consumer)} executes the consumer on the original caller thread of the * sequence. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingForEach} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the source signals an error, the operator wraps a checked {@link Exception} * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and * {@link Error}s are rethrown as they are.</dd> * </dl> * * @param onNext * the {@code Consumer} to invoke for each item emitted by the {@code Observable} * @param capacityHint * the number of items expected to be buffered (allows reducing buffer reallocations) * @throws NullPointerException if {@code onNext} is {@code null} * @throws IllegalArgumentException if {@code capacityHint} is non-positive * @throws RuntimeException * if an error occurs; {@code Error}s and {@code RuntimeException}s are rethrown * as they are, checked {@code Exception}s are wrapped into {@code RuntimeException}s * @see <a href="http://reactivex.io/documentation/operators/subscribe.html">ReactiveX documentation: Subscribe</a> * @see #subscribe(Consumer) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingForEach(@NonNull Consumer<? super T> onNext, int capacityHint) { Objects.requireNonNull(onNext, "onNext is null"); Iterator<T> it = blockingIterable(capacityHint).iterator(); while (it.hasNext()) { try { onNext.accept(it.next()); } catch (Throwable e) { Exceptions.throwIfFatal(e); ((Disposable)it).dispose(); throw ExceptionHelper.wrapOrThrow(e); } } } /** * Exposes the current {@code Observable} as an {@link Iterable} which, when iterated, * subscribes to the current {@code Observable} and blocks * until the current {@code Observable} emits items or terminates. * <p> * <img width="640" height="315" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingIterable.o.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingIterable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Iterable} instance * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX documentation: To</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Iterable<T> blockingIterable() { return blockingIterable(bufferSize()); } /** * Exposes the current {@code Observable} as an {@link Iterable} which, when iterated, * subscribes to the current {@code Observable} and blocks * until the current {@code Observable} emits items or terminates. * <p> * <img width="640" height="315" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingIterable.o.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingIterable} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param capacityHint the expected number of items to be buffered * @return the new {@code Iterable} instance * @throws IllegalArgumentException if {@code capacityHint} is non-positive * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX documentation: To</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Iterable<T> blockingIterable(int capacityHint) { ObjectHelper.verifyPositive(capacityHint, "capacityHint"); return new BlockingObservableIterable<>(this, capacityHint); } /** * Returns the last item emitted by the current {@code Observable}, or throws * {@link NoSuchElementException} if the current {@code Observable} emits no items. * <p> * <img width="640" height="315" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingLast.o.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingLast} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the source signals an error, the operator wraps a checked {@link Exception} * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and * {@link Error}s are rethrown as they are.</dd> * </dl> * * @return the last item emitted by the current {@code Observable} * @throws NoSuchElementException * if the current {@code Observable} emits no items * @see <a href="http://reactivex.io/documentation/operators/last.html">ReactiveX documentation: Last</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final T blockingLast() { BlockingLastObserver<T> observer = new BlockingLastObserver<>(); subscribe(observer); T v = observer.blockingGet(); if (v != null) { return v; } throw new NoSuchElementException(); } /** * Returns the last item emitted by the current {@code Observable}, or a default value if it emits no * items. * <p> * <img width="640" height="310" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingLastDefault.o.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingLast} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the source signals an error, the operator wraps a checked {@link Exception} * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and * {@link Error}s are rethrown as they are.</dd> * </dl> * * @param defaultItem * a default value to return if the current {@code Observable} emits no items * @return the last item emitted by the {@code Observable}, or the default value if it emits no * items * @throws NullPointerException if {@code defaultItem} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/last.html">ReactiveX documentation: Last</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final T blockingLast(@NonNull T defaultItem) { Objects.requireNonNull(defaultItem, "defaultItem is null"); BlockingLastObserver<T> observer = new BlockingLastObserver<>(); subscribe(observer); T v = observer.blockingGet(); return v != null ? v : defaultItem; } /** * Returns an {@link Iterable} that returns the latest item emitted by the current {@code Observable}, * waiting if necessary for one to become available. * <p> * <img width="640" height="350" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingLatest.o.png" alt=""> * <p> * If the current {@code Observable} produces items faster than {@code Iterator.next} takes them, * {@code onNext} events might be skipped, but {@code onError} or {@code onComplete} events are not. * <p> * Note also that an {@code onNext} directly followed by {@code onComplete} might hide the {@code onNext} * event. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingLatest} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Iterable} instance * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX documentation: First</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Iterable<T> blockingLatest() { return new BlockingObservableLatest<>(this); } /** * Returns an {@link Iterable} that always returns the item most recently emitted by the current * {@code Observable}. * <p> * <img width="640" height="426" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingMostRecent.o.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingMostRecent} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param initialItem * the initial value that the {@code Iterable} sequence will yield if the current * {@code Observable} has not yet emitted an item * @return the new {@code Iterable} instance * @throws NullPointerException if {@code initialItem} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX documentation: First</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Iterable<T> blockingMostRecent(@NonNull T initialItem) { Objects.requireNonNull(initialItem, "initialItem is null"); return new BlockingObservableMostRecent<>(this, initialItem); } /** * Returns an {@link Iterable} that blocks until the current {@code Observable} emits another item, then * returns that item. * <p> * <img width="640" height="427" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingNext.o.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingNext} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Iterable} instance * @see <a href="http://reactivex.io/documentation/operators/takelast.html">ReactiveX documentation: TakeLast</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Iterable<T> blockingNext() { return new BlockingObservableNext<>(this); } /** * If the current {@code Observable} completes after emitting a single item, return that item, otherwise * throw a {@link NoSuchElementException}. * <p> * <img width="640" height="315" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingSingle.o.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSingle} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the source signals an error, the operator wraps a checked {@link Exception} * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and * {@link Error}s are rethrown as they are.</dd> * </dl> * * @return the single item emitted by the current {@code Observable} * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX documentation: First</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final T blockingSingle() { T v = singleElement().blockingGet(); if (v == null) { throw new NoSuchElementException(); } return v; } /** * If the current {@code Observable} completes after emitting a single item, return that item; if it emits * more than one item, throw an {@link IllegalArgumentException}; if it emits no items, return a default * value. * <p> * <img width="640" height="315" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/blockingSingleDefault.o.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSingle} does not operate by default on a particular {@link Scheduler}.</dd> * <dt><b>Error handling:</b></dt> * <dd>If the source signals an error, the operator wraps a checked {@link Exception} * into {@link RuntimeException} and throws that. Otherwise, {@code RuntimeException}s and * {@link Error}s are rethrown as they are.</dd> * </dl> * * @param defaultItem * a default value to return if the current {@code Observable} emits no items * @return the single item emitted by the current {@code Observable}, or the default value if it emits no * items * @throws NullPointerException if {@code defaultItem} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/first.html">ReactiveX documentation: First</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final T blockingSingle(@NonNull T defaultItem) { return single(defaultItem).blockingGet(); } /** * Returns a {@link Future} representing the only value emitted by the current {@code Observable}. * <p> * <img width="640" height="299" src="https://github.com/ReactiveX/RxJava/wiki/images/rx-operators/toFuture.o.png" alt=""> * <p> * If the {@code Observable} emits more than one item, {@code Future} will receive an * {@link IndexOutOfBoundsException}. If the {@code Observable} is empty, {@code Future} * will receive an {@link NoSuchElementException}. The {@code Observable} source has to terminate in order * for the returned {@code Future} to terminate as well. * <p> * If the {@code Observable} may emit more than one item, use {@code Observable.toList().toFuture()}. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code toFuture} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Future} instance * @see <a href="http://reactivex.io/documentation/operators/to.html">ReactiveX documentation: To</a> * @see #singleOrErrorStage() */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Future<T> toFuture() { return subscribeWith(new FutureObserver<>()); } /** * Runs the current {@code Observable} to a terminal event, ignoring any values and rethrowing any exception. * <p> * <img width="640" height="270" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/blockingSubscribe.o.0.png" alt=""> * <p> * Note that calling this method will block the caller thread until the upstream terminates * normally or with an error. Therefore, calling this method from special threads such as the * Android Main Thread or the Swing Event Dispatch Thread is not recommended. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @since 2.0 * @see #blockingSubscribe(Consumer) * @see #blockingSubscribe(Consumer, Consumer) * @see #blockingSubscribe(Consumer, Consumer, Action) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe() { ObservableBlockingSubscribe.subscribe(this); } /** * Subscribes to the source and calls the given callbacks <strong>on the current thread</strong>. * <p> * <img width="640" height="394" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/blockingSubscribe.o.1.png" alt=""> * <p> * If the {@code Observable} emits an error, it is wrapped into an * {@link OnErrorNotImplementedException} * and routed to the {@link RxJavaPlugins#onError(Throwable)} handler. * Using the overloads {@link #blockingSubscribe(Consumer, Consumer)} * or {@link #blockingSubscribe(Consumer, Consumer, Action)} instead is recommended. * <p> * Note that calling this method will block the caller thread until the upstream terminates * normally or with an error. Therefore, calling this method from special threads such as the * Android Main Thread or the Swing Event Dispatch Thread is not recommended. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param onNext the callback action for each source value * @throws NullPointerException if {@code onNext} is {@code null} * @since 2.0 * @see #blockingSubscribe(Consumer, Consumer) * @see #blockingSubscribe(Consumer, Consumer, Action) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe(@NonNull Consumer<? super T> onNext) { ObservableBlockingSubscribe.subscribe(this, onNext, Functions.ON_ERROR_MISSING, Functions.EMPTY_ACTION); } /** * Subscribes to the source and calls the given callbacks <strong>on the current thread</strong>. * <p> * <img width="640" height="397" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/blockingSubscribe.o.2.png" alt=""> * <p> * Note that calling this method will block the caller thread until the upstream terminates * normally or with an error. Therefore, calling this method from special threads such as the * Android Main Thread or the Swing Event Dispatch Thread is not recommended. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param onNext the callback action for each source value * @param onError the callback action for an error event * @throws NullPointerException if {@code onNext} or {@code onError} is {@code null} * @since 2.0 * @see #blockingSubscribe(Consumer, Consumer, Action) */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe(@NonNull Consumer<? super T> onNext, @NonNull Consumer<? super Throwable> onError) { ObservableBlockingSubscribe.subscribe(this, onNext, onError, Functions.EMPTY_ACTION); } /** * Subscribes to the source and calls the given callbacks <strong>on the current thread</strong>. * <p> * <img width="640" height="394" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/blockingSubscribe.o.png" alt=""> * <p> * Note that calling this method will block the caller thread until the upstream terminates * normally or with an error. Therefore, calling this method from special threads such as the * Android Main Thread or the Swing Event Dispatch Thread is not recommended. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * @param onNext the callback action for each source value * @param onError the callback action for an error event * @param onComplete the callback action for the completion event. * @throws NullPointerException if {@code onNext}, {@code onError} or {@code onComplete} is {@code null} * @since 2.0 */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe(@NonNull Consumer<? super T> onNext, @NonNull Consumer<? super Throwable> onError, @NonNull Action onComplete) { ObservableBlockingSubscribe.subscribe(this, onNext, onError, onComplete); } /** * Subscribes to the source and calls the {@link Observer} methods <strong>on the current thread</strong>. * <p> * Note that calling this method will block the caller thread until the upstream terminates * normally, with an error or the {@code Observer} disposes the {@link Disposable} it receives via * {@link Observer#onSubscribe(Disposable)}. * Therefore, calling this method from special threads such as the * Android Main Thread or the Swing Event Dispatch Thread is not recommended. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code blockingSubscribe} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * The a dispose() call is composed through. * @param observer the {@code Observer} instance to forward events and calls to in the current thread * @throws NullPointerException if {@code observer} is {@code null} * @since 2.0 */ @SchedulerSupport(SchedulerSupport.NONE) public final void blockingSubscribe(@NonNull Observer<? super T> observer) { Objects.requireNonNull(observer, "observer is null"); ObservableBlockingSubscribe.subscribe(this, observer); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits connected, non-overlapping buffers, each containing {@code count} items. When the current * {@code Observable} completes, the resulting {@code Observable} emits the current buffer and propagates the notification * from the current {@code Observable}. Note that if the current {@code Observable} issues an {@code onError} notification * the event is passed on immediately without first emitting the buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer3.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param count * the maximum number of items in each buffer before it should be emitted * @return the new {@code Observable} instance * @throws IllegalArgumentException if {@code count} is non-positive * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Observable<@NonNull List<T>> buffer(int count) { return buffer(count, count); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits buffers every {@code skip} items, each containing {@code count} items. When the current * {@code Observable} completes, the resulting {@code Observable} emits the current buffer and propagates the notification * from the current {@code Observable}. Note that if the current {@code Observable} issues an {@code onError} notification * the event is passed on immediately without first emitting the buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer4.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param count * the maximum size of each buffer before it should be emitted * @param skip * how many items emitted by the current {@code Observable} should be skipped before starting a new * buffer. Note that when {@code skip} and {@code count} are equal, this is the same operation as * {@link #buffer(int)}. * @return the new {@code Observable} instance * @throws IllegalArgumentException if {@code count} or {@code skip} is non-positive * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Observable<@NonNull List<T>> buffer(int count, int skip) { return buffer(count, skip, ArrayListSupplier.asSupplier()); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits buffers every {@code skip} items, each containing {@code count} items. When the current * {@code Observable} completes, the resulting {@code Observable} emits the current buffer and propagates the notification * from the current {@code Observable}. Note that if the current {@code Observable} issues an {@code onError} notification * the event is passed on immediately without first emitting the buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer4.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> the collection subclass type to buffer into * @param count * the maximum size of each buffer before it should be emitted * @param skip * how many items emitted by the current {@code Observable} should be skipped before starting a new * buffer. Note that when {@code skip} and {@code count} are equal, this is the same operation as * {@link #buffer(int)}. * @param bufferSupplier * a factory function that returns an instance of the collection subclass to be used and returned * as the buffer * @return the new {@code Observable} instance * @throws NullPointerException if {@code bufferSupplier} is {@code null} * @throws IllegalArgumentException if {@code count} or {@code skip} is non-positive * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull U extends Collection<? super T>> Observable<U> buffer(int count, int skip, @NonNull Supplier<U> bufferSupplier) { ObjectHelper.verifyPositive(count, "count"); ObjectHelper.verifyPositive(skip, "skip"); Objects.requireNonNull(bufferSupplier, "bufferSupplier is null"); return RxJavaPlugins.onAssembly(new ObservableBuffer<>(this, count, skip, bufferSupplier)); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits connected, non-overlapping buffers, each containing {@code count} items. When the current * {@code Observable} completes, the resulting {@code Observable} emits the current buffer and propagates the notification * from the current {@code Observable}. Note that if the current {@code Observable} issues an {@code onError} notification * the event is passed on immediately without first emitting the buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer3.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> the collection subclass type to buffer into * @param count * the maximum number of items in each buffer before it should be emitted * @param bufferSupplier * a factory function that returns an instance of the collection subclass to be used and returned * as the buffer * @return the new {@code Observable} instance * @throws NullPointerException if {@code bufferSupplier} is {@code null} * @throws IllegalArgumentException if {@code count} is non-positive * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull U extends Collection<? super T>> Observable<U> buffer(int count, @NonNull Supplier<U> bufferSupplier) { return buffer(count, count, bufferSupplier); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} starts a new buffer periodically, as determined by the {@code timeskip} argument. It emits * each buffer after a fixed timespan, specified by the {@code timespan} argument. When the current * {@code Observable} completes, the resulting {@code Observable} emits the current buffer and propagates the notification * from the current {@code Observable}. Note that if the current {@code Observable} issues an {@code onError} notification * the event is passed on immediately without first emitting the buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer7.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timespan * the period of time each buffer collects items before it is emitted * @param timeskip * the period of time after which a new buffer will be created * @param unit * the unit of time that applies to the {@code timespan} and {@code timeskip} arguments * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public final Observable<@NonNull List<T>> buffer(long timespan, long timeskip, @NonNull TimeUnit unit) { return buffer(timespan, timeskip, unit, Schedulers.computation(), ArrayListSupplier.asSupplier()); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} starts a new buffer periodically, as determined by the {@code timeskip} argument, and on the * specified {@code scheduler}. It emits each buffer after a fixed timespan, specified by the * {@code timespan} argument. When the current {@code Observable} completes, the resulting {@code Observable} emits the * current buffer and propagates the notification from the current {@code Observable}. Note that if the current * {@code Observable} issues an {@code onError} notification the event is passed on immediately without first emitting the * buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer7.s.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> * </dl> * * @param timespan * the period of time each buffer collects items before it is emitted * @param timeskip * the period of time after which a new buffer will be created * @param unit * the unit of time that applies to the {@code timespan} and {@code timeskip} arguments * @param scheduler * the {@code Scheduler} to use when determining the end and start of a buffer * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @NonNull public final Observable<@NonNull List<T>> buffer(long timespan, long timeskip, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { return buffer(timespan, timeskip, unit, scheduler, ArrayListSupplier.asSupplier()); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} starts a new buffer periodically, as determined by the {@code timeskip} argument, and on the * specified {@code scheduler}. It emits each buffer after a fixed timespan, specified by the * {@code timespan} argument. When the current {@code Observable} completes, the resulting {@code Observable} emits the * current buffer and propagates the notification from the current {@code Observable}. Note that if the current * {@code Observable} issues an {@code onError} notification the event is passed on immediately without first emitting the * buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer7.s.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> * </dl> * * @param <U> the collection subclass type to buffer into * @param timespan * the period of time each buffer collects items before it is emitted * @param timeskip * the period of time after which a new buffer will be created * @param unit * the unit of time that applies to the {@code timespan} and {@code timeskip} arguments * @param scheduler * the {@code Scheduler} to use when determining the end and start of a buffer * @param bufferSupplier * a factory function that returns an instance of the collection subclass to be used and returned * as the buffer * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit}, {@code scheduler} or {@code bufferSupplier} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @NonNull public final <@NonNull U extends Collection<? super T>> Observable<U> buffer(long timespan, long timeskip, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, @NonNull Supplier<U> bufferSupplier) { Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); Objects.requireNonNull(bufferSupplier, "bufferSupplier is null"); return RxJavaPlugins.onAssembly(new ObservableBufferTimed<>(this, timespan, timeskip, unit, scheduler, bufferSupplier, Integer.MAX_VALUE, false)); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument. When the current {@code Observable} completes, the resulting {@code Observable} emits the * current buffer and propagates the notification from the current {@code Observable}. Note that if the current * {@code Observable} issues an {@code onError} notification the event is passed on immediately without first emitting the * buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer5.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timespan * the period of time each buffer collects items before it is emitted and replaced with a new * buffer * @param unit * the unit of time that applies to the {@code timespan} argument * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public final Observable<@NonNull List<T>> buffer(long timespan, @NonNull TimeUnit unit) { return buffer(timespan, unit, Schedulers.computation(), Integer.MAX_VALUE); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument or a maximum size specified by the {@code count} argument (whichever is reached * first). When the current {@code Observable} completes, the resulting {@code Observable} emits the current buffer and * propagates the notification from the current {@code Observable}. Note that if the current {@code Observable} issues an * {@code onError} notification the event is passed on immediately without first emitting the buffer it is in the process of * assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer6.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} operates by default on the {@code computation} {@link Scheduler}.</dd> * </dl> * * @param timespan * the period of time each buffer collects items before it is emitted and replaced with a new * buffer * @param unit * the unit of time which applies to the {@code timespan} argument * @param count * the maximum size of each buffer before it is emitted * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} is {@code null} * @throws IllegalArgumentException if {@code count} is non-positive * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.COMPUTATION) @NonNull public final Observable<@NonNull List<T>> buffer(long timespan, @NonNull TimeUnit unit, int count) { return buffer(timespan, unit, Schedulers.computation(), count); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument as measured on the specified {@code scheduler}, or a maximum size specified by * the {@code count} argument (whichever is reached first). When the current {@code Observable} completes, the resulting * {@code Observable} emits the current buffer and propagates the notification from the current {@code Observable}. Note * that if the current {@code Observable} issues an {@code onError} notification the event is passed on immediately without * first emitting the buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer6.s.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> * </dl> * * @param timespan * the period of time each buffer collects items before it is emitted and replaced with a new * buffer * @param unit * the unit of time which applies to the {@code timespan} argument * @param scheduler * the {@code Scheduler} to use when determining the end and start of a buffer * @param count * the maximum size of each buffer before it is emitted * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @throws IllegalArgumentException if {@code count} is non-positive * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @NonNull public final Observable<@NonNull List<T>> buffer(long timespan, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, int count) { return buffer(timespan, unit, scheduler, count, ArrayListSupplier.asSupplier(), false); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument as measured on the specified {@code scheduler}, or a maximum size specified by * the {@code count} argument (whichever is reached first). When the current {@code Observable} completes, the resulting * {@code Observable} emits the current buffer and propagates the notification from the current {@code Observable}. Note * that if the current {@code Observable} issues an {@code onError} notification the event is passed on immediately without * first emitting the buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer6.s.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> * </dl> * * @param <U> the collection subclass type to buffer into * @param timespan * the period of time each buffer collects items before it is emitted and replaced with a new * buffer * @param unit * the unit of time which applies to the {@code timespan} argument * @param scheduler * the {@code Scheduler} to use when determining the end and start of a buffer * @param count * the maximum size of each buffer before it is emitted * @param bufferSupplier * a factory function that returns an instance of the collection subclass to be used and returned * as the buffer * @param restartTimerOnMaxSize if {@code true}, the time window is restarted when the max capacity of the current buffer * is reached * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit}, {@code scheduler} or {@code bufferSupplier} is {@code null} * @throws IllegalArgumentException if {@code count} is non-positive * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @NonNull public final <@NonNull U extends Collection<? super T>> Observable<U> buffer( long timespan, @NonNull TimeUnit unit, @NonNull Scheduler scheduler, int count, @NonNull Supplier<U> bufferSupplier, boolean restartTimerOnMaxSize) { Objects.requireNonNull(unit, "unit is null"); Objects.requireNonNull(scheduler, "scheduler is null"); Objects.requireNonNull(bufferSupplier, "bufferSupplier is null"); ObjectHelper.verifyPositive(count, "count"); return RxJavaPlugins.onAssembly(new ObservableBufferTimed<>(this, timespan, timespan, unit, scheduler, bufferSupplier, count, restartTimerOnMaxSize)); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits connected, non-overlapping buffers, each of a fixed duration specified by the * {@code timespan} argument and on the specified {@code scheduler}. When the current {@code Observable} completes, * the resulting {@code Observable} emits the current buffer and propagates the notification from the current * {@code Observable}. Note that if the current {@code Observable} issues an {@code onError} notification the event is passed on * immediately without first emitting the buffer it is in the process of assembling. * <p> * <img width="640" height="320" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer5.s.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>You specify which {@link Scheduler} this operator will use.</dd> * </dl> * * @param timespan * the period of time each buffer collects items before it is emitted and replaced with a new * buffer * @param unit * the unit of time which applies to the {@code timespan} argument * @param scheduler * the {@code Scheduler} to use when determining the end and start of a buffer * @return the new {@code Observable} instance * @throws NullPointerException if {@code unit} or {@code scheduler} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.CUSTOM) @NonNull public final Observable<@NonNull List<T>> buffer(long timespan, @NonNull TimeUnit unit, @NonNull Scheduler scheduler) { return buffer(timespan, unit, scheduler, Integer.MAX_VALUE, ArrayListSupplier.asSupplier(), false); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits buffers that it creates when the specified {@code openingIndicator} {@link ObservableSource} emits an * item, and closes when the {@code ObservableSource} returned from {@code closingIndicator} emits an item. If any of the * current {@code Observable}, {@code openingIndicator} or {@code closingIndicator} issues an {@code onError} notification the * event is passed on immediately without first emitting the buffer it is in the process of assembling. * <p> * <img width="640" height="470" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer2.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <TOpening> the element type of the buffer-opening {@code ObservableSource} * @param <TClosing> the element type of the individual buffer-closing {@code ObservableSource}s * @param openingIndicator * the {@code ObservableSource} that, when it emits an item, causes a new buffer to be created * @param closingIndicator * the {@link Function} that is used to produce an {@code ObservableSource} for every buffer created. When this indicator * {@code ObservableSource} emits an item, the associated buffer is emitted. * @return the new {@code Observable} instance * @throws NullPointerException if {@code openingIndicator} or {@code closingIndicator} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull TOpening, @NonNull TClosing> Observable<@NonNull List<T>> buffer( @NonNull ObservableSource<? extends TOpening> openingIndicator, @NonNull Function<? super TOpening, ? extends ObservableSource<? extends TClosing>> closingIndicator) { return buffer(openingIndicator, closingIndicator, ArrayListSupplier.asSupplier()); } /** * Returns an {@code Observable} that emits buffers of items it collects from the current {@code Observable}. The resulting * {@code Observable} emits buffers that it creates when the specified {@code openingIndicator} {@link ObservableSource} emits an * item, and closes when the {@code ObservableSource} returned from {@code closingIndicator} emits an item. If any of the * current {@code Observable}, {@code openingIndicator} or {@code closingIndicator} issues an {@code onError} notification the * event is passed on immediately without first emitting the buffer it is in the process of assembling. * <p> * <img width="640" height="470" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer2.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> the collection subclass type to buffer into * @param <TOpening> the element type of the buffer-opening {@code ObservableSource} * @param <TClosing> the element type of the individual buffer-closing {@code ObservableSource}s * @param openingIndicator * the {@code ObservableSource} that, when it emits an item, causes a new buffer to be created * @param closingIndicator * the {@link Function} that is used to produce an {@code ObservableSource} for every buffer created. When this indicator * {@code ObservableSource} emits an item, the associated buffer is emitted. * @param bufferSupplier * a factory function that returns an instance of the collection subclass to be used and returned * as the buffer * @return the new {@code Observable} instance * @throws NullPointerException if {@code openingIndicator}, {@code closingIndicator} or {@code bufferSupplier} is {@code null} * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull TOpening, @NonNull TClosing, @NonNull U extends Collection<? super T>> Observable<U> buffer( @NonNull ObservableSource<? extends TOpening> openingIndicator, @NonNull Function<? super TOpening, ? extends ObservableSource<? extends TClosing>> closingIndicator, @NonNull Supplier<U> bufferSupplier) { Objects.requireNonNull(openingIndicator, "openingIndicator is null"); Objects.requireNonNull(closingIndicator, "closingIndicator is null"); Objects.requireNonNull(bufferSupplier, "bufferSupplier is null"); return RxJavaPlugins.onAssembly(new ObservableBufferBoundary<T, U, TOpening, TClosing>(this, openingIndicator, closingIndicator, bufferSupplier)); } /** * Returns an {@code Observable} that emits non-overlapping buffered items from the current {@code Observable} each time the * specified boundary {@link ObservableSource} emits an item. * <p> * <img width="640" height="395" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer8.v3.png" alt=""> * <p> * Completion of either the source or the boundary {@code ObservableSource} causes the returned {@code ObservableSource} to emit the * latest buffer and complete. If either the current {@code Observable} or the boundary {@code ObservableSource} issues an * {@code onError} notification the event is passed on immediately without first emitting the buffer it is in the process of * assembling. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <B> * the boundary value type (ignored) * @param boundaryIndicator * the boundary {@code ObservableSource} * @return the new {@code Observable} instance * @throws NullPointerException if {@code boundaryIndicator} is {@code null} * @see #buffer(ObservableSource, int) * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull B> Observable<@NonNull List<T>> buffer(@NonNull ObservableSource<B> boundaryIndicator) { return buffer(boundaryIndicator, ArrayListSupplier.asSupplier()); } /** * Returns an {@code Observable} that emits non-overlapping buffered items from the current {@code Observable} each time the * specified boundary {@link ObservableSource} emits an item. * <p> * <img width="640" height="395" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer8.v3.png" alt=""> * <p> * Completion of either the source or the boundary {@code ObservableSource} causes the returned {@code ObservableSource} to emit the * latest buffer and complete. If either the current {@code Observable} or the boundary {@code ObservableSource} issues an * {@code onError} notification the event is passed on immediately without first emitting the buffer it is in the process of * assembling. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <B> * the boundary value type (ignored) * @param boundaryIndicator * the boundary {@code ObservableSource} * @param initialCapacity * the initial capacity of each buffer chunk * @return the new {@code Observable} instance * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> * @throws NullPointerException if {@code boundaryIndicator} is {@code null} * @throws IllegalArgumentException if {@code initialCapacity} is non-positive * @see #buffer(ObservableSource) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull B> Observable<@NonNull List<T>> buffer(@NonNull ObservableSource<B> boundaryIndicator, int initialCapacity) { ObjectHelper.verifyPositive(initialCapacity, "initialCapacity"); return buffer(boundaryIndicator, Functions.createArrayList(initialCapacity)); } /** * Returns an {@code Observable} that emits non-overlapping buffered items from the current {@code Observable} each time the * specified boundary {@link ObservableSource} emits an item. * <p> * <img width="640" height="395" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/buffer8.v3.png" alt=""> * <p> * Completion of either the source or the boundary {@code ObservableSource} causes the returned {@code ObservableSource} to emit the * latest buffer and complete. If either the current {@code Observable} or the boundary {@code ObservableSource} issues an * {@code onError} notification the event is passed on immediately without first emitting the buffer it is in the process of * assembling. * <dl> * <dt><b>Scheduler:</b></dt> * <dd>This version of {@code buffer} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> the collection subclass type to buffer into * @param <B> * the boundary value type (ignored) * @param boundaryIndicator * the boundary {@code ObservableSource} * @param bufferSupplier * a factory function that returns an instance of the collection subclass to be used and returned * as the buffer * @return the new {@code Observable} instance * @throws NullPointerException if {@code boundaryIndicator} or {@code bufferSupplier} is {@code null} * @see #buffer(ObservableSource, int) * @see <a href="http://reactivex.io/documentation/operators/buffer.html">ReactiveX operators documentation: Buffer</a> */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final <@NonNull B, @NonNull U extends Collection<? super T>> Observable<U> buffer(@NonNull ObservableSource<B> boundaryIndicator, @NonNull Supplier<U> bufferSupplier) { Objects.requireNonNull(boundaryIndicator, "boundaryIndicator is null"); Objects.requireNonNull(bufferSupplier, "bufferSupplier is null"); return RxJavaPlugins.onAssembly(new ObservableBufferExactBoundary<>(this, boundaryIndicator, bufferSupplier)); } /** * Returns an {@code Observable} that subscribes to the current {@code Observable} lazily, caches all of its events * and replays them, in the same order as received, to all the downstream observers. * <p> * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/cache.v3.png" alt=""> * <p> * This is useful when you want an {@code Observable} to cache responses and you can't control the * subscribe/dispose behavior of all the {@link Observer}s. * <p> * The operator subscribes only when the first downstream observer subscribes and maintains * a single subscription towards the current {@code Observable}. In contrast, the operator family of {@link #replay()} * that return a {@link ConnectableObservable} require an explicit call to {@link ConnectableObservable#connect()}. * <p> * <em>Note:</em> You sacrifice the ability to dispose the origin when you use the {@code cache} * operator so be careful not to use this operator on {@code Observable}s that emit an infinite or very large number * of items that will use up memory. * A possible workaround is to apply {@code takeUntil} with a predicate or * another source before (and perhaps after) the application of {@code cache()}. * <pre><code> * AtomicBoolean shouldStop = new AtomicBoolean(); * * source.takeUntil(v -&gt; shouldStop.get()) * .cache() * .takeUntil(v -&gt; shouldStop.get()) * .subscribe(...); * </code></pre> * Since the operator doesn't allow clearing the cached values either, the possible workaround is * to forget all references to it via {@link #onTerminateDetach()} applied along with the previous * workaround: * <pre><code> * AtomicBoolean shouldStop = new AtomicBoolean(); * * source.takeUntil(v -&gt; shouldStop.get()) * .onTerminateDetach() * .cache() * .takeUntil(v -&gt; shouldStop.get()) * .onTerminateDetach() * .subscribe(...); * </code></pre> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code cache} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @return the new {@code Observable} instance * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> * @see #takeUntil(Predicate) * @see #takeUntil(ObservableSource) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Observable<T> cache() { return cacheWithInitialCapacity(16); } /** * Returns an {@code Observable} that subscribes to the current {@code Observable} lazily, caches all of its events * and replays them, in the same order as received, to all the downstream observers. * <p> * <img width="640" height="410" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/cacheWithInitialCapacity.o.v3.png" alt=""> * <p> * This is useful when you want an {@code Observable} to cache responses and you can't control the * subscribe/dispose behavior of all the {@link Observer}s. * <p> * The operator subscribes only when the first downstream observer subscribes and maintains * a single subscription towards the current {@code Observable}. In contrast, the operator family of {@link #replay()} * that return a {@link ConnectableObservable} require an explicit call to {@link ConnectableObservable#connect()}. * <p> * <em>Note:</em> You sacrifice the ability to dispose the origin when you use the {@code cache} * operator so be careful not to use this operator on {@code Observable}s that emit an infinite or very large number * of items that will use up memory. * A possible workaround is to apply `takeUntil` with a predicate or * another source before (and perhaps after) the application of {@code cache()}. * <pre><code> * AtomicBoolean shouldStop = new AtomicBoolean(); * * source.takeUntil(v -&gt; shouldStop.get()) * .cache() * .takeUntil(v -&gt; shouldStop.get()) * .subscribe(...); * </code></pre> * Since the operator doesn't allow clearing the cached values either, the possible workaround is * to forget all references to it via {@link #onTerminateDetach()} applied along with the previous * workaround: * <pre><code> * AtomicBoolean shouldStop = new AtomicBoolean(); * * source.takeUntil(v -&gt; shouldStop.get()) * .onTerminateDetach() * .cache() * .takeUntil(v -&gt; shouldStop.get()) * .onTerminateDetach() * .subscribe(...); * </code></pre> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code cacheWithInitialCapacity} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * <p> * <em>Note:</em> The capacity hint is not an upper bound on cache size. For that, consider * {@link #replay(int)} in combination with {@link ConnectableObservable#autoConnect()} or similar. * * @param initialCapacity hint for number of items to cache (for optimizing underlying data structure) * @return the new {@code Observable} instance * @throws IllegalArgumentException if {@code initialCapacity} is non-positive * @see <a href="http://reactivex.io/documentation/operators/replay.html">ReactiveX operators documentation: Replay</a> * @see #takeUntil(Predicate) * @see #takeUntil(ObservableSource) */ @CheckReturnValue @SchedulerSupport(SchedulerSupport.NONE) @NonNull public final Observable<T> cacheWithInitialCapacity(int initialCapacity) { ObjectHelper.verifyPositive(initialCapacity, "initialCapacity"); return RxJavaPlugins.onAssembly(new ObservableCache<>(this, initialCapacity)); } /** * Returns an {@code Observable} that emits the upstream items while * they can be cast via {@link Class#cast(Object)} until the upstream terminates, * or until the upstream signals an item which can't be cast, * resulting in a {@link ClassCastException} to be signaled to the downstream. * <p> * <img width="640" height="305" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/cast.v3.png" alt=""> * <dl> * <dt><b>Scheduler:</b></dt> * <dd>{@code cast} does not operate by default on a particular {@link Scheduler}.</dd> * </dl> * * @param <U> the output value type cast to * @param clazz * the target
is
java
apache__camel
dsl/camel-endpointdsl/src/generated/java/org/apache/camel/builder/endpoint/dsl/ElasticsearchEndpointBuilderFactory.java
{ "start": 27405, "end": 29962 }
class ____ the document to unmarshall. * * The option is a: {@code Class} type. * * Default: ObjectNode * Group: producer * * @return the name of the header {@code documentClass}. */ public String documentClass() { return "documentClass"; } /** * The index creation waits for the write consistency number of shards * to be available. * * The option is a: {@code Integer} type. * * Group: producer * * @return the name of the header {@code waitForActiveShards}. */ public String waitForActiveShards() { return "waitForActiveShards"; } /** * The starting index of the response. * * The option is a: {@code Integer} type. * * Group: producer * * @return the name of the header {@code scrollKeepAliveMs}. */ public String scrollKeepAliveMs() { return "scrollKeepAliveMs"; } /** * Set to true to enable scroll usage. * * The option is a: {@code Boolean} type. * * Group: producer * * @return the name of the header {@code useScroll}. */ public String useScroll() { return "useScroll"; } /** * The size of the response. * * The option is a: {@code Integer} type. * * Group: producer * * @return the name of the header {@code size}. */ public String size() { return "size"; } /** * The starting index of the response. * * The option is a: {@code Integer} type. * * Group: producer * * @return the name of the header {@code from}. */ public String from() { return "from"; } /** * Indicates whether the body of the message contains only documents. * * The option is a: {@code Boolean} type. * * Default: false * Group: producer * * @return the name of the header {@code enableDocumentOnlyMode}. */ public String enableDocumentOnlyMode() { return "enableDocumentOnlyMode"; } } static ElasticsearchEndpointBuilder endpointBuilder(String componentName, String path) {
of
java
spring-cloud__spring-cloud-gateway
spring-cloud-gateway-proxyexchange-webflux/src/test/java/org/springframework/cloud/gateway/webflux/ReactiveTests.java
{ "start": 2704, "end": 5030 }
class ____ { @Autowired private TestRestTemplate rest; @LocalServerPort private int port; @Test public void postBytes() throws Exception { ResponseEntity<List<Foo>> result = rest .exchange(RequestEntity.post(rest.getRestTemplate().getUriTemplateHandler().expand("/bytes")) .body("hello foo".getBytes()), new ParameterizedTypeReference<List<Foo>>() { }); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(result.getBody().iterator().next().getName()).isEqualTo("hello foo"); } @Test public void post() throws Exception { ResponseEntity<List<Bar>> result = rest.exchange( RequestEntity.post(rest.getRestTemplate().getUriTemplateHandler().expand("/bars")) .body(Collections.singletonList(Collections.singletonMap("name", "foo"))), new ParameterizedTypeReference<List<Bar>>() { }); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(result.getBody().iterator().next().getName()).isEqualTo("hello foo"); } @Test public void postFlux() throws Exception { ResponseEntity<List<Bar>> result = rest.exchange( RequestEntity.post(rest.getRestTemplate().getUriTemplateHandler().expand("/flux/bars")) .body(Collections.singletonList(Collections.singletonMap("name", "foo"))), new ParameterizedTypeReference<List<Bar>>() { }); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(result.getBody().iterator().next().getName()).isEqualTo("hello foo"); } @Test public void get() throws Exception { ResponseEntity<List<Foo>> result = rest.exchange( RequestEntity.get(rest.getRestTemplate().getUriTemplateHandler().expand("/foos")).build(), new ParameterizedTypeReference<List<Foo>>() { }); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(result.getBody().iterator().next().getName()).isEqualTo("hello"); } @Test public void forward() throws Exception { ResponseEntity<List<Foo>> result = rest.exchange( RequestEntity.get(rest.getRestTemplate().getUriTemplateHandler().expand("/forward/foos")).build(), new ParameterizedTypeReference<List<Foo>>() { }); assertThat(result.getStatusCode()).isEqualTo(HttpStatus.OK); assertThat(result.getBody().iterator().next().getName()).isEqualTo("hello"); } @SpringBootApplication static
ReactiveTests
java
apache__hadoop
hadoop-tools/hadoop-aws/src/test/java/org/apache/hadoop/fs/s3a/TestS3AAWSCredentialsProvider.java
{ "start": 3883, "end": 14992 }
class ____ extends AbstractS3ATestBase { /** * URI of the test file: this must be anonymously accessible. * As these are unit tests no actual connection to the store is made. */ private static final URI TESTFILE_URI = new Path( PublicDatasetTestUtils.DEFAULT_EXTERNAL_FILE).toUri(); private static final Logger LOG = LoggerFactory.getLogger(TestS3AAWSCredentialsProvider.class); public static final int TERMINATION_TIMEOUT = 3; @Test public void testProviderWrongClass() throws Exception { expectProviderInstantiationFailure(this.getClass(), DOES_NOT_IMPLEMENT + " software.amazon.awssdk.auth.credentials.AwsCredentialsProvider"); } @Test public void testProviderAbstractClass() throws Exception { expectProviderInstantiationFailure(AbstractProvider.class, InstantiationIOException.ABSTRACT_PROVIDER); } @Test public void testProviderNotAClass() throws Exception { expectProviderInstantiationFailure("NoSuchClass", "ClassNotFoundException"); } @Test public void testProviderConstructorError() throws Exception { expectProviderInstantiationFailure( ConstructorSignatureErrorProvider.class, InstantiationIOException.CONSTRUCTOR_EXCEPTION); } @Test public void testProviderFailureError() throws Exception { expectProviderInstantiationFailure( ConstructorFailureProvider.class, InstantiationIOException.INSTANTIATION_EXCEPTION); } @Test public void testInstantiationChain() throws Throwable { Configuration conf = new Configuration(false); conf.set(AWS_CREDENTIALS_PROVIDER, TemporaryAWSCredentialsProvider.NAME + ", \t" + SimpleAWSCredentialsProvider.NAME + " ,\n " + AnonymousAWSCredentialsProvider.NAME); Path testFile = getExternalData(conf); AWSCredentialProviderList list = createAWSCredentialProviderList( testFile.toUri(), conf); List<Class<?>> expectedClasses = Arrays.asList( TemporaryAWSCredentialsProvider.class, SimpleAWSCredentialsProvider.class, AnonymousAWSCredentialsProvider.class); assertCredentialProviders(expectedClasses, list); } @Test public void testProfileAWSCredentialsProvider() throws Throwable { Configuration conf = new Configuration(false); conf.set(AWS_CREDENTIALS_PROVIDER, ProfileAWSCredentialsProvider.NAME); File tempFile = File.createTempFile("testcred", ".conf", new File("target")); tempFile.deleteOnExit(); try (FileWriter fileWriter = new FileWriter(tempFile); BufferedWriter bufferedWriter = new BufferedWriter(fileWriter)) { bufferedWriter.write("[default]\n" + "aws_access_key_id = defaultaccesskeyid\n" + "aws_secret_access_key = defaultsecretkeyid\n"); bufferedWriter.write("[nondefault]\n" + "aws_access_key_id = nondefaultaccesskeyid\n" + "aws_secret_access_key = nondefaultsecretkeyid\n"); } conf.set(ProfileAWSCredentialsProvider.PROFILE_FILE, tempFile.getAbsolutePath()); URI testUri = new URI("s3a://bucket1"); AWSCredentialProviderList list = createAWSCredentialProviderList(testUri, conf); assertCredentialProviders(Collections.singletonList(ProfileAWSCredentialsProvider.class), list); AwsCredentials credentials = list.resolveCredentials(); Assertions.assertThat(credentials.accessKeyId()).isEqualTo("defaultaccesskeyid"); Assertions.assertThat(credentials.secretAccessKey()).isEqualTo("defaultsecretkeyid"); conf.set(ProfileAWSCredentialsProvider.PROFILE_NAME, "nondefault"); list = createAWSCredentialProviderList(testUri, conf); credentials = list.resolveCredentials(); Assertions.assertThat(credentials.accessKeyId()).isEqualTo("nondefaultaccesskeyid"); Assertions.assertThat(credentials.secretAccessKey()).isEqualTo("nondefaultsecretkeyid"); } @Test public void testDefaultChain() throws Exception { URI uri1 = new URI("s3a://bucket1"), uri2 = new URI("s3a://bucket2"); Configuration conf = new Configuration(false); // use the default credential provider chain conf.unset(AWS_CREDENTIALS_PROVIDER); AWSCredentialProviderList list1 = createAWSCredentialProviderList( uri1, conf); AWSCredentialProviderList list2 = createAWSCredentialProviderList( uri2, conf); List<Class<?>> expectedClasses = STANDARD_AWS_PROVIDERS; assertCredentialProviders(expectedClasses, list1); assertCredentialProviders(expectedClasses, list2); } @Test public void testNonSdkExceptionConversion() throws Throwable { // Create a mock credential provider that throws a non-SDK exception AwsCredentialsProvider mockProvider = () -> { throw new RuntimeException("Test credential error"); }; // Create the provider list with our mock provider AWSCredentialProviderList providerList = new AWSCredentialProviderList(Collections.singletonList(mockProvider)); // Attempt to get credentials, which should trigger the exception intercept(NoAuthWithAWSException.class, "No AWS Credentials provided", () -> providerList.resolveCredentials()); } @Test public void testDefaultChainNoURI() throws Exception { Configuration conf = new Configuration(false); // use the default credential provider chain conf.unset(AWS_CREDENTIALS_PROVIDER); assertCredentialProviders(STANDARD_AWS_PROVIDERS, createAWSCredentialProviderList(null, conf)); } @Test public void testConfiguredChain() throws Exception { URI uri1 = new URI("s3a://bucket1"), uri2 = new URI("s3a://bucket2"); List<Class<?>> expectedClasses = Arrays.asList( IAMInstanceCredentialsProvider.class, AnonymousAWSCredentialsProvider.class, EnvironmentVariableCredentialsProvider.class ); Configuration conf = createProviderConfiguration(buildClassListString(expectedClasses)); AWSCredentialProviderList list1 = createAWSCredentialProviderList( uri1, conf); AWSCredentialProviderList list2 = createAWSCredentialProviderList( uri2, conf); assertCredentialProviders(expectedClasses, list1); assertCredentialProviders(expectedClasses, list2); } @Test public void testConfiguredChainUsesSharedInstanceProfile() throws Exception { URI uri1 = new URI("s3a://bucket1"), uri2 = new URI("s3a://bucket2"); Configuration conf = new Configuration(false); List<Class<?>> expectedClasses = Arrays.asList( InstanceProfileCredentialsProvider.class); conf.set(AWS_CREDENTIALS_PROVIDER, buildClassListString(expectedClasses)); AWSCredentialProviderList list1 = createAWSCredentialProviderList( uri1, conf); AWSCredentialProviderList list2 = createAWSCredentialProviderList( uri2, conf); assertCredentialProviders(expectedClasses, list1); assertCredentialProviders(expectedClasses, list2); } @Test public void testFallbackToDefaults() throws Throwable { // build up the base provider final AWSCredentialProviderList credentials = buildAWSProviderList( new URI("s3a://bucket1"), createProviderConfiguration(" "), ASSUMED_ROLE_CREDENTIALS_PROVIDER, Arrays.asList( EnvironmentVariableCredentialsProvider.class), Sets.newHashSet()); assertTrue(credentials.size() > 0, "empty credentials"); } /** * Test S3A credentials provider remapping with assumed role * credentials provider. */ @Test public void testAssumedRoleWithRemap() throws Throwable { Configuration conf = new Configuration(false); conf.set(ASSUMED_ROLE_CREDENTIALS_PROVIDER, "custom.assume.role.key1,custom.assume.role.key2,custom.assume.role.key3"); conf.set(AWS_CREDENTIALS_PROVIDER_MAPPING, "custom.assume.role.key1=" + CredentialProviderListFactory.ENVIRONMENT_CREDENTIALS_V2 + " ,custom.assume.role.key2 =" + CountInvocationsProvider.NAME + ", custom.assume.role.key3= " + CredentialProviderListFactory.PROFILE_CREDENTIALS_V1); final AWSCredentialProviderList credentials = buildAWSProviderList( new URI("s3a://bucket1"), conf, ASSUMED_ROLE_CREDENTIALS_PROVIDER, new ArrayList<>(), new HashSet<>()); Assertions .assertThat(credentials.size()) .describedAs("List of Credentials providers") .isEqualTo(3); } /** * Test S3A credentials provider remapping with aws * credentials provider. */ @Test public void testAwsCredentialProvidersWithRemap() throws Throwable { Configuration conf = new Configuration(false); conf.set(AWS_CREDENTIALS_PROVIDER, "custom.aws.creds.key1,custom.aws.creds.key2,custom.aws.creds.key3,custom.aws.creds.key4"); conf.set(AWS_CREDENTIALS_PROVIDER_MAPPING, "custom.aws.creds.key1=" + CredentialProviderListFactory.ENVIRONMENT_CREDENTIALS_V2 + " ,\ncustom.aws.creds.key2=" + CountInvocationsProvider.NAME + "\n, custom.aws.creds.key3=" + CredentialProviderListFactory.PROFILE_CREDENTIALS_V1 + ",custom.aws.creds.key4 = " + CredentialProviderListFactory.PROFILE_CREDENTIALS_V2); final AWSCredentialProviderList credentials = buildAWSProviderList( new URI("s3a://bucket1"), conf, AWS_CREDENTIALS_PROVIDER, new ArrayList<>(), new HashSet<>()); Assertions .assertThat(credentials.size()) .describedAs("List of Credentials providers") .isEqualTo(4); } @Test public void testProviderConstructor() throws Throwable { final AWSCredentialProviderList list = new AWSCredentialProviderList("name", new AnonymousAWSCredentialsProvider(), new ErrorProvider(TESTFILE_URI, new Configuration())); Assertions.assertThat(list.getProviders()) .describedAs("provider list in %s", list) .hasSize(2); final AwsCredentials credentials = list.resolveCredentials(); Assertions.assertThat(credentials) .isInstanceOf(AwsBasicCredentials.class); assertCredentialResolution(credentials, null, null); } public static void assertCredentialResolution(AwsCredentials creds, String key, String secret) { Assertions.assertThat(creds.accessKeyId()) .describedAs("access key of %s", creds) .isEqualTo(key); Assertions.assertThat(creds.secretAccessKey()) .describedAs("secret key of %s", creds) .isEqualTo(secret); } private String buildClassList(Class... classes) { return Arrays.stream(classes) .map(Class::getCanonicalName) .collect(Collectors.joining(",")); } private String buildClassList(String... classes) { return Arrays.stream(classes) .collect(Collectors.joining(",")); } /** * A credential provider declared as abstract, so it cannot be instantiated. */ static abstract
TestS3AAWSCredentialsProvider
java
quarkusio__quarkus
independent-projects/arc/tests/src/test/java/io/quarkus/arc/test/interceptors/targetclass/mixed/AroundInvokeOnTargetClassAndOutsideAndManySuperclassesWithOverridesTest.java
{ "start": 2773, "end": 3011 }
class ____ extends Delta { @AroundInvoke Object specialIntercept(InvocationContext ctx) throws Exception { return "this should not be called as the method is overridden in Charlie"; } } static
Echo
java
google__guice
core/src/com/google/inject/ProvidedBy.java
{ "start": 962, "end": 1077 }
interface ____ { /** The implementation type. */ Class<? extends jakarta.inject.Provider<?>> value(); }
ProvidedBy
java
apache__hadoop
hadoop-yarn-project/hadoop-yarn/hadoop-yarn-applications/hadoop-yarn-applications-distributedshell/src/test/java/org/apache/hadoop/yarn/applications/distributedshell/TestDSSleepingAppMaster.java
{ "start": 936, "end": 2042 }
class ____ extends ApplicationMaster { private static final Logger LOG = LoggerFactory .getLogger(TestDSSleepingAppMaster.class); private static final long SLEEP_TIME = 5000; public static void main(String[] args) { boolean result = false; TestDSSleepingAppMaster appMaster = new TestDSSleepingAppMaster(); try { boolean doRun = appMaster.init(args); if (!doRun) { System.exit(0); } appMaster.run(); if (appMaster.appAttemptID.getAttemptId() <= 2) { try { // sleep some time Thread.sleep(SLEEP_TIME); } catch (InterruptedException e) {} // fail the first am. System.exit(100); } result = appMaster.finish(); } catch (Throwable t) { System.exit(1); } finally { if (appMaster != null) { appMaster.cleanup(); } } if (result) { LOG.info("Application Master completed successfully. exiting"); System.exit(0); } else { LOG.info("Application Master failed. exiting"); System.exit(2); } } }
TestDSSleepingAppMaster
java
elastic__elasticsearch
server/src/main/java/org/elasticsearch/search/aggregations/metrics/InternalMultiValueAggregation.java
{ "start": 859, "end": 1492 }
class ____ extends InternalAggregation implements MultiValueAggregation { protected InternalMultiValueAggregation(String name, Map<String, Object> metadata) { super(name, metadata); } /** * Read from a stream. */ protected InternalMultiValueAggregation(StreamInput in) throws IOException { super(in); } @Override public final SortValue sortValue(AggregationPath.PathElement head, Iterator<AggregationPath.PathElement> tail) { throw new IllegalArgumentException("Metrics aggregations cannot have sub-aggregations (at [>" + head + "]"); } }
InternalMultiValueAggregation
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxDistinct.java
{ "start": 5987, "end": 9421 }
class ____<T, K, C> implements ConditionalSubscriber<T>, InnerOperator<T, T> { final ConditionalSubscriber<? super T> actual; final Context ctx; final C collection; final Function<? super T, ? extends K> keyExtractor; final BiPredicate<C, K> distinctPredicate; final Consumer<C> cleanupCallback; @SuppressWarnings("NotNullFieldNotInitialized") // s initialized in onSubscribe Subscription s; boolean done; DistinctConditionalSubscriber(ConditionalSubscriber<? super T> actual, C collection, Function<? super T, ? extends K> keyExtractor, BiPredicate<C, K> distinctPredicate, Consumer<C> cleanupCallback) { this.actual = actual; this.ctx = actual.currentContext(); this.collection = collection; this.keyExtractor = keyExtractor; this.distinctPredicate = distinctPredicate; this.cleanupCallback = cleanupCallback; } @Override public void onSubscribe(Subscription s) { if (Operators.validate(this.s, s)) { this.s = s; actual.onSubscribe(this); } } @Override public void onNext(T t) { if (done) { Operators.onNextDropped(t, this.ctx); return; } K k; try { k = Objects.requireNonNull(keyExtractor.apply(t), "The distinct extractor returned a null value."); } catch (Throwable e) { onError(Operators.onOperatorError(s, e, t, this.ctx)); Operators.onDiscard(t, this.ctx); return; } boolean b; try { b = distinctPredicate.test(collection, k); } catch (Throwable e) { onError(Operators.onOperatorError(s, e, t, this.ctx)); Operators.onDiscard(t, this.ctx); return; } if (b) { actual.onNext(t); } else { Operators.onDiscard(t, ctx); s.request(1); } } @Override public boolean tryOnNext(T t) { if (done) { Operators.onNextDropped(t, this.ctx); return true; } K k; try { k = Objects.requireNonNull(keyExtractor.apply(t), "The distinct extractor returned a null value."); } catch (Throwable e) { onError(Operators.onOperatorError(s, e, t, this.ctx)); Operators.onDiscard(t, this.ctx); return true; } boolean b; try { b = distinctPredicate.test(collection, k); } catch (Throwable e) { onError(Operators.onOperatorError(s, e, t, this.ctx)); Operators.onDiscard(t, this.ctx); return true; } if (b) { return actual.tryOnNext(t); } else { Operators.onDiscard(t, ctx); return false; } } @Override public void onError(Throwable t) { if (done) { Operators.onErrorDropped(t, this.ctx); return; } done = true; cleanupCallback.accept(collection); actual.onError(t); } @Override public void onComplete() { if (done) { return; } done = true; cleanupCallback.accept(collection); actual.onComplete(); } @Override public CoreSubscriber<? super T> actual() { return actual; } @Override public void request(long n) { s.request(n); } @Override public void cancel() { s.cancel(); if (collection != null) { cleanupCallback.accept(collection); } } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.PARENT) return s; if (key == Attr.TERMINATED) return done; if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return InnerOperator.super.scanUnsafe(key); } } static final
DistinctConditionalSubscriber
java
google__dagger
javatests/dagger/functional/builder/PrivateConstructorsTest.java
{ "start": 1096, "end": 1159 }
interface ____ { String string(); @Component.Builder
C
java
apache__camel
core/camel-core/src/test/java/org/apache/camel/component/file/ConsumerTemplateFileShutdownTest.java
{ "start": 1125, "end": 1710 }
class ____ extends ContextTestSupport { private static final String TEST_FILE_NAME = "hello." + UUID.randomUUID() + ".txt"; @Test public void testConsumerTemplateFile() { template.sendBodyAndHeader(fileUri(), "Hello World", Exchange.FILE_NAME, TEST_FILE_NAME); Exchange exchange = consumer.receive(fileUri("?fileName=" + TEST_FILE_NAME), 5000); assertNotNull(exchange); assertEquals("Hello World", exchange.getIn().getBody(String.class)); consumer.doneUoW(exchange); consumer.stop(); } }
ConsumerTemplateFileShutdownTest
java
apache__camel
components/camel-as2/camel-as2-api/src/main/java/org/apache/camel/component/as2/api/AS2ServerConnection.java
{ "start": 15922, "end": 25909 }
class ____ extends Thread { private final HttpService httpService; private final HttpServerConnection serverConnection; public RequestHandlerThread(HttpService httpService, Socket inSocket) throws IOException { final int bufSize = 8 * 1024; Http1Config cfg = Http1Config.custom().setBufferSize(bufSize).build(); final AS2BHttpServerConnection inConn = new AS2BHttpServerConnection(cfg); LOG.info("Incoming connection from {}", inSocket.getInetAddress()); inConn.bind(inSocket); // TODO Update once baseline is Java 21 // setName(REQUEST_HANDLER_THREAD_NAME_PREFIX + threadId()); setName(REQUEST_HANDLER_THREAD_NAME_PREFIX + getId()); this.httpService = httpService; this.serverConnection = inConn; } @Override public void run() { LOG.info("Processing new AS2 request"); final HttpContext context = new BasicHttpContext(null); try { while (!Thread.interrupted()) { this.httpService.handleRequest(this.serverConnection, context); HttpCoreContext coreContext = HttpCoreContext.adapt(context); // Safely retrieve the AS2 consumer configuration and path from ThreadLocal storage. AS2ConsumerConfiguration config = Optional.ofNullable(CURRENT_CONSUMER_CONFIG.get()) .map(w -> w.config) .orElse(null); String recipientAddress = coreContext.getAttribute(AS2AsynchronousMDNManager.RECIPIENT_ADDRESS, String.class); if (recipientAddress != null && config != null) { // Send the MDN asynchronously. DispositionNotificationMultipartReportEntity multipartReportEntity = coreContext.getAttribute( AS2AsynchronousMDNManager.ASYNCHRONOUS_MDN, DispositionNotificationMultipartReportEntity.class); AS2AsynchronousMDNManager asynchronousMDNManager = new AS2AsynchronousMDNManager( AS2ServerConnection.this.as2Version, AS2ServerConnection.this.originServer, AS2ServerConnection.this.serverFqdn, config.getSigningCertificateChain(), config.getSigningPrivateKey(), AS2ServerConnection.this.userName, AS2ServerConnection.this.password, AS2ServerConnection.this.accessToken); HttpRequest request = coreContext.getAttribute(HttpCoreContext.HTTP_REQUEST, HttpRequest.class); AS2SignedDataGenerator gen = ResponseMDN.createSigningGenerator( request, config.getSigningAlgorithm(), config.getSigningCertificateChain(), config.getSigningPrivateKey()); if (gen != null) { // send a signed MDN MultipartSignedEntity multipartSignedEntity = null; try { multipartSignedEntity = ResponseMDN.prepareSignedReceipt(gen, multipartReportEntity); } catch (Exception e) { LOG.warn("failed to sign MDN"); } if (multipartSignedEntity != null) { asynchronousMDNManager.send( multipartSignedEntity, multipartSignedEntity.getContentType(), recipientAddress); } } else { // send an unsigned MDN asynchronousMDNManager.send(multipartReportEntity, multipartReportEntity.getMainMessageContentType(), recipientAddress); } } } } catch (final ConnectionClosedException ex) { LOG.info("Client closed connection"); } catch (final IOException ex) { LOG.error("I/O error: {}", ex.getMessage()); } catch (final HttpException ex) { LOG.error("Unrecoverable HTTP protocol violation: {}", ex.getMessage(), ex); } finally { try { this.serverConnection.close(); } catch (final IOException ignore) { } } } } public AS2ServerConnection(String as2Version, String originServer, String serverFqdn, Integer serverPortNumber, AS2SignatureAlgorithm signingAlgorithm, Certificate[] signingCertificateChain, PrivateKey signingPrivateKey, PrivateKey decryptingPrivateKey, String mdnMessageTemplate, Certificate[] validateSigningCertificateChain, SSLContext sslContext, String userName, String password, String accessToken) throws IOException { this.as2Version = ObjectHelper.notNull(as2Version, "as2Version"); this.originServer = ObjectHelper.notNull(originServer, "userAgent"); this.serverFqdn = ObjectHelper.notNull(serverFqdn, "serverFqdn"); final Integer parserServerPortNumber = ObjectHelper.notNull(serverPortNumber, "serverPortNumber"); this.userName = userName; this.password = password; this.accessToken = accessToken; // Create and register a default consumer configuration for the root path ('/'). // This ensures that all incoming requests have a fallback configuration for decryption // and MDN signing, even if they don't match a specific Camel route path. AS2ServerConnection.AS2ConsumerConfiguration consumerConfig = new AS2ServerConnection.AS2ConsumerConfiguration( signingAlgorithm, signingCertificateChain, signingPrivateKey, decryptingPrivateKey, validateSigningCertificateChain); registerConsumerConfiguration("/", consumerConfig); listenerService = new RequestListenerService( this.as2Version, this.originServer, this.serverFqdn, mdnMessageTemplate); acceptorThread = new RequestAcceptorThread(parserServerPortNumber, sslContext, listenerService); acceptorThread.setDaemon(true); acceptorThread.start(); } public Certificate[] getValidateSigningCertificateChain() { return Optional.ofNullable(CURRENT_CONSUMER_CONFIG.get()) .map(w -> w.config.getValidateSigningCertificateChain()) .orElse(null); } public PrivateKey getSigningPrivateKey() { return Optional.ofNullable(CURRENT_CONSUMER_CONFIG.get()) .map(w -> w.config.getSigningPrivateKey()) .orElse(null); } public PrivateKey getDecryptingPrivateKey() { return Optional.ofNullable(CURRENT_CONSUMER_CONFIG.get()) .map(w -> w.config.getDecryptingPrivateKey()) .orElse(null); } public void registerConsumerConfiguration(String path, AS2ConsumerConfiguration config) { consumerConfigurations.put(path, config); } public void close() { if (acceptorThread != null) { lock.lock(); try { try { // 3. Close the shared ServerSocket if (serversocket != null) { serversocket.close(); } } catch (IOException e) { LOG.debug(e.getMessage(), e); } finally { acceptorThread = null; listenerService = null; } } finally { lock.unlock(); } } } public void listen(String requestUri, HttpRequestHandler handler) { if (listenerService != null) { lock.lock(); try { listenerService.registerHandler(requestUri, handler); } finally { lock.unlock(); } } } public void unlisten(String requestUri) { if (listenerService != null) { lock.lock(); try { listenerService.unregisterHandler(requestUri); consumerConfigurations.remove(requestUri); } finally { lock.unlock(); } } } protected HttpProcessor initProtocolProcessor( String as2Version, String originServer, String serverFqdn, String mdnMessageTemplate) { return HttpProcessorBuilder.create() .addFirst(new AS2ConsumerConfigInterceptor()) // Sets up the request-specific keys and certificates in the HttpContext .add(new ResponseContent(true)) .add(new ResponseServer(originServer)) .add(new ResponseDate()) .add(new ResponseConnControl()) .add(new ResponseMDN(as2Version, serverFqdn, mdnMessageTemplate)) .build(); } }
RequestHandlerThread
java
apache__hadoop
hadoop-tools/hadoop-aws/src/main/java/org/apache/hadoop/fs/s3a/impl/EncryptionS3ClientFactory.java
{ "start": 2085, "end": 2783 }
class ____. * value: {@value} */ private static final String ENCRYPTION_CLIENT_CLASSNAME = "software.amazon.encryption.s3.S3EncryptionClient"; /** * Encryption client availability. */ private static final LazyAtomicReference<Boolean> ENCRYPTION_CLIENT_AVAILABLE = LazyAtomicReference.lazyAtomicReferenceFromSupplier( EncryptionS3ClientFactory::checkForEncryptionClient ); /** * S3Client to be wrapped by encryption client. */ private S3Client s3Client; /** * S3AsyncClient to be wrapped by encryption client. */ private S3AsyncClient s3AsyncClient; /** * Checks if {@link #ENCRYPTION_CLIENT_CLASSNAME} is available in the
name
java
hibernate__hibernate-orm
hibernate-core/src/test/java/org/hibernate/orm/test/unionsubclass/Location.java
{ "start": 235, "end": 1054 }
class ____ { private long id; private String name; private Collection beings = new ArrayList(); Location() {} public Location(String name) { this.name = name; } public void addBeing(Being b) { b.setLocation(this); beings.add(b); } /** * @return Returns the id. */ public long getId() { return id; } /** * @param id The id to set. */ public void setId(long id) { this.id = id; } /** * @return Returns the name. */ public String getName() { return name; } /** * @param name The name to set. */ public void setName(String name) { this.name = name; } /** * @return Returns the beings. */ public Collection getBeings() { return beings; } /** * @param beings The beings to set. */ public void setBeings(Collection beings) { this.beings = beings; } }
Location
java
apache__flink
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/calcite/FlinkCalciteSqlValidator.java
{ "start": 20399, "end": 24881 }
class ____ extends SqlSelect { private final List<SqlIdentifier> descriptors; public ExplicitTableSqlSelect(SqlIdentifier table, List<SqlIdentifier> descriptors) { super( SqlParserPos.ZERO, null, SqlNodeList.of(SqlIdentifier.star(SqlParserPos.ZERO)), table, null, null, null, null, null, null, null, null); this.descriptors = descriptors; } } /** * Returns whether the given column has been declared in a {@link SqlKind#DESCRIPTOR} next to a * {@link SqlKind#EXPLICIT_TABLE} within TVF operands. */ private static boolean declaredDescriptorColumn(SelectScope scope, Column column) { if (!(scope.getNode() instanceof ExplicitTableSqlSelect)) { return false; } final ExplicitTableSqlSelect select = (ExplicitTableSqlSelect) scope.getNode(); return select.descriptors.stream() .map(SqlIdentifier::getSimple) .anyMatch(id -> id.equals(column.getName())); } /** * Returns all {@link SqlKind#EXPLICIT_TABLE} and {@link SqlKind#SET_SEMANTICS_TABLE} operands * within TVF operands. A list entry is {@code null} if the operand is not an {@link * SqlKind#EXPLICIT_TABLE} or {@link SqlKind#SET_SEMANTICS_TABLE}. */ private static List<SqlIdentifier> getTableOperands(SqlNode node) { if (!(node instanceof SqlBasicCall)) { return null; } final SqlBasicCall call = (SqlBasicCall) node; if (!(call.getOperator() instanceof SqlFunction)) { return null; } final SqlFunction function = (SqlFunction) call.getOperator(); if (!isTableFunction(function)) { return null; } return call.getOperandList().stream() .map(FlinkCalciteSqlValidator::extractTableOperand) .collect(Collectors.toList()); } private static @Nullable SqlIdentifier extractTableOperand(SqlNode op) { if (op.getKind() == SqlKind.EXPLICIT_TABLE) { final SqlBasicCall opCall = (SqlBasicCall) op; if (opCall.operandCount() == 1 && opCall.operand(0) instanceof SqlIdentifier) { // for TUMBLE(TABLE t3, ...) return opCall.operand(0); } } else if (op.getKind() == SqlKind.SET_SEMANTICS_TABLE) { // for SESSION windows final SqlBasicCall opCall = (SqlBasicCall) op; final SqlCall setSemanticsTable = opCall.operand(0); if (setSemanticsTable.operand(0) instanceof SqlIdentifier) { return setSemanticsTable.operand(0); } } else if (op.getKind() == SqlKind.ARGUMENT_ASSIGNMENT) { // for TUMBLE(DATA => TABLE t3, ...) final SqlBasicCall opCall = (SqlBasicCall) op; return extractTableOperand(opCall.operand(0)); } return null; } private static Stream<SqlIdentifier> extractDescriptors(SqlNode op) { if (op.getKind() == SqlKind.DESCRIPTOR) { // for TUMBLE(..., DESCRIPTOR(col), ...) final SqlBasicCall opCall = (SqlBasicCall) op; return opCall.getOperandList().stream() .filter(SqlIdentifier.class::isInstance) .map(SqlIdentifier.class::cast); } else if (op.getKind() == SqlKind.SET_SEMANTICS_TABLE) { // for SESSION windows final SqlBasicCall opCall = (SqlBasicCall) op; return ((SqlNodeList) opCall.operand(1)) .stream() .filter(SqlIdentifier.class::isInstance) .map(SqlIdentifier.class::cast); } else if (op.getKind() == SqlKind.ARGUMENT_ASSIGNMENT) { // for TUMBLE(..., TIMECOL => DESCRIPTOR(col), ...) final SqlBasicCall opCall = (SqlBasicCall) op; return extractDescriptors(opCall.operand(0)); } return Stream.empty(); } private static boolean isTableFunction(SqlFunction function) { return function instanceof SqlTableFunction || function.getFunctionType() == SqlFunctionCategory.USER_DEFINED_TABLE_FUNCTION; } }
ExplicitTableSqlSelect
java
micronaut-projects__micronaut-core
inject-java/src/test/groovy/io/micronaut/inject/configproperties/inheritance/AbstractConfig.java
{ "start": 118, "end": 686 }
class ____ { @NotNull private final String value; @NotNull private String notThing; public AbstractConfig(@NotNull String value) { this.value = value; this.notThing = "def notThing"; } @NotNull public final String getValue() { return this.value; } @NotNull public final String getNotThing() { return this.notThing; } public final void setNotThing(@NotNull String notThing) { this.notThing = notThing; } @NotNull public abstract String getThing(); }
AbstractConfig
java
reactor__reactor-core
reactor-core/src/main/java/reactor/core/publisher/FluxWindowPredicate.java
{ "start": 2459, "end": 3903 }
class ____<T> extends InternalFluxOperator<T, Flux<T>> implements Fuseable{ final Supplier<? extends Queue<T>> groupQueueSupplier; final Supplier<? extends Queue<Flux<T>>> mainQueueSupplier; final Mode mode; final Predicate<? super T> predicate; final int prefetch; FluxWindowPredicate(Flux<? extends T> source, Supplier<? extends Queue<Flux<T>>> mainQueueSupplier, Supplier<? extends Queue<T>> groupQueueSupplier, int prefetch, Predicate<? super T> predicate, Mode mode) { super(Flux.from(source)); if (prefetch <= 0) { throw new IllegalArgumentException("prefetch > 0 required but it was " + prefetch); } this.predicate = Objects.requireNonNull(predicate, "predicate"); this.mainQueueSupplier = Objects.requireNonNull(mainQueueSupplier, "mainQueueSupplier"); this.groupQueueSupplier = Objects.requireNonNull(groupQueueSupplier, "groupQueueSupplier"); this.mode = mode; this.prefetch = prefetch; } @Override public CoreSubscriber<? super T> subscribeOrReturn(CoreSubscriber<? super Flux<T>> actual) { return new WindowPredicateMain<>(actual, mainQueueSupplier.get(), groupQueueSupplier, prefetch, predicate, mode); } @Override public int getPrefetch() { return prefetch; } @Override public @Nullable Object scanUnsafe(Attr key) { if (key == Attr.RUN_STYLE) return Attr.RunStyle.SYNC; return super.scanUnsafe(key); } static final
FluxWindowPredicate
java
micronaut-projects__micronaut-core
inject-groovy/src/main/groovy/io/micronaut/ast/groovy/scan/Attribute.java
{ "start": 1599, "end": 1641 }
class ____. * * @param cr the
reader
java
ReactiveX__RxJava
src/test/java/io/reactivex/rxjava3/internal/jdk8/ObservableFromOptionalTest.java
{ "start": 746, "end": 1073 }
class ____ extends RxJavaTest { @Test public void hasValue() { Observable.fromOptional(Optional.of(1)) .test() .assertResult(1); } @Test public void empty() { Observable.fromOptional(Optional.empty()) .test() .assertResult(); } }
ObservableFromOptionalTest
java
quarkusio__quarkus
extensions/micrometer/deployment/src/test/java/io/quarkus/micrometer/deployment/binder/VertxTcpMetricsNoClientMetricsTest.java
{ "start": 3570, "end": 4334 }
class ____ { @Inject Vertx vertx; private NetSocket client; private BlockingQueue<String> queue = new ArrayBlockingQueue<>(1); @PostConstruct public void init() { // Do not pass a name so the metrics clients are not reported. client = vertx.createNetClient() .connect(8888, "localhost") .await().indefinitely(); client.handler(buffer -> queue.offer(buffer.toString())); } public String sendAndAwait(String message) throws InterruptedException { client.writeAndAwait(message); return queue.take(); } public void quit() { client.closeAndAwait(); } } }
NetClient